text
stringlengths
10
2.72M
package com.tencent.mm.plugin.honey_pay.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.honey_pay.ui.HoneyPayCheckPwdUI.2; class HoneyPayCheckPwdUI$2$1 implements OnClickListener { final /* synthetic */ 2 klf; HoneyPayCheckPwdUI$2$1(2 2) { this.klf = 2; } public final void onClick(DialogInterface dialogInterface, int i) { HoneyPayCheckPwdUI.d(this.klf.kld); } }
package com.top.demo.modules.mapper; import com.top.demo.modules.pojo.RolePermissionDO; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 角色资源表 Mapper 接口 * </p> * * @author lth * @since 2019-10-17 */ public interface RolePermissionMapper extends BaseMapper<RolePermissionDO> { }
package com.espendwise.manta.model.view; // Generated by Hibernate Tools import com.espendwise.manta.model.ValueObject; /** * CountryView generated by hbm2java */ public class CountryView extends ValueObject implements java.io.Serializable { private static final long serialVersionUID = -1; public static final String COUNTRY_ID = "countryId"; public static final String SHORT_DESC = "shortDesc"; public static final String UI_NAME = "uiName"; public static final String COUNTRY_CODE = "countryCode"; public static final String LOCALE_CD = "localeCd"; public static final String INPUT_DATE_FORMAT = "inputDateFormat"; public static final String INPUT_TIME_FORMAT = "inputTimeFormat"; public static final String USES_STATE = "usesState"; private Long countryId; private String shortDesc; private String uiName; private String countryCode; private String localeCd; private String inputDateFormat; private String inputTimeFormat; private String usesState; public CountryView() { } public CountryView(Long countryId) { this.setCountryId(countryId); } public CountryView(Long countryId, String shortDesc, String uiName, String countryCode, String localeCd, String inputDateFormat, String inputTimeFormat, String usesState) { this.setCountryId(countryId); this.setShortDesc(shortDesc); this.setUiName(uiName); this.setCountryCode(countryCode); this.setLocaleCd(localeCd); this.setInputDateFormat(inputDateFormat); this.setInputTimeFormat(inputTimeFormat); this.setUsesState(usesState); } public Long getCountryId() { return this.countryId; } public void setCountryId(Long countryId) { this.countryId = countryId; setDirty(true); } public String getShortDesc() { return this.shortDesc; } public void setShortDesc(String shortDesc) { this.shortDesc = shortDesc; setDirty(true); } public String getUiName() { return this.uiName; } public void setUiName(String uiName) { this.uiName = uiName; setDirty(true); } public String getCountryCode() { return this.countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; setDirty(true); } public String getLocaleCd() { return this.localeCd; } public void setLocaleCd(String localeCd) { this.localeCd = localeCd; setDirty(true); } public String getInputDateFormat() { return this.inputDateFormat; } public void setInputDateFormat(String inputDateFormat) { this.inputDateFormat = inputDateFormat; setDirty(true); } public String getInputTimeFormat() { return this.inputTimeFormat; } public void setInputTimeFormat(String inputTimeFormat) { this.inputTimeFormat = inputTimeFormat; setDirty(true); } public String getUsesState() { return this.usesState; } public void setUsesState(String usesState) { this.usesState = usesState; setDirty(true); } }
package com.jetplanestechbrains.sithtranslator; import org.json.JSONObject; /** "contents": { "translated": "Nu went kia coruscant which meo ten parsekas salini!", "text": "I went to coruscant which was ten parsec away!", "translation": "sith" } } */ public class Translation { private String translated; private String text; public String getTranslated() { return translated; } public void setTranslated(String translated) { this.translated = translated; } public String getText() { return text; } public void setText(String text) { this.text = text; } public void setFields(JSONObject jsonObject) { translated = jsonObject.optString("translated"); text = jsonObject.optString("text"); } }
package lesson3.begginer; /** * Created by Angelina on 21.01.2017. */ public class Task8 { public static void main(String[] args) { System.out.println("Given a string and an int n. Return a string made of the first n characters of the string, followed \n" + "by the first n-1 characters of the string, and so on. Example:\n" + "yourMethod(\"Testing\", 4) → \"TestTesTeT\"\n" + "yourMethod(\"Testing\", 3) → \"TesTeT\"\n" + "yourMethod(\"Testing\", 2) → \"TeT“\n"); Task8 t8 = new Task8(); t8.firstCharStr(); } public void firstCharStr(){ int n=5; String a="Testing"; System.out.println("Your initial string - "+a); for(int i=n; n>0; n--) { System.out.print(a.substring(0, n)); } System.out.println(" - your result"); } }
package id.co.imastudio.praditaapps; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //kenalin Button ya; Button tidak; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //hubungin ya = findViewById(R.id.btnYa); tidak = findViewById(R.id.btnTidak); //ngapain ya.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //panggil toast Toast.makeText(MainActivity.this, "Ini pesan Ya", Toast.LENGTH_SHORT).show(); } }); tidak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Intent Intent pindah = new Intent(MainActivity.this, MenuActivity.class); startActivity(pindah); } }); } }
package arrayexer; import java.util.Scanner; /*从键盘读入学生成绩,找出最高分 * 并输出学生成绩等级。 * 成绩>=最高分-10 等级为‘A’ * 成绩>=最高分-20 等级为‘B’ * 成绩>=最高分-30 等级为‘C’ * 其余 等级为‘D’ * 提示:先读入学生人数,根据人数创建int数组, * 存放学生成绩。 * 输出样式:student 0 score is 56 grade is D */ public class ArrExer { public static void main(String[] args) { //1.使用Scanner,读取学生个数 Scanner scan = new Scanner(System.in); System.out.print("请输入学生人数:"); int number = scan.nextInt(); //2.创建数组,来存储学生成绩:动态初始化 int[] scores = new int[number]; //3.给数组中的元素赋值 int max = 0; for (int i = 0; i < scores.length; i++) { System.out.print("请输入学生成绩:"); scores[i] = scan.nextInt(); //4.获取数组中的元素的最大值:最高分 if (max < scores[i]) { max = scores[i]; } } //5.根据每个学生成绩与最高分的差值,得到每个学生的等级,并输出等级和成绩。 for (int i = 0; i < scores.length; i++) { if ((max - scores[i]) <= 10){ System.out.println("student " + i + " scores " + scores[i] + " grade is " + "A"); }else if((max - scores[i]) <= 20){ System.out.println("student " + i + " scores " + scores[i] + " grade is " + "B"); }else if((max - scores[i]) <= 30){ System.out.println("student " + i + " scores " + scores[i] + " grade is " + "C"); }else { System.out.println("student " + i + " scores " + scores[i] + " grade is " + "D"); } } scan.close(); } }
int main() { int[] a1; a1 = new int[-1]; return 0; }
package com.tencent.mm.plugin.wenote.model.nativenote.spans; import com.tencent.mm.plugin.wenote.model.nativenote.manager.WXRTEditText; import java.util.ArrayList; public final class u { public static final ArrayList<t> qtA; public static final b qtv = new b(); public static final j qtw = new j(); public static final c qtx = new c(); public static final l qty = new l(); public static final h qtz = new h(); static { ArrayList arrayList = new ArrayList(); qtA = arrayList; arrayList.add(qtv); qtA.add(qtx); qtA.add(qty); qtA.add(qtw); } public static void a(WXRTEditText wXRTEditText, t... tVarArr) { a(wXRTEditText, qtz, tVarArr); a(wXRTEditText, qtx, tVarArr); a(wXRTEditText, qty, tVarArr); a(wXRTEditText, qtw, tVarArr); } private static void a(WXRTEditText wXRTEditText, o oVar, t... tVarArr) { int length = tVarArr.length; int i = 0; while (i < length) { if (oVar != tVarArr[i]) { i++; } else { return; } } oVar.a(wXRTEditText, null, null); } }
package cn.bs.zjzc.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.gson.Gson; import java.util.List; import cn.bs.zjzc.R; import cn.bs.zjzc.base.BaseNormalAdapter; import cn.bs.zjzc.model.response.HistoryAddressResponse; import cn.bs.zjzc.util.DBUtils; /** * 地址历史记录 * Created by mgc on 2016/7/4. */ public class HistroyAddressAdapter extends BaseNormalAdapter<HistoryAddressResponse.Data> { private DBUtils db; public HistroyAddressAdapter(Context context, DBUtils db, List<HistoryAddressResponse.Data> datas) { super(context, datas); this.db = db; } @Override public View builderItemView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_history_record_list, parent, false); holder.name = (TextView) convertView.findViewById(R.id.name); holder.phone_number = (TextView) convertView.findViewById(R.id.phone_number); holder.address_detail = (TextView) convertView.findViewById(R.id.order_detail_address_take); holder.btn_delete = (ImageView) convertView.findViewById(R.id.btn_delete); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.name.setText(mDatas.get(position).name); holder.phone_number.setText(mDatas.get(position).phone); holder.address_detail.setText(mDatas.get(position).address); holder.btn_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { db.deleteOneData("'" + new Gson().toJson(mDatas.get(position)) + "'"); mDatas.remove(position); notifyDataSetChanged(); } }); return convertView; } class ViewHolder { public TextView name, phone_number, address_detail; public ImageView btn_delete; } }
package com.atn.app.database.handler; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Environment; import android.text.TextUtils; import com.atn.app.AtnApp; import com.atn.app.datamodels.AtnOfferData; import com.atn.app.datamodels.AtnPromotion; import com.atn.app.datamodels.AtnPromotion.PromotionType; import com.atn.app.datamodels.AtnRegisteredVenueData; import com.atn.app.datamodels.UserDetail; import com.atn.app.datamodels.VenueModel; import com.atn.app.pool.UserDataPool; import com.atn.app.provider.Atn; import com.atn.app.utils.AtnUtils; import com.atn.app.utils.SharedPrefUtils; /** * Creates a helper class that interacts with the database to perform all the * required database related operations. You should use only this class to do * all the database related operations. */ public class DbHandler { static final String DB_NAME = "ATN_DB"; private static final int DB_VERSION = 2;//last 1 at 1.3 protected static String DROP_TABLE_COMMAND = "DROP TABLE IF EXISTS "; private static DbHandler instance = null; private static final String TRUE = "1"; private DatabaseHelper mOpenHelper; /** * Returns instance of the database helper to perform database related * operations. * * @return DbHandler instance */ public static DbHandler getInstance() { if (instance == null) { instance = new DbHandler(); } return instance; } private DbHandler() { mOpenHelper = new DatabaseHelper(AtnApp.getAppContext()); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } /** * * Creates the underlying database with table name and column names * taken from the NotePad class. * */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(UserTable.create_user_table); db.execSQL(BusinessTable.create_business_table); db.execSQL(PromotionTable.create_promotion_table); db.execSQL(LoginTable.CREATE_TABLE); } /** * * Demonstrates that the provider must consider what happens when the * underlying datastore is changed. In this sample, the database is * upgraded the database by destroying the existing data. A real * application should upgrade the database in place. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DROP_TABLE_COMMAND + UserTable.USER_TABLE); db.execSQL(DROP_TABLE_COMMAND + BusinessTable.BUSINESS_TABLE); db.execSQL(DROP_TABLE_COMMAND + PromotionTable.PROMOTION_TABLE); db.execSQL(DROP_TABLE_COMMAND + LoginTable.TABLE_NAME); onCreate(db); SharedPrefUtils.clearAll(AtnApp.getAppContext()); } } private SQLiteDatabase getWritableDatabase() { return mOpenHelper.getWritableDatabase(); } private SQLiteDatabase getReadableDatabase() { return mOpenHelper.getReadableDatabase(); } /** * Insert user details in database. * * @param userDetail * to add in database. */ public void addUserDetail(UserDetail userDetail) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(UserTable.COL_USER_CREATED, userDetail.getUserCreated()); values.put(UserTable.COL_USER_DOB, userDetail.getUserDob()); values.put(UserTable.COL_USER_EMAIL, userDetail.getUserEmail()); values.put(UserTable.COL_USER_FB_ACCESS_TOKEN,userDetail.getUserFbToken()); values.put(UserTable.COL_USER_FB_LINK, userDetail.getUserFbLink()); values.put(UserTable.COL_USER_FB_UID, userDetail.getUserFbUid()); values.put(UserTable.COL_USER_FIRST_NAME, userDetail.getUserFirstName()); values.put(UserTable.COL_USER_GENDER, userDetail.getUserGender()); values.put(UserTable.COL_USER_ID, userDetail.getUserId()); values.put(UserTable.COL_USER_MANNUAL_LOGIN, userDetail.isUserManualLogin()); values.put(UserTable.COL_USER_LAST_NAME, userDetail.getUserLastName()); values.put(UserTable.COL_USER_LOCATION, userDetail.getUserLocation()); values.put(UserTable.COL_USER_MODIFIED, userDetail.getUserModified()); values.put(UserTable.COL_USER_POINTS, userDetail.getUserPoints()); values.put(UserTable.COL_USER_NAME, userDetail.getUserName()); db.insert(UserTable.USER_TABLE, null, values); } /** * Returns user details of specified user id. * * @param userId * to get user details. * @return User details. */ public UserDetail getUserDetail(String userId) { if (userId == null) { return null; } UserDetail userDetail = new UserDetail(); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(UserTable.USER_TABLE, null, UserTable.COL_USER_ID + " =?", new String[] { userId }, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); userDetail.setUserCreated(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_CREATED))); userDetail.setUserDob(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_DOB))); userDetail.setUserEmail(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_EMAIL))); userDetail.setUserFbToken(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_FB_ACCESS_TOKEN))); userDetail.setUserFbLink(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_FB_LINK))); userDetail.setUserFbUid(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_FB_UID))); userDetail.setUserFirstName(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_FIRST_NAME))); userDetail.setUserGender(cursor.getInt(cursor.getColumnIndex(LoginTable.COL_USER_GENDER))); userDetail.setUserId(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_ID))); userDetail.setUserLastName(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_LAST_NAME))); userDetail.setUserLocation(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_LOCATION))); userDetail.setUserModified(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_MODIFIED))); userDetail.setUserPoints(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_POINTS))); userDetail.setUserName(cursor.getString(cursor.getColumnIndex(UserTable.COL_USER_NAME))); } return userDetail; } /** * Inserts user details in database when user login. * * @param userDetail * to insert in database. */ public void loginUser(UserDetail userDetail) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(LoginTable.COL_USER_ID, userDetail.getUserId()); values.put(LoginTable.COL_USER_NAME, userDetail.getUserName()); values.put(LoginTable.COL_USER_EMAIL, userDetail.getUserEmail()); values.put(LoginTable.COL_USER_ADDRESS, userDetail.getUserLocation()); values.put(LoginTable.COL_USER_PASSWORD, userDetail.getUserPassword()); values.put(LoginTable.COL_USER_PIC, userDetail.getImageUrl()); values.put(LoginTable.COL_USER_GENDER, userDetail.getUserGender()); int rowUpadted = db.update(LoginTable.TABLE_NAME, values, LoginTable.COL_USER_ID+" = ?", new String[]{userDetail.getUserId()}); if(rowUpadted<=0){ long rowId = db.insert(LoginTable.TABLE_NAME, null, values); if(rowId<0){ AtnUtils.log("Error Occured in insert user object"); } UserDataPool.getInstance().setUserLoggedIn(true); } } /** * Removes user details from database when user log out. * * @param userId * to remove user details. */ public void logoutUser(String userId) { SQLiteDatabase db = getWritableDatabase(); db.delete(LoginTable.TABLE_NAME, LoginTable.COL_USER_ID + "=?", new String[] { userId }); } /** * Returns the currently logged-in user details from database. */ public UserDetail getLoggedInUser() { SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(LoginTable.TABLE_NAME, null, null, null, null,null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); UserDetail userDetail = new UserDetail(); userDetail.setUserId(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_ID))); userDetail.setUserName(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_NAME))); userDetail.setUserPassword(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_PASSWORD))); userDetail.setUserEmail(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_EMAIL))); userDetail.setUserLocation(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_ADDRESS))); userDetail.setImageUrl(cursor.getString(cursor.getColumnIndex(LoginTable.COL_USER_PIC))); userDetail.setUserGender(cursor.getInt(cursor.getColumnIndex(LoginTable.COL_USER_GENDER))); cursor.close(); return userDetail; } if(cursor!=null){cursor.close();}; return null; } public synchronized void deleteBusinessBar(String businessId) { SQLiteDatabase db = getWritableDatabase(); db.delete(PromotionTable.PROMOTION_TABLE, PromotionTable.COL_PROMOTION_BUSINESS_ID + " IS ?", new String[] { businessId }); } public synchronized void deleteBusinessBar() { SQLiteDatabase db = getWritableDatabase(); db.delete(PromotionTable.PROMOTION_TABLE, PromotionTable.COL_PROMOTION_ACCEPTED + " IS NOT ?", new String[] { TRUE }); } public synchronized void deletePromotionsBar() { SQLiteDatabase db = getWritableDatabase(); db.delete(PromotionTable.PROMOTION_TABLE, PromotionTable.COL_PROMOTION_ACCEPTED + " IS ?", new String[] { TRUE }); } public synchronized void insertOrUpdate(ContentValues values) { AtnRegisteredVenueData atnBar = getAtnBusinessDetail(values.getAsString(BusinessTable.COL_BUSINESS_ID)); String newFsId = ""; if(values.containsKey(BusinessTable.COL_BUSINESS_FS_LINK_ID)) { newFsId = values.getAsString(BusinessTable.COL_BUSINESS_FS_LINK_ID); } if(atnBar!=null&&!TextUtils.isEmpty(atnBar.getBusinessFoursquareVenueId())&&!newFsId.equals(atnBar.getBusinessFoursquareVenueId())) { ContentValues value = new ContentValues(); value.put(Atn.Venue.VENUE_ID, atnBar.getBusinessFoursquareVenueId()); value.put(Atn.Venue.FOLLOWED, VenueModel.NON_ATN_BAR); Atn.Venue.update(value, AtnApp.getAppContext()); } SQLiteDatabase db = getWritableDatabase(); int rowId = db.update(BusinessTable.BUSINESS_TABLE, values, BusinessTable.COL_BUSINESS_ID + " = ? ", new String[] { values.getAsString(BusinessTable.COL_BUSINESS_ID) }); if(rowId==0){ db.insert(BusinessTable.BUSINESS_TABLE, null, values); } } /** * Inserts bulk favorite business details in database. This is used by * following tab to add favorite business in database that is recevied from * web service response. * * @param userId * @param venueList * list of business to add in database. */ public synchronized void addBulkBusinessDetail(String userId, ArrayList<AtnRegisteredVenueData> venueList) { for (AtnRegisteredVenueData venueData : venueList) { this.addBusinessDetail(venueData); } } /** * Add favorite business detail. * * @param userId to add corresponding business details. * @param venueData to add in database. */ public synchronized void addBusinessDetail(AtnRegisteredVenueData venueData) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(BusinessTable.COL_BUSINESS_CITY, venueData.getBusinessCity()); values.put(BusinessTable.COL_BUSINESS_CREATED,venueData.getBusinessCreated()); values.put(BusinessTable.COL_BUSINESS_FAVORITED,venueData.isFavorited()); values.put(BusinessTable.COL_BUSINESS_FB_LINK,venueData.getBusinessFacebookLink()); values.put(BusinessTable.COL_BUSINESS_FB_LINK_ID,venueData.getBusinessFacebookLinkId()); values.put(BusinessTable.COL_BUSINESS_FS_LINK,venueData.getBusinessFoursquareVenueLink()); values.put(BusinessTable.COL_BUSINESS_FS_LINK_ID,venueData.getBusinessFoursquareVenueId()); values.put(BusinessTable.COL_BUSINESS_ID, venueData.getBusinessId()); values.put(BusinessTable.COL_BUSINESS_LAT, venueData.getBusinessLat()); values.put(BusinessTable.COL_BUSINESS_LOGO,venueData.getBusinessImageUrl()); values.put(BusinessTable.COL_BUSINESS_LON, venueData.getBusinessLng()); values.put(BusinessTable.COL_BUSINESS_MODIFIED,venueData.getBusinessModified()); values.put(BusinessTable.COL_BUSINESS_NAME, venueData.getBusinessName()); values.put(BusinessTable.COL_BUSINESS_PHONE,venueData.getBusinessPhone()); values.put(BusinessTable.COL_BUSINESS_SHARED,venueData.getBusinessShared()); values.put(BusinessTable.COL_BUSINESS_STATE,venueData.getBusinessState()); values.put(BusinessTable.COL_BUSINESS_STATUS,venueData.getBusinessStatus()); values.put(BusinessTable.COL_BUSINESS_STREET,venueData.getBusinessStreet()); values.put(BusinessTable.COL_BUSINESS_SUBSCRIBED,venueData.isSubscribed()); values.put(BusinessTable.COL_BUSINESS_ZIP, venueData.getBusinessZip()); values.put(BusinessTable.COL_IS_REGISTERED,venueData.isRegisterdVenue()); values.put(BusinessTable.COL_BUSINESS_FS_CAT_ID,venueData.getVenueCategoryId()); int count = db.update(BusinessTable.BUSINESS_TABLE, values, BusinessTable.COL_BUSINESS_ID+" = ? ", new String[]{venueData.getBusinessId()}); if(count==0){ db.insert(BusinessTable.BUSINESS_TABLE, null, values); } for (int i = 0; i < venueData.getBulkPromotion().size(); i++){ addPromotionDetail(venueData.getPromotion(i)); } } public synchronized void updateBusinessFavoriteStatus(String businessId, boolean value) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(BusinessTable.COL_BUSINESS_ID, businessId); values.put(BusinessTable.COL_BUSINESS_FAVORITED, value); db.update(BusinessTable.BUSINESS_TABLE, values, BusinessTable.COL_BUSINESS_ID + " = ?", new String[] { businessId }); } /** * Returns all the Atn venue data saved in database. * * @return list of registered Atn venues. */ public synchronized ArrayList<AtnOfferData> getBulkVenueDetails(boolean isAccepted) { ArrayList<AtnOfferData> atnVenueList = new ArrayList<AtnOfferData>(); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(BusinessTable.BUSINESS_TABLE, null, null,null, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { AtnRegisteredVenueData venueData = new AtnRegisteredVenueData(); venueData.setBusinessCity(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_CITY))); venueData.setBusinessFacebookLink(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK))); venueData.setBusinessFacebookLinkId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK_ID))); venueData.setBusinessFoursquareVenueId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK_ID))); venueData.setBusinessFoursquareVenueLink(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK))); venueData.setBusinessId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_ID))); venueData.setBusinessImageUrl(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LOGO))); venueData.setBusinessLat(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LAT))); venueData.setBusinessLng(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LON))); venueData.setBusinessModified(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_MODIFIED))); venueData.setBusinessName(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_NAME))); venueData.setBusinessPhone(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_PHONE))); venueData.setBusinessShared(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_SHARED))); venueData.setBusinessState(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STATE))); venueData.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STATUS))); venueData.setBusinessStreet(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STREET))); venueData.setBusinessZip(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_ZIP))); venueData.setVenueCategoryId(cursor.getInt(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_CAT_ID))); if (cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FAVORITED)).equalsIgnoreCase(TRUE)) venueData.setFavorited(true); else venueData.setFavorited(false); if (cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_SUBSCRIBED)).equalsIgnoreCase(TRUE)) venueData.setSubscribed(true); else venueData.setSubscribed(false); if (cursor.getString( cursor.getColumnIndex(BusinessTable.COL_IS_REGISTERED)) .equalsIgnoreCase(TRUE)) venueData.setRegisterdVenue(true); else venueData.setRegisterdVenue(false); if (isAccepted) { List<AtnPromotion> listPro = getBulkPromotionDetail(venueData.getBusinessId(), isAccepted); if (listPro != null && listPro.size() > 0) { venueData.addBulkPromotion((ArrayList<AtnPromotion>) listPro); atnVenueList.add(venueData); } } else { venueData.addBulkPromotion(getBulkPromotionDetail(venueData.getBusinessId(), isAccepted)); atnVenueList.add(venueData); } } while (cursor.moveToNext()); } if(cursor!=null){cursor.close();}; return atnVenueList; } /** * Returns all user's favorite businesses * * @return */ public synchronized ArrayList<AtnOfferData> getBulkFavoriteVenueDetails() { ArrayList<AtnOfferData> atnVenueList = new ArrayList<AtnOfferData>(); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(BusinessTable.BUSINESS_TABLE, null, BusinessTable.COL_BUSINESS_FAVORITED+" = ?", new String[]{TRUE}, null, null, null); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { AtnRegisteredVenueData venueData = new AtnRegisteredVenueData(); venueData.setFavorited(true); venueData.setBusinessCity(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_CITY))); venueData.setBusinessFacebookLink(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK))); venueData.setBusinessFacebookLinkId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK_ID))); venueData.setBusinessFoursquareVenueId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK_ID))); venueData.setBusinessFoursquareVenueLink(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK))); venueData.setBusinessId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_ID))); venueData.setBusinessImageUrl(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LOGO))); venueData.setBusinessLat(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LAT))); venueData.setBusinessLng(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_LON))); venueData.setBusinessModified(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_MODIFIED))); venueData.setBusinessName(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_NAME))); venueData.setBusinessPhone(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_PHONE))); venueData.setBusinessShared(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_SHARED))); venueData.setBusinessState(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STATE))); venueData.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STATUS))); venueData.setBusinessStreet(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_STREET))); venueData.setBusinessZip(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_ZIP))); venueData.setVenueCategoryId(cursor.getInt(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_CAT_ID))); if(!TextUtils.isEmpty(venueData.getBusinessFoursquareVenueId())){ venueData.setFsVenueModel(Atn.Venue.getVenue(venueData.getBusinessFoursquareVenueId(), AtnApp.getAppContext())); } if(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_SUBSCRIBED)).equalsIgnoreCase(TRUE)) venueData.setSubscribed(true); else venueData.setSubscribed(false); if(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_IS_REGISTERED)).equalsIgnoreCase(TRUE)) venueData.setRegisterdVenue(true); else venueData.setRegisterdVenue(false); venueData.addBulkPromotion(getBulkPromotionDetail(venueData.getBusinessId(),false)); atnVenueList.add(venueData); } while (cursor.moveToNext()); } if(cursor!=null){cursor.close();}; return atnVenueList; } /** * Returns ATN registered venue details using specified ATN registered * business id. * * @param businessId * to get ATN venue details. * @return ATN registered venue details. */ public synchronized AtnRegisteredVenueData getAtnBusinessDetail(String businessId) { AtnRegisteredVenueData venueData = null; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(BusinessTable.BUSINESS_TABLE, null, BusinessTable.COL_BUSINESS_ID + " = ? OR "+BusinessTable.COL_BUSINESS_FS_LINK_ID+" = ?", new String[] { businessId,businessId }, null, null, null); if (cursor != null && cursor.getCount() > 0) { venueData = new AtnRegisteredVenueData(); cursor.moveToFirst(); venueData.setBusinessCity(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_CITY))); venueData.setBusinessFacebookLink(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK))); venueData.setBusinessFacebookLinkId(cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FB_LINK_ID))); venueData.setBusinessFoursquareVenueId(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK_ID))); venueData.setBusinessFoursquareVenueLink(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_FS_LINK))); venueData.setBusinessId(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_ID))); venueData.setBusinessImageUrl(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_LOGO))); venueData.setBusinessLat(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_LAT))); venueData.setBusinessLng(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_LON))); venueData.setBusinessModified(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_MODIFIED))); venueData.setBusinessName(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_NAME))); venueData.setBusinessPhone(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_PHONE))); venueData.setBusinessShared(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_SHARED))); venueData.setBusinessState(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_STATE))); venueData.setBusinessStatus(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_STATUS))); venueData.setBusinessStreet(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_STREET))); venueData.setBusinessZip(cursor.getString(cursor .getColumnIndex(BusinessTable.COL_BUSINESS_ZIP))); venueData.setVenueCategoryId(cursor.getInt(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FS_CAT_ID))); if (cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_FAVORITED)) .equalsIgnoreCase(TRUE)) venueData.setFavorited(true); else venueData.setFavorited(false); if (cursor.getString(cursor.getColumnIndex(BusinessTable.COL_BUSINESS_SUBSCRIBED)) .equalsIgnoreCase(TRUE)) venueData.setSubscribed(true); else venueData.setSubscribed(false); if (cursor.getString(cursor.getColumnIndex(BusinessTable.COL_IS_REGISTERED)) .equalsIgnoreCase(TRUE)) venueData.setRegisterdVenue(true); else venueData.setRegisterdVenue(false); venueData.addBulkPromotion(getBulkPromotionDetail(venueData.getBusinessId(), false)); if(!TextUtils.isEmpty(venueData.getBusinessFoursquareVenueId())){ venueData.setFsVenueModel(Atn.Venue.getVenue(venueData.getBusinessFoursquareVenueId(), AtnApp.getAppContext())); } } if(cursor!=null){cursor.close();}; return venueData; } public synchronized void insertOrUpdatePromotion(ContentValues values){ SQLiteDatabase db = getWritableDatabase(); int count = db.update(PromotionTable.PROMOTION_TABLE,values, PromotionTable.COL_PROMOTION_BUSINESS_ID + " = ? AND "+ PromotionTable.COL_PROMOTION_ID + " = ?", new String[] {values.getAsString(PromotionTable.COL_PROMOTION_BUSINESS_ID), values.getAsString(PromotionTable.COL_PROMOTION_ID) }); if(count==0){ db.insert(PromotionTable.PROMOTION_TABLE, null, values); } } /** * Inserts promotion detail in database. * * @param mTipDetail to insert. */ public synchronized void addPromotionDetail(AtnPromotion promotionDetail) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PromotionTable.COL_PROMOTION_ACCEPTED, promotionDetail.isAccepted()); values.put(PromotionTable.COL_PROMOTION_AGE_MAX, promotionDetail.getAgeMax()); values.put(PromotionTable.COL_PROMOTION_AGE_MIN, promotionDetail.getAgeMin()); values.put(PromotionTable.COL_PROMOTION_BUSINESS_ID, promotionDetail.getBusinessId()); values.put(PromotionTable.COL_PROMOTION_COUPON_EXPIRY_DATE, promotionDetail.getCouponExpiryDate()); values.put(PromotionTable.COL_PROMOTION_CREATED, promotionDetail.getPromotionCreated()); values.put(PromotionTable.COL_PROMOTION_DETAILS, promotionDetail.getPromotionDetail()); values.put(PromotionTable.COL_PROMOTION_END_DATE, promotionDetail.getEndDate()); values.put(PromotionTable.COL_PROMOTION_GROUP_COUNT, promotionDetail.getPromotionGroupCount()); values.put(PromotionTable.COL_PROMOTION_HIGH_RES_IMAGE, promotionDetail.getPromotionImageLargeUrl()); values.put(PromotionTable.COL_PROMOTION_ID, promotionDetail.getPromotionId()); values.put(PromotionTable.COL_PROMOTION_LOW_RES_IMAGE, promotionDetail.getPromotionImageSmallUrl()); values.put(PromotionTable.COL_PROMOTION_MODIFIED, promotionDetail.getPromotionModified()); values.put(PromotionTable.COL_PROMOTION_REDEEMED, promotionDetail.isRedeemed()); values.put(PromotionTable.COL_PROMOTION_SEX, promotionDetail.getSex()); values.put(PromotionTable.COL_PROMOTION_SHARED, promotionDetail.isShared()); values.put(PromotionTable.COL_PROMOTION_START_DATE, promotionDetail.getStartDate()); values.put(PromotionTable.COL_PROMOTION_STATUS, promotionDetail.getPromotionStatus()); values.put(PromotionTable.COL_PROMOTION_TITLE, promotionDetail.getPromotionTitle()); values.put(PromotionTable.COL_PROMOTION_TYPE, promotionDetail.getPromotionType().toString()); values.put(PromotionTable.COL_PROMOTION_LOGO_URL, promotionDetail.getPromotionLogoUrl()); int count = db.update(PromotionTable.PROMOTION_TABLE, values, PromotionTable.COL_PROMOTION_BUSINESS_ID+" = ? AND "+PromotionTable.COL_PROMOTION_ID+" = ?", new String[]{promotionDetail.getBusinessId(),promotionDetail.getPromotionId()}); if(count==0){ db.insert(PromotionTable.PROMOTION_TABLE, null, values); } } /** * Add promotion to my deals. * * @param promotionId to add * @param status to update. */ ///TO DO: ROHIT public synchronized void updatePromotionAddedStatus(String promotionId, boolean status) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PromotionTable.COL_PROMOTION_ID, promotionId); values.put(PromotionTable.COL_PROMOTION_ACCEPTED, status); db.update(PromotionTable.PROMOTION_TABLE, values, PromotionTable.COL_PROMOTION_ID + " = ?", new String[] { promotionId }); } /** * Updates promotion status for specified promotion id. * @param promotionId * @param promotionType */ public synchronized void updatePromotionStatus(String promotionId, PromotionType promotionType) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PromotionTable.COL_PROMOTION_ID, promotionId); values.put(PromotionTable.COL_PROMOTION_TYPE, promotionType.name()); db.update(PromotionTable.PROMOTION_TABLE, values, PromotionTable.COL_PROMOTION_ID + " = ?", new String[]{promotionId}); } public synchronized boolean isPromotionExist(String promotionId){ SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(PromotionTable.PROMOTION_TABLE, null, PromotionTable.COL_PROMOTION_ID + " = ?", new String[] { promotionId }, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.close(); return true; } if(cursor!=null){cursor.close();}; return false; } /** * Returns promotion details using specified promotionId. * * @param value promotion id to get promotion details. * @return promotion details. */ public synchronized AtnPromotion getPromotionDetail(String promotionId) { AtnPromotion promotionDetail = null; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(PromotionTable.PROMOTION_TABLE, null, PromotionTable.COL_PROMOTION_ID + " = ?", new String[] { promotionId }, null, null, null); if (cursor != null && cursor.getCount() > 0) { promotionDetail = new AtnPromotion(); cursor.moveToFirst(); if (cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_ACCEPTED)).equalsIgnoreCase(TRUE)) promotionDetail.setAccepted(true); else promotionDetail.setAccepted(false); promotionDetail.setAgeMax(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_AGE_MAX))); promotionDetail.setAgeMin(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_AGE_MIN))); promotionDetail.setBusinessId(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_BUSINESS_ID))); promotionDetail.setCouponExpiryDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_COUPON_EXPIRY_DATE))); promotionDetail.setPromotionCreated(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_CREATED))); promotionDetail.setPromotionDetail(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_DETAILS))); promotionDetail.setEndDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_END_DATE))); promotionDetail.setPromotionGroupCount(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_GROUP_COUNT))); promotionDetail.setPromotionId(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_ID))); promotionDetail.setPromotionModified(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_MODIFIED))); promotionDetail.setPromotionImageSmallUrl(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_LOW_RES_IMAGE))); promotionDetail.setStartDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_START_DATE))); String redeemTxt = cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_REDEEMED)); if (redeemTxt!=null&&redeemTxt.equalsIgnoreCase(TRUE)) promotionDetail.setRedeemed(true); else promotionDetail.setRedeemed(false); promotionDetail.setPromotionImageLargeUrl(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_HIGH_RES_IMAGE))); promotionDetail.setSex(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_SEX))); promotionDetail.setPromotionTitle(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_TITLE))); promotionDetail.setPromotionStatus(cursor.getInt(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_STATUS))); if (cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_SHARED)) == null) promotionDetail.setShared(false); else promotionDetail.setShared(true); String type = cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_TYPE)); if (type.equals(PromotionType.Event.toString())) promotionDetail.setPromotionType(PromotionType.Event); else if (type.equals(PromotionType.Offer.toString())) promotionDetail.setPromotionType(PromotionType.Offer); } if(cursor!=null){cursor.close();}; return promotionDetail; } /** * Returns bulk promotion details using specified businessId. * * @param businessId * to get promotion details. * @return promotion details. */ public synchronized ArrayList<AtnPromotion> getBulkPromotionDetail(String businessId, boolean isAccepted) { ArrayList<AtnPromotion> promotionList = new ArrayList<AtnPromotion>(); AtnPromotion promotionDetail; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = null; if (isAccepted) { cursor = db.query(PromotionTable.PROMOTION_TABLE, null, PromotionTable.COL_PROMOTION_BUSINESS_ID + " =? AND " + PromotionTable.COL_PROMOTION_ACCEPTED + " = ?", new String[] { businessId, TRUE }, null, null, null); } else { cursor = db.query(PromotionTable.PROMOTION_TABLE, null, PromotionTable.COL_PROMOTION_BUSINESS_ID + " =?", new String[] { businessId }, null, null, null); } if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { promotionDetail = new AtnPromotion(); if (cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_ACCEPTED)).equalsIgnoreCase(TRUE)) { promotionDetail.setAccepted(true); } else { promotionDetail.setAccepted(false); } promotionDetail.setAgeMax(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_AGE_MAX))); promotionDetail.setAgeMin(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_AGE_MIN))); promotionDetail.setBusinessId(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_BUSINESS_ID))); promotionDetail.setCouponExpiryDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_COUPON_EXPIRY_DATE))); promotionDetail.setPromotionCreated(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_CREATED))); promotionDetail.setPromotionDetail(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_DETAILS))); promotionDetail.setEndDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_END_DATE))); promotionDetail.setStartDate(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_START_DATE))); promotionDetail.setPromotionGroupCount(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_GROUP_COUNT))); promotionDetail.setPromotionId(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_ID))); promotionDetail.setPromotionModified(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_MODIFIED))); promotionDetail.setPromotionImageSmallUrl(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_LOW_RES_IMAGE))); promotionDetail.setPromotionLogoUrl(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_LOGO_URL))); String reddem = cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_REDEEMED)); if (reddem!=null&&reddem.equalsIgnoreCase(TRUE)) { promotionDetail.setRedeemed(true); } else { promotionDetail.setRedeemed(false); } promotionDetail.setPromotionImageLargeUrl(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_HIGH_RES_IMAGE))); promotionDetail.setSex(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_SEX))); promotionDetail.setPromotionTitle(cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_TITLE))); promotionDetail.setPromotionStatus(cursor.getInt(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_STATUS))); if (cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_SHARED)).equalsIgnoreCase(TRUE)) { promotionDetail.setShared(false); } else { promotionDetail.setShared(true); } String type = cursor.getString(cursor.getColumnIndex(PromotionTable.COL_PROMOTION_TYPE)); if (type.equals(PromotionType.Event.toString())) { promotionDetail.setPromotionType(PromotionType.Event); } else if (type.equals(PromotionType.Offer.toString())) { promotionDetail.setPromotionType(PromotionType.Offer); } promotionList.add(promotionDetail); } while (cursor.moveToNext()); } if(cursor!=null){cursor.close();}; return promotionList; } /** * Saves Facebook token of specified user into database. * * @param userId * @param fbToken * of the user. */ public synchronized int updateCouponStatus(String promotionId, int status) { SQLiteDatabase db = getWritableDatabase(); int result = -1; ContentValues values = new ContentValues(); values.put(PromotionTable.COL_PROMOTION_STATUS, status); result = db.update(PromotionTable.PROMOTION_TABLE, values, PromotionTable.COL_PROMOTION_ID + " = ?", new String[] { promotionId }); return result; } public synchronized int updatePromotion(ContentValues values, String promotionId) { SQLiteDatabase db = getWritableDatabase(); int result = -1; result = db.update(PromotionTable.PROMOTION_TABLE, values,PromotionTable.COL_PROMOTION_ID + " = ?", new String[] { promotionId }); return result; } /** * Updates the subsciption status of venue. * * @param businessId * to update status. * @param isSubscibed * subscribe/unsubscribe */ public synchronized void updateSubscriptionStatus(String businessId, boolean isSubscibed) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(BusinessTable.COL_BUSINESS_SUBSCRIBED, isSubscibed); db.update(BusinessTable.BUSINESS_TABLE, values, BusinessTable.COL_BUSINESS_ID + " = ?", new String[] { businessId }); } public synchronized int getPromotionStatus(String promotionId) { int status = 0; SQLiteDatabase db = getReadableDatabase(); String query = "SELECT " + PromotionTable.COL_PROMOTION_STATUS + " FROM " + PromotionTable.PROMOTION_TABLE + " WHERE " + PromotionTable.COL_PROMOTION_ID + " = " + promotionId; Cursor c = db.rawQuery(query, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); status = c.getInt(c.getColumnIndex(PromotionTable.COL_PROMOTION_STATUS)); } if(c!=null){ c.close(); } return status; } /** * Updates the subsciption status of for all ATN registered venues. * * @param isSubscibed * to update status. */ public synchronized void updateSubscriptionStatusForAllBusiness(boolean isSubscibed) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(BusinessTable.COL_BUSINESS_SUBSCRIBED, isSubscibed); db.update(BusinessTable.BUSINESS_TABLE, values, null, null); } /** * Updates promotion expire Time for specified promotion id. * @param promotionId * @param expiredTime */ public synchronized void updatePromotionExpireTime(String promotionId, String expiredTime) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PromotionTable.COL_PROMOTION_ID, promotionId); values.put(PromotionTable.COL_PROMOTION_COUPON_EXPIRY_DATE, expiredTime); db.update(PromotionTable.PROMOTION_TABLE, values, PromotionTable.COL_PROMOTION_ID + " = ?", new String[]{promotionId}); } /** * Clears all the database tables when user logout. */ public void clearDatabase() { SQLiteDatabase db = getWritableDatabase(); db.delete(BusinessTable.BUSINESS_TABLE, null, null); db.delete(LoginTable.TABLE_NAME, null, null); db.delete(PromotionTable.PROMOTION_TABLE, null, null); db.delete(UserTable.USER_TABLE, null, null); UserDataPool.getInstance().setUserDetail(null); } }
package com.demo.withdrawal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WithdrawalApplication { public static void main(String[] args) { SpringApplication.run(WithdrawalApplication.class, args); } }
package com.tencent.mm.plugin.z; import com.tencent.mm.a.e; import com.tencent.mm.a.p; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.opensdk.constants.ConstantsAPI$AppSupportContentFlag; import com.tencent.mm.plugin.backup.g.d; import com.tencent.mm.plugin.backup.h.k; import com.tencent.mm.plugin.backup.h.l; import com.tencent.mm.plugin.z.c.a; import com.tencent.mm.pointers.PInt; import com.tencent.mm.pointers.PLong; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ai; import java.io.File; import java.util.Iterator; import java.util.LinkedList; class c$1 implements Runnable { final /* synthetic */ LinkedList lsC; final /* synthetic */ long lsD; final /* synthetic */ c lsE; c$1(c cVar, LinkedList linkedList, long j) { this.lsE = cVar; this.lsC = linkedList; this.lsD = j; } public final void run() { long VF = bi.VF(); if (this.lsC == null) { x.e("MicroMsg.MsgSynchronizePack", "MsgSynchronizeSessionList is null."); if (this.lsE.lsB != null) { this.lsE.lsB.onCancel(); return; } return; } e.k(new File(f.bfG())); e.k(new File(f.bfH())); StringBuilder stringBuilder = new StringBuilder(); au.HU(); e.k(new File(stringBuilder.append(c.Gq()).append("msgsynchronize/").toString())); stringBuilder = new StringBuilder(); au.HU(); e.k(new File(stringBuilder.append(c.Gq()).append("msgsynchronize.zip").toString())); LinkedList linkedList = new LinkedList(); String str = (String) d.asG().asH().DT().get(2, null); PInt pInt = new PInt(); PInt pInt2 = new PInt(); PLong pLong = new PLong(); Iterator it = this.lsC.iterator(); while (it.hasNext()) { a aVar = (a) it.next(); ai Yq = d.asG().asH().FW().Yq(aVar.gRG); int i = Yq != null ? Yq.field_unReadCount : 0; if (pInt2.value >= b.lsy) { break; } k kVar = new k(); kVar.hbL = aVar.gRG; kVar.hbJ = (int) (d.asG().asH().FT().GZ(aVar.gRG) / 1000); kVar.hbK = i; linkedList.add(kVar); pInt2.value++; if (pInt.value < b.lsw) { this.lsE.a(aVar, str, i, pInt, pLong, this.lsD); } if (this.lsE.lsA) { break; } } if (this.lsE.lsA) { x.e("MicroMsg.MsgSynchronizePack", "MsgSynchronizePack canceled!"); return; } l lVar = new l(); lVar.hbM = linkedList; lVar.hbN = com.tencent.mm.az.d.SF().clP(); try { f.e(f.bfF(), "sessionlist", lVar.toByteArray()); x.i("MicroMsg.MsgSynchronizePack", "BackupSessionInfoList pack finish."); } catch (Exception e) { x.e("MicroMsg.MsgSynchronizePack", "ERROR: BackupSessionInfoList to Buffer, list:%d :%s", new Object[]{Integer.valueOf(lVar.hbM.size()), e.getMessage()}); } p.b(new File(f.bfG()), false, f.bfH()); x.i("MicroMsg.MsgSynchronizePack", "synchronize finish, backupCostTime[%d]", new Object[]{Long.valueOf(bi.bH(VF))}); long cm = (long) e.cm(f.bfH()); if (this.lsE.lsB != null) { this.lsE.lsB.a(f.bfH(), this.lsC.size(), str, pInt.value, pLong.value, cm / ConstantsAPI$AppSupportContentFlag.MMAPP_SUPPORT_XLS); } } }
package com.puxtech.reuters.rfa.test; import java.net.InetSocketAddress; import java.net.ConnectException; import java.nio.charset.Charset; import java.util.Date; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.buffer.SimpleBufferAllocator; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.filter.keepalive.KeepAliveFilter; import org.apache.mina.filter.keepalive.KeepAliveMessageFactory; import org.apache.mina.filter.keepalive.KeepAliveRequestTimeoutHandler; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.SocketConnector; import org.apache.mina.transport.socket.nio.NioSocketConnector; import com.puxtech.reuters.rfa.Common.TextCodecFactory; public class MinaClient { public SocketConnector socketConnector; /** * 缺省连接超时时间 */ public static final int DEFAULT_CONNECT_TIMEOUT = 5; public static final String HOST = "10.150.16.118"; public static final int PORT = 9931; public MinaClient() { init(); } public void init() { socketConnector = new NioSocketConnector(Runtime.getRuntime().availableProcessors()); // 长连接 // socketConnector.getSessionConfig().setKeepAlive(true); // socketConnector.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); // socketConnector.setReaderIdleTime(DEFAULT_CONNECT_TIMEOUT); // socketConnector.setWriterIdleTime(DEFAULT_CONNECT_TIMEOUT); // socketConnector.setBothIdleTime(DEFAULT_CONNECT_TIMEOUT); // socketConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory())); // socketConnector.getFilterChain().addLast("logger", new LoggingFilter()); // socketConnector.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextCodecFactory(Charset.forName("GBK")))); // KeepAliveMessageFactory heartBeatFactory = new KeepAliveMessageFactoryImpl(); //// KeepAliveRequestTimeoutHandler heartBeatHandler = new KeepAliveRequestTimeoutHandlerImpl(); // KeepAliveFilter heartBeat = new KeepAliveFilter(heartBeatFactory, // IdleStatus.BOTH_IDLE, KeepAliveRequestTimeoutHandler.DEAF_SPEAKER); // /** 是否回发 */ // heartBeat.setForwardEvent(true); // /** 发送频率 */ // heartBeat.setRequestInterval(10); // socketConnector.getFilterChain().addLast("heartbeat", heartBeat); ClientIoHandler ioHandler = new ClientIoHandler(); socketConnector.setHandler(ioHandler); socketConnector.getSessionConfig().setReaderIdleTime(20); } boolean run = true; class NioExecuter implements Runnable{ @Override public void run() { InetSocketAddress addr = new InetSocketAddress(HOST, PORT); ConnectFuture cf = socketConnector.connect(addr); try { cf.awaitUninterruptibly(); // cf.getSession().write(msg); // System.out.println("send message " + msg); // while(run){ // System.out.println("running......"); // } } catch (RuntimeIoException e) { if (e.getCause() instanceof ConnectException) { try { if (cf.isConnected()) { cf.getSession().close(); } } catch (RuntimeIoException e1) { } } } } } public void sendMessage(final String msg) { InetSocketAddress addr = new InetSocketAddress(HOST, PORT); ConnectFuture cf = socketConnector.connect(addr); try { cf.isConnected(); cf.getSession().getCloseFuture().awaitUninterruptibly(); socketConnector.dispose(); // cf.getSession().write(msg); // System.out.println("send message " + msg); // while(run){ // System.out.println("running......"); // } } catch (RuntimeIoException e) { if (e.getCause() instanceof ConnectException) { try { if (cf.isConnected()) { cf.getSession().close(); } } catch (RuntimeIoException e1) { } } } } public static void main(String[] args) throws InterruptedException { MinaClient clent = new MinaClient(); new Thread(clent.new NioExecuter()).start(); // for (int i = 0; i < 1; i++) { // System.err.println(i); // clent.sendMessage("Hello World " + i); // } // clent.getSocketConnector().dispose(); //System.exit(0); } public SocketConnector getSocketConnector() { return socketConnector; } public void setSocketConnector(SocketConnector socketConnector) { this.socketConnector = socketConnector; } private static class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory { /* * (non-Javadoc) * * @see * org.apache.mina.filter.keepalive.KeepAliveMessageFactory#getRequest * (org.apache.mina.core.session.IoSession) */ private static long initDate = new Date().getTime(); @Override public Object getRequest(IoSession session) { System.out.println("返回预设语句"); /** 返回预设语句 */ // if(new Date().getTime() - initDate >= 1*60*1000){ // return null; // } return ""; } /* * (non-Javadoc) * * @see * org.apache.mina.filter.keepalive.KeepAliveMessageFactory#getResponse * (org.apache.mina.core.session.IoSession, java.lang.Object) */ @Override public Object getResponse(IoSession session, Object request) { System.out.println("返回null"); /** 返回预设语句 */ return null; } /* * (non-Javadoc) * * @see * org.apache.mina.filter.keepalive.KeepAliveMessageFactory#isRequest * (org.apache.mina.core.session.IoSession, java.lang.Object) */ @Override public boolean isRequest(IoSession session, Object message) { System.out.println("是否是心跳包Request: " + message); // if(message.equals(HEARTBEATREQUEST)) return true; // return false; } /* * (non-Javadoc) * * @see * org.apache.mina.filter.keepalive.KeepAliveMessageFactory#isResponse * (org.apache.mina.core.session.IoSession, java.lang.Object) */ @Override public boolean isResponse(IoSession session, Object message) { System.out.println("是否是心跳包Response: " + message); // if(message.equals(HEARTBEATRESPONSE)) return true; // return false; } } } class ClientIoHandler implements IoHandler { private void releaseSession(IoSession session) throws Exception { System.out.println("releaseSession"); if (session.isConnected()) { session.close(true); } } @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("sessionOpened"); } @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("sessionClosed"); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("sessionIdle"); // try { // releaseSession(session); // } catch (RuntimeIoException e) { // } } @Override public void messageReceived(IoSession session, Object message) throws Exception { System.out.println("Receive Server message " + message.getClass().getName()); org.apache.mina.core.buffer.SimpleBufferAllocator buff; // super.messageReceived(session, message); // releaseSession(session); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { System.out.println("exceptionCaught"); cause.printStackTrace(); releaseSession(session); } @Override public void messageSent(IoSession session, Object message) throws Exception { System.out.println("messageSent"); // super.messageSent(session, message); } @Override public void sessionCreated(IoSession session) throws Exception { // TODO Auto-generated method stub } }
/** * */ package codejam.hanoi_tower; import java.util.Stack; /** * * @author dgamez * */ public class HanoiTower { /** * This method moves the Disks from towerA to towerB using towerC as temporal tower * @param towerA Tower used as from * @param towerC Tower used as to * @param towerB Tower used as temporal * @return the number of moves */ public int move(Stack<HanoiDisk> towerA, Stack<HanoiDisk> towerC, Stack<HanoiDisk> towerB){ return move(towerA, towerC, towerB, towerA.size(), 0); } protected int move(Stack<HanoiDisk> towerA, Stack<HanoiDisk> towerC, Stack<HanoiDisk> towerB, int diskNumber, int moves){ if (diskNumber >= 1){ moves = move(towerA, towerB, towerC, diskNumber -1, moves); moves += moveDisk(towerA, towerC); moves = move(towerB, towerC, towerA, diskNumber -1, moves); } return moves; } protected int moveDisk(Stack<HanoiDisk> fromTower, Stack<HanoiDisk> toTower){ int result = 0; if (fromTower.size() > 0){ HanoiDisk disk = fromTower.pop(); toTower.push(disk); result = 1; } return result; } }
package g_auth_resource; import java.io.IOException; import java.security.GeneralSecurityException; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import status_resource.Status; /** * 通信に必要なオブジェクトを管理する。 */ public abstract class ConnectionResource extends Status { private JsonFactory jsonFactory; private HttpTransport transport; public ConnectionResource() { this.initStatus(); this.jsonFactory = JacksonFactory.getDefaultInstance(); try { this.transport = GoogleNetHttpTransport.newTrustedTransport(); this.setCode(2); } catch (GeneralSecurityException e) { this.errorTerminate("エラーが発生しました。 " + e); } catch (IOException e) { this.errorTerminate("エラーが発生しました。 " + e); } } /** * @return JsonFactory */ public JsonFactory getJsonFactory() { return this.jsonFactory; } /** * @return HttpTransport */ public HttpTransport getTransport() { return this.transport; } /** * @return Credential */ public abstract Credential getCredential(); }
package com.finalist.plugin; import org.onehippo.cms7.essentials.dashboard.rest.BaseResource; import org.onehippo.cms7.essentials.dashboard.rest.MessageRestful; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED}) @Path("/textblockPlugin/") public class TextBlockPluginResource extends BaseResource { @GET public MessageRestful runTextblockPlugin(@Context ServletContext servletContext) { return new MessageRestful("Not implemented yet"); } }
package com.smartwerkz.bytecode.classfile; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; /** * <pre> * Code_attribute { * u2 attribute_name_index; * u4 attribute_length; * u2 max_stack; * u2 max_locals; * u4 code_length; * u1 code[code_length]; * u2 exception_table_length; * { u2 start_pc; * u2 end_pc; * u2 handler_pc; * u2 catch_type; * } exception_table[exception_table_length]; * u2 attributes_count; * attribute_info attributes[attributes_count]; * } * </pre> * * @author mhaller */ public class CodeAttribute { private int maxStack; private int maxLocals; private int codeLength; private byte[] codeArray; private int exceptionTableLength; private int attributesCount; private final ExceptionTable exceptionTable = new ExceptionTable(); private final Attributes attributes; public CodeAttribute(ConstantPool constantPool, byte[] value) { try { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(value)); maxStack = dis.readUnsignedShort(); maxLocals = dis.readUnsignedShort(); codeLength = dis.readInt(); codeArray = new byte[codeLength]; dis.read(codeArray); exceptionTableLength = dis.readUnsignedShort(); for (int i = 0; i < exceptionTableLength; i++) { int startPc = dis.readUnsignedShort(); int endPc = dis.readUnsignedShort(); int handlerPc = dis.readUnsignedShort(); int catchType = dis.readUnsignedShort(); exceptionTable.registerHandler(startPc, endPc, handlerPc, catchType); } attributes = new Attributes(constantPool, dis); dis.close(); } catch (IOException e) { throw new RuntimeException(e); } } public int getMaxLocals() { return maxLocals; } public int getMaxStack() { return maxStack; } public byte[] getCode() { return codeArray; } public ExceptionTable getExceptionTable() { return exceptionTable; } public LineNumberTable getLineNumberTable() { AttributeInfo attribute = attributes.getAttribute("LineNumberTable"); if (attribute==null) { return null; } return new LineNumberTable(attribute); } }
package jdbc; import java.sql.*; import javax.sql.*; import javax.naming.*; public class ConnUtil { public Connection getConnection() { Connection con = null; try { Context init = new InitialContext(); DataSource ds = (DataSource)init.lookup("java:comp/env/jdbc/mydb"); con = ds.getConnection(); }catch(Exception e) { System.out.println("Conection 생성 실패~~~"); } return con; } }
package leetcode.string; /** * Created by apple on 2019/5/16. */ public class replaceSpaceSolution { public String replaceSpace1(StringBuffer str) { StringBuffer res = new StringBuffer(); int len = str.length() - 1; for(int i = len; i >= 0; i--){ if(str.charAt(i) == ' ') res.append("02%"); else res.append(str.charAt(i)); } return res.reverse().toString(); } public String replaceSpace2(StringBuffer str) { /* 思路一:return str.toString().replace(" ", "%20"); 思路二:计算字符串的空格数量,空出对应的位置依次插入'%''2''0'三个字符 */ char c[] = new char[str.length()]; int count = 0; for(int i=0;i<c.length;i++) { c[i] = str.charAt(i); if(c[i]==' ') { count++; } } char chr[] = new char[c.length+count*2]; for(int i = 0,j = 0;i<c.length&&j<chr.length;) { if(c[i]==' ') { chr[j++] = '%'; chr[j++] = '2'; chr[j++] = '0'; } else { chr[j] = c[i]; j++; } i++; } return String.valueOf(chr); } public static void main(String args[]) { StringBuffer x1 = new StringBuffer("we are happy "); replaceSpaceSolution rep = new replaceSpaceSolution(); System.out.println(rep.replaceSpace1(x1)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import java.awt.Font; import java.awt.FontFormatException; import java.io.IOException; import java.io.InputStream; import org.lwjgl.opengl.GL11; import org.newdawn.slick.Color; import org.newdawn.slick.util.ResourceLoader; /** * * @author Lars Aksel */ public class TextType { private boolean antiAliased; private TrueTypeFont ttFont; private Color textColor; private float fontSize; private int alignment; public TextType(float xPos, float yPos, String text, String fontPath, float fontSize, boolean antiAliased) { this.fontSize = fontSize; this.antiAliased = antiAliased; this.textColor = new Color(1,1,1); try { InputStream inputStream = ResourceLoader.getResourceAsStream(fontPath); Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream); awtFont = awtFont.deriveFont(fontSize); // set font size ttFont = new TrueTypeFont(awtFont, antiAliased, null); } catch (FontFormatException | IOException e) { e.printStackTrace(); } } public TextType(String fontPath, float fontSize, boolean antiAliased, Color textColor, int alignment) { this.fontSize = fontSize; this.antiAliased = antiAliased; this.textColor = textColor; this.alignment = alignment; try { Font awtFont; try (InputStream inputStream = ResourceLoader.getResourceAsStream(fontPath)) { awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream); } awtFont = awtFont.deriveFont(fontSize); // set font size ttFont = new TrueTypeFont(awtFont, antiAliased, null); } catch (FontFormatException | IOException e) { e.printStackTrace(); } } public void draw(float xPos, float yPos, String text) { GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glColor3f(this.textColor.r, this.textColor.g, this.textColor.b); ttFont.drawString(xPos, yPos, text, 1, 1, alignment); GL11.glColor3f(1, 1, 1); GL11.glDisable(GL11.GL_TEXTURE_2D); } }
package code; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class EventHandlerPlace implements ActionListener { private boolean _hasPlaced; private char[][] boardArray; private boolean _invalidPlacement; private String curtile; private JPanel _pan2; private ScannerMan _sm; private BufferedImage _guiTile; private static int _x; private static int _y; public EventHandlerPlace(boolean hasPlaced, char[][] _boardArray, boolean invalidPlacement, String _curtile, JPanel pan2, ScannerMan sm) { _hasPlaced = hasPlaced; boardArray = _boardArray; _invalidPlacement = invalidPlacement; curtile = _curtile; _pan2 = pan2; _sm = sm; } @Override public void actionPerformed(ActionEvent e) { int x = 0; boolean canSave = true; while(x == 0){ JTextField inputx = new JTextField(); JLabel xcoord = new JLabel("X Coordinate:"); final JComponent[] xinput = new JComponent[]{ xcoord, inputx }; JOptionPane.showMessageDialog(null,xinput,"Place",JOptionPane.PLAIN_MESSAGE); if(inputx.getText().equals("1") || inputx.getText().equals("2") || inputx.getText().equals("3") || inputx.getText().equals("4") || inputx.getText().equals("5") || inputx.getText().equals("6") || inputx.getText().equals("7") || inputx.getText().equals("8") || inputx.getText().equals("9") || inputx.getText().equals("10") || inputx.getText().equals("11") || inputx.getText().equals("12")){ x = Integer.parseInt(inputx.getText()); } else{ JLabel xwrong = new JLabel("Not a valid X Coordinate! (1-12 Are Valid)"); final JComponent[] inputwrong = new JComponent[]{ xwrong }; JOptionPane.showMessageDialog(null,inputwrong,"Place",JOptionPane.PLAIN_MESSAGE); } } int y = 0; while(y == 0){ JTextField inputy = new JTextField(); JLabel ycoord = new JLabel("Y Coordinate:"); final JComponent[] xinput = new JComponent[]{ ycoord, inputy }; JOptionPane.showMessageDialog(null,xinput,"Place",JOptionPane.PLAIN_MESSAGE); if(inputy.getText().equals("1") || inputy.getText().equals("2") || inputy.getText().equals("3") || inputy.getText().equals("4") || inputy.getText().equals("5") || inputy.getText().equals("6") || inputy.getText().equals("7") || inputy.getText().equals("8") || inputy.getText().equals("9") || inputy.getText().equals("10") || inputy.getText().equals("11") || inputy.getText().equals("12")){ y = Integer.parseInt(inputy.getText()); } else{ JLabel ywrong = new JLabel("Not a valid Y Coordinate! (1-12 Are Valid)"); final JComponent[] inputwrong = new JComponent[]{ ywrong }; JOptionPane.showMessageDialog(null,inputwrong,"Place",JOptionPane.PLAIN_MESSAGE); } } _x = x; _y = y; if(canSave){ //does nothing, just want to get rid of the yellow line } if(_invalidPlacement){ //does nothing, just want to get rid of the yellow line } if(placeIsName(x, y)){ canSave = false; } } public boolean placeIsName(int xcord, int ycord) { if((xcord == 6 && ycord == 6) || (xcord == 6 && ycord == 7) || (xcord == 7 && ycord == 6)|| (xcord == 7 && ycord == 7)){ JLabel station = new JLabel("You Can't Place This Tile Here, There Is A Station There"); final JComponent[] inputwrong = new JComponent[]{ station }; JOptionPane.showMessageDialog(null,inputwrong,"Place",JOptionPane.PLAIN_MESSAGE); return true; } else{ if (!_hasPlaced && isEmpty(xcord, ycord, boardArray)) { JLabel labelrem; labelrem = (JLabel) _pan2.getComponentAt(xcord*50, ycord*50); _pan2.remove(labelrem); new Block(stringToImage(curtile), xcord, ycord, xcord, ycord, 50, 50, _pan2, _sm); _pan2.repaint(); if (TileTypeChecker(curtile, xcord, ycord,boardArray) == true) { _hasPlaced = true; _invalidPlacement = false; } else { JLabel cant = new JLabel("You Can't Place This Tile Here, Please remove it"); final JComponent[] inputwrong = new JComponent[]{ cant }; JOptionPane.showMessageDialog(null,inputwrong,"Place",JOptionPane.PLAIN_MESSAGE); _hasPlaced = true; _invalidPlacement = true; } } else { JLabel invalid = new JLabel("Sorry, invalid tile placement. Either Something's already here or you already placed your tile."); final JComponent[] inputwrong = new JComponent[]{ invalid }; JOptionPane.showMessageDialog(null,inputwrong,"Place",JOptionPane.PLAIN_MESSAGE); } return true; } } public boolean TileTypeChecker(String tilestring, int locx, int locy,char[][] boardArray) { if (tilestring.equals(" 31 2 24 4 31 ")) { //A return true; } else if (tilestring.equals(" 32 3 24 1 41 ") || tilestring.equals(" 34 1 24 3 21 ")) { //B and C boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {1,12}; for (int x : xs2) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs3 = {6,7}; for (int x : xs3) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+7,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==1 || locx==12)&&(locy==1 || locy==12)); } } else if (tilestring.equals(" 33 4 24 2 11 ")) { //D boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==1 || locx==12 || locy==1 || locy==12)); } } else if (tilestring.equals(" 31 4 24 2 31 ")) { //E boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+7,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==1 || locx==12)); } } else if (tilestring.equals(" 33 2 24 4 11 ")) { //F boolean allSpacesTaken = true; int[] xs1 = {1,2,3,4,5,8,9,10,11,12}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locy==1 || locy==12)); } } else if (tilestring.equals(" 33 1 24 2 41 ")) { //G boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=2; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs3 = {6,7}; for (int x : xs3) { for (int y=8; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs4 = {1}; for (int x : xs4) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==12 || locy==1) || (locx==1 && locy==12)); } } else if (tilestring.equals(" 33 4 24 1 21 ")) { //H boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=2; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs3 = {6,7}; for (int x : xs3) { for (int y=8; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs4 = {12}; for (int x : xs4) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==1 || locy==1) || (locx==12 && locy==12)); } } else if (tilestring.equals(" 32 4 24 3 11 ")) { //I boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs3 = {6,7}; for (int x : xs3) { for (int y=8; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs4 = {12}; for (int x : xs4) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==1 || locy==12) || (locx==12 && locy==1)); } } else if (tilestring.equals(" 34 3 24 2 11 ")) { //J boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs3 = {6,7}; for (int x : xs3) { for (int y=8; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs4 = {1}; for (int x : xs4) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } if(allSpacesTaken){ return true; } else{ return !((locx==12 || locy==12) || (locx==1 && locy==1)); } } else if (tilestring.equals(" 32 1 24 3 41 ") || tilestring.equals(" 32 1 24 4 31 ") || tilestring.equals(" 31 2 24 3 41 ")) { //K and U and X boolean allSpacesTaken = true; int[] xs1 = {1,2,3,4,5,8,9,10,11,12}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } for (int x=1; x<=11; x++) { allSpacesTaken &= !isEmpty(x,1,boardArray); allSpacesTaken &= !isEmpty(x+1,12,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locx==1 && locy==12) || (locx==12 && locy==1)); } } else if (tilestring.equals(" 34 3 24 1 21 ") || tilestring.equals(" 34 2 24 1 31 ") || tilestring.equals(" 31 3 24 4 21 ")) { //L and V and W boolean allSpacesTaken = true; int[] xs1 = {1,2,3,4,5,8,9,10,11,12}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } for (int x=2; x<=12; x++) { allSpacesTaken &= !isEmpty(x,1,boardArray); allSpacesTaken &= !isEmpty(x-1,12,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locx==1 && locy==1) || (locx==12 && locy==12)); } } else if (tilestring.equals(" 32 3 24 4 11 ") || tilestring.equals(" 34 2 24 3 11 ")) { //M and S boolean allSpacesTaken = true; int[] xs1 = {1,2,3,4,5,8,9,10,11,12}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } for (int x=2; x<=11; x++) { allSpacesTaken &= !isEmpty(x,1,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locy==12)||(locx==1 && locy==1)||(locx==12 && locy==1)); } } else if (tilestring.equals(" 33 2 24 1 41 ") || tilestring.equals(" 33 1 24 4 21 ")) { //N and R boolean allSpacesTaken = true; int[] xs1 = {1,2,3,4,5,8,9,10,11,12}; for (int x : xs1) { for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=2; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+6,boardArray); } } for (int x=2; x<=11; x++) { allSpacesTaken &= !isEmpty(x,12,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locy==1)||(locx==1 && locy==12)||(locx==12 && locy==12)); } } else if (tilestring.equals(" 32 4 24 1 31 ") || tilestring.equals(" 31 4 24 3 21 ")) { //O and T boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+7,boardArray); } } for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(12,y,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locx==1)||(locx==12 && locy==1)||(locx==12 && locy==12)); } } else if (tilestring.equals(" 31 3 24 2 41 ") || tilestring.equals(" 34 1 24 2 31 ")) { //P and Q boolean allSpacesTaken = true; int[] xs1 = {2,3,4,5,8,9,10,11}; for (int x : xs1) { for (int y=1; y<=12; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); } } int[] xs2 = {6,7}; for (int x : xs2) { for (int y=1; y<=5; y++) { allSpacesTaken &= !isEmpty(x,y,boardArray); allSpacesTaken &= !isEmpty(x,y+7,boardArray); } } for (int y=2; y<=11; y++) { allSpacesTaken &= !isEmpty(1,y,boardArray); } if(allSpacesTaken){ return true; } else{ return !((locx==12)||(locx==11 && locy==1)||(locx==1 && locy==12)); } } else{ return true; //never should execute here } } public boolean isEmpty(int x, int y, char[][] boardArray) { return (boardArray[4 * (y - 1) + 1][4 * (x - 1) + 2] == ' '); } private BufferedImage stringToImage(String curTile){ if(curTile.equals(" 31 2 24 4 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEA.png"); } else if(curTile.equals(" 32 3 24 1 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEB.png"); } else if(curTile.equals(" 34 1 24 3 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEC.png"); } else if(curTile.equals(" 33 4 24 2 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILED.png"); } else if(curTile.equals(" 31 4 24 2 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEE.png"); } else if(curTile.equals(" 33 2 24 4 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEF.png"); } else if(curTile.equals(" 33 1 24 2 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEG.png"); } else if(curTile.equals(" 33 4 24 1 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEH.png"); } else if(curTile.equals(" 32 4 24 3 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEI.png"); } else if(curTile.equals(" 34 3 24 2 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEJ.png"); } else if(curTile.equals(" 32 1 24 3 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEK.png"); } else if(curTile.equals(" 34 3 24 1 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEL.png"); } else if(curTile.equals(" 32 3 24 4 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEM.png"); } else if(curTile.equals(" 33 2 24 1 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEN.png"); } else if(curTile.equals(" 32 4 24 1 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEO.png"); } else if(curTile.equals(" 31 3 24 2 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEP.png"); } else if(curTile.equals(" 34 1 24 2 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEQ.png"); } else if(curTile.equals(" 33 1 24 4 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILER.png"); } else if(curTile.equals(" 34 2 24 3 11 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILES.png"); } else if(curTile.equals(" 31 4 24 3 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILET.png"); } else if(curTile.equals(" 32 1 24 4 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEU.png"); } else if(curTile.equals(" 34 2 24 1 31 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEV.png"); } else if(curTile.equals(" 31 3 24 4 21 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEW.png"); } else if(curTile.equals(" 31 2 24 3 41 ")){ _guiTile = HelpfulImageMethods.loadImage("tileGUIPictures/TILEX.png"); } return _guiTile; } public static int getX(){ return _x; } public static int getY(){ return _y; } }
package com.liemily.tradesimulation.trade; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by Emily Li on 12/08/2017. */ public interface TradeRepository extends JpaRepository<Trade, Long> { }
package ru.moneydeal.app.auth; import androidx.annotation.NonNull; import androidx.room.Entity; import ru.moneydeal.app.models.BaseUser; @Entity(tableName = "auth") public class AuthEntity extends BaseUser { @NonNull public String token; public AuthEntity( String id, String login, String firstName, String lastName, @NonNull String token ) { super(id, login, firstName, lastName); this.token = token; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.test.producer.specializes; import java.lang.annotation.Annotation; import java.util.Set; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.util.AnnotationLiteral; import org.apache.webbeans.test.AbstractUnitTest; import org.apache.webbeans.test.annotation.binding.Binding1; import org.apache.webbeans.test.annotation.binding.Binding2; import org.apache.webbeans.test.component.producer.specializes.SpecializesProducer1; import org.apache.webbeans.test.component.producer.specializes.SpecializesProducerParentBean; import org.apache.webbeans.test.component.producer.specializes.superclazz.SpecializesProducer1SuperClazz; import org.junit.Assert; import org.junit.Test; public class SpecializesProducer1Test extends AbstractUnitTest { @Test public void testSpecializedProducer1() { startContainer(SpecializesProducer1SuperClazz.class, SpecializesProducer1.class); Annotation binding1 = new AnnotationLiteral<Binding1>() { }; Annotation binding2 = new AnnotationLiteral<Binding2>() { }; Integer methodNumber = getInstance(int.class, binding1); Assert.assertEquals(10000, methodNumber.intValue()); Integer fieldNumber = getInstance(int.class, binding2); Assert.assertEquals(4711, fieldNumber.intValue()); } /** * SpecializesProducerParentBean specializes SpecializesProducer1SuperClazz * Thus all the producer fields and methods in the parent class must be disabled. */ @Test public void testDisabledProducerViaSpecialization() { startContainer(SpecializesProducer1SuperClazz.class, SpecializesProducerParentBean.class); Annotation binding1 = new AnnotationLiteral<Binding1>() { }; Annotation binding2 = new AnnotationLiteral<Binding2>() { }; Set<Bean<?>> beans = getBeanManager().getBeans(int.class, binding1); Assert.assertEquals(0, beans.size()); beans = getBeanManager().getBeans(int.class, binding2); Assert.assertEquals(0, beans.size()); } }
package resto.com.app.services; import java.util.List; import resto.com.app.pojos.User; public interface LoginService { public User loginToUser(String username ,String password); }
package com.anyang.myWeb.service; import com.anyang.myWeb.entity.user.User; import com.anyang.myWeb.service.user.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.TreeMap; @Service public class ExampleService { @Autowired private UserService userService; public Map<String, Object> greet() { List<User> userList = userService.getAll(); Map<String, Object> result = new TreeMap<>(); result.put("userList", userList); return result; } }
package zm.gov.moh.core.repository.database.dao.domain; import androidx.lifecycle.LiveData; import androidx.room.*; import zm.gov.moh.core.repository.database.entity.domain.EncounterRole; @Dao public interface EncounterRoleDao { //gets all locations @Query("SELECT * FROM encounter_role WHERE encounter_role_id = :id") LiveData<EncounterRole> getById(long id); @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(EncounterRole... encounterRoles); }
package com.rishi.baldawa.iq; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class RemoveElementsFromArrayTest { @Test public void solution() throws Exception { int[] nums = {1, 2, 2, 3}; assertEquals(new RemoveElementsFromArray().solution(nums, 3), 3); assertArrayEquals(nums, new int[]{1, 2, 2, 3}); } @Test public void solution2() throws Exception { int[] nums = {3, 2, 2, 3}; assertEquals(new RemoveElementsFromArray().solution(nums, 3), 2); assertArrayEquals(nums, new int[]{2, 2, 2, 3}); } }
package com.gexne.xpay; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.gexne.paylib.Xpay; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; /** * 本 URL 只供测试,实际需要换成自己的服务端地址 */ public static final String URL = "https://wx.bilifoo.com/demo/api/order_sign"; private EditText goodsNameEdt, totalFeeEdt; private Button wapBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUi(); } private void initUi() { goodsNameEdt = (EditText) findViewById(R.id.goods_name_edt); totalFeeEdt = (EditText) findViewById(R.id.total_fee_edt); wapBtn = (Button) findViewById(R.id.wap); wapBtn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.wap: //先请求自己服务器,获得 charge getChargeAsync(Xpay.CHANNEL_WAP_ZHIMOU, totalFeeEdt.getText().toString().trim(), goodsNameEdt.getText().toString().trim()); break; } } /** * 获取 charge 的方式根据需要与自己的服务端约定,这里只是给个例子 */ public void getChargeAsync(String channel, String totalFee, String goodsName) { FormBody formBody = new FormBody.Builder() .add("channel", channel) .add("total_fee", totalFee) .add("goods_name", goodsName) .build(); final Request request = new Request.Builder() .url(URL) .post(formBody) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "network error", e); } @Override public void onResponse(Call call, Response response) throws IOException { /** * 从自己服务器获取到 charge,调用 sdk 即可打开支付页面 */ String chargeStr = response.body().string(); Log.d(TAG, "chargeStr = " + chargeStr); Xpay.DEBUG = true; Xpay.createPayment(MainActivity.this, chargeStr); } }); } /** * 重写 onActivityResult 方法,得到支付回调的结果 * 注意:请勿直接使用客户端支付结果作为最终判定订单状态的依据,支付状态以服务端为准!!! * 在收到客户端同步返回结果时,请向自己的服务端请求来查询订单状态。 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Xpay.REQUEST_CODE_XPAY) { if (resultCode == RESULT_OK) { //有返回信息,可能成功,也可能失败 String payResult = data.getStringExtra(Xpay.KEY_PAY_RESULT); String channel = data.getStringExtra(Xpay.KEY_CHANNEL); String extraMsg = data.getStringExtra(Xpay.KEY_EXTRA_MSG); String errorMsg = data.getStringExtra(Xpay.KEY_ERROR_MSG); Log.d(TAG, "payResult = " + payResult); Log.d(TAG, "channel = " + channel); Log.d(TAG, "extraMsg = " + extraMsg); Log.d(TAG, "errorMsg = " + errorMsg); } } } }
import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; public class BlockCreator { static ArrayList<String> files; static int orderValue; // create arraylist that will be used for making sorted file public static void createFile(String filename,long blockSize,String sortColumn[],String outputColumn[]) throws IOException { files=new ArrayList<String>(); String outputFilenname; //Parser obj=new Parser(); outputFilenname=Parser.outputFile; //System.out.println("---->"+Parser.outputFile); BufferedReader reader=new BufferedReader(new FileReader(filename)); String str=""; long count=1; int numbr_files=1,flag=0; String interfilename; ArrayList<String> data=new ArrayList<String>(); while ((str = reader.readLine()) != null) { if(count==blockSize) { flag=0; data.add(str); interfilename="file".concat(String.valueOf(numbr_files)); files.add(interfilename); sortArraylist(data, sortColumn,interfilename); //interfilename="file".concat(String.valueOf(numbr_files)); numbr_files++; data.clear(); count=1; } else { flag=1; data.add(str); count++; } } if(flag==1) { interfilename="file".concat(String.valueOf(numbr_files)); files.add(interfilename); sortArraylist(data, sortColumn,interfilename); } reader.close(); //for(int i=0;i<files.size();i++) //System.out.println(outputFilenname); filesMergeSort(files, outputFilenname, sortColumn,outputColumn); } // Sort arraylist w.r.t any number of column and then create file public static void sortArraylist(ArrayList<String> data,final String sortColumn[],String interFilename) throws IOException { int index=0; final engine e=new engine(); //final int orderValue; if(Parser.order.equals("asc")) { orderValue=1; } else { orderValue=-1; } Collections.sort(data, new Comparator<String>() { @Override //for() public int compare(String s1, String s2) { int j=0,i; for(i=0;i<sortColumn.length;i++) { j=e.mapFile.get(sortColumn[i]); if(!s1.split(",")[j].equals(s2.split(",")[j])) { break; } } switch(e.mapDataType.get(j)) { case "int" : return orderValue * (Integer.parseInt(s1.split(",")[j]) < Integer.parseInt(s2.split(",")[j]) ? -1 : Integer.parseInt(s1.split(",")[j]) == Integer.parseInt(s2.split(",")[j]) ? 0 : 1); case "char" : return orderValue * (s1.split(",")[j].compareTo(s2.split(",")[j])); case "date" : DateFormat f = new SimpleDateFormat("dd/MM/yyyy"); try { return orderValue * (f.parse(s1.split(",")[j]).compareTo(f.parse(s2.split(",")[j]))); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return 0; } }); FileWriter writer=new FileWriter(interFilename); for(int i=0;i<data.size();i++) { writer.write(data.get(i)+"\n"); } writer.close(); } public static void filesMergeSort(ArrayList<String> files, String outputfile,final String sortColumn[],String outputColumn[]) throws IOException { //System.out.println("---"+engine.numberOfIntermediateFile); final engine e=new engine(); for(int i=0;i<outputColumn.length;i++) System.out.println(outputColumn[i]); PriorityQueue<BinaryFileBuffer> pq = new PriorityQueue<BinaryFileBuffer>(engine.numberOfIntermediateFile, new Comparator<BinaryFileBuffer>() { public int compare(BinaryFileBuffer ii, BinaryFileBuffer jj) { String s1=ii.peek(); // System.out.println(s1); // System.out.println(s1); String s2=jj.peek(); int j=0,i; for(i=0;i<sortColumn.length;i++) { j=e.mapFile.get(sortColumn[i]); if(!s1.split(",")[j].equals(s2.split(",")[j])) { break; } } switch(e.mapDataType.get(j)) { case "int" : return orderValue * (Integer.parseInt(s1.split(",")[j]) < Integer.parseInt(s2.split(",")[j]) ? -1 : Integer.parseInt(s1.split(",")[j]) == Integer.parseInt(s2.split(",")[j]) ? 0 : 1); case "char" : return orderValue * (s1.split(",")[j].compareTo(s2.split(",")[j])); case "date" : DateFormat f = new SimpleDateFormat("dd/MM/yyyy"); try { return orderValue * (f.parse(s1.split(",")[j]).compareTo(f.parse(s2.split(",")[j]))); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // return cmp.compare(i.peek(), j.peek()); return 0; } } ); for (String f : files) { BinaryFileBuffer bfb = new BinaryFileBuffer(f); pq.add(bfb); } BufferedWriter fbw = new BufferedWriter(new FileWriter(outputfile)); // int rowcounter = 0; try { while(pq.size()>0) { BinaryFileBuffer bfb = pq.poll(); String r[] = bfb.pop().split(","); // add the column in file that appear in command line int len=outputColumn.length; String output=""; for(int i=0;i<len;i++) { if(i<=len-2) output+=(r[engine.mapFile.get(outputColumn[i])]+","); else output+=(r[engine.mapFile.get(outputColumn[i])]); } fbw.write(output); fbw.newLine(); // ++rowcounter; if(bfb.empty()) { bfb.fbr.close(); // bfb.originalfile.delete();// we don't need you anymore } else { pq.add(bfb); // add it back } } } finally { fbw.close(); for(BinaryFileBuffer bfb : pq ) bfb.close(); } } } class BinaryFileBuffer { // public static int BUFFERSIZE = 2048; public BufferedReader fbr; public String originalfile; private String cache; private boolean empty; public BinaryFileBuffer(String f) throws IOException { originalfile = f; fbr = new BufferedReader(new FileReader(f)); reload(); } public boolean empty() { return empty; } private void reload() throws IOException { try { if((this.cache = fbr.readLine()) == null){ empty = true; cache = null; } else{ empty = false; } } catch(EOFException oef) { empty = true; cache = null; } } public void close() throws IOException { fbr.close(); } public String peek() { if(empty()) return null; return cache.toString(); } public String pop() throws IOException { String answer = peek(); reload(); return answer; } }
package com.example.library.Service; import com.example.library.Entity.User; import com.example.library.Exceptions.UserNotFoundException; import com.example.library.Login.MyUserDetails; import com.example.library.Repository.UsersRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class UserService { private final UsersRepository usersRepository; public MyUserDetails getUserByUsername(String username) { User user = usersRepository.findUserByLogin(username).orElseThrow(() -> new UserNotFoundException(username)); return new MyUserDetails(user); } }
package me.reichwald.spigot.mtools.actions; public enum ToolAction { BREAK_PLOCK, PLACE_BLOCK, REPLACE_BLOCK, EXECUTE_COMMAND, DAMAGE_ENTITY, DAMAGE_ARMOR, DAMAGE_ITEM, HEAL_ENTITY, SUMMON_ENTITY, KILL_ENTITY, MOVE_ENTITY, POTION_EFFECT, ENCHANT_ITEM, }
package com.hussam.interests; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class RegisterFragment extends Fragment { TextView firstnameText, lastnameText, emailText, passwordText; Button registerButton; boolean flag1 , flag2, flag3, flag4, flag; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_register,container, false); firstnameText = (TextView) rootView.findViewById(R.id.registerFirstName); lastnameText = (TextView) rootView.findViewById(R.id.registerLastName); emailText = (TextView) rootView.findViewById(R.id.registerEmail); passwordText = (TextView) rootView.findViewById(R.id.registerPassword); firstnameText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { if(firstnameText.getText().toString().matches(Utilities.namePattern) && s.length()>0){ firstnameText.setTextColor(getResources().getColor(R.color.greeny)); flag1 = true; }else{ firstnameText.setTextColor(getResources().getColor(R.color.redy)); flag1 = false; } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } }); lastnameText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(lastnameText.getText().toString().matches(Utilities.namePattern) && s.length()>0){ lastnameText.setTextColor(getResources().getColor(R.color.greeny)); flag2 = true; }else { lastnameText.setTextColor(getResources().getColor(R.color.redy)); flag2 = false; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); emailText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(emailText.getText().toString().matches(Utilities.emailPattern) && s.length()>0){ emailText.setTextColor(getResources().getColor(R.color.greeny)); flag3 = true; }else { emailText.setTextColor(getResources().getColor(R.color.redy)); flag3 = false; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); passwordText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (passwordText.getText().toString().matches(Utilities.passwordPattern) && s.length() > 0) { passwordText.setTextColor(getResources().getColor(R.color.greeny)); flag4 = true; } else { passwordText.setTextColor(getResources().getColor(R.color.redy)); flag4 = false; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); registerButton = (Button) rootView.findViewById(R.id.registerButton); registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String firstName = firstnameText.getText().toString(); String lastName = lastnameText.getText().toString(); String email = emailText.getText().toString(); String password = passwordText.getText().toString(); flag = flag1 && flag2 && flag3 && flag4; if(flag){ // instance of asyncTask here ; new registerData().execute(firstName, lastName, email, password); Toast.makeText(getContext(), "Registration Succes, you can login now!", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getContext(), "Registration Failed, check all unvalid red entries", Toast.LENGTH_LONG).show(); flag = true; } } }); return rootView; } public class registerData extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { String firstName = ""; String lastName = ""; String email = ""; String password = ""; try { firstName = params[0]; lastName = params[1]; email = params[2]; password = params[3]; String link = "http://192.168.1.3/register.php"; URL url = new URL(link); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); String post_data = URLEncoder.encode("email", "UTF-8") + "=" +URLEncoder.encode(email, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") +"="+URLEncoder.encode(password, "UTF-8") + "&" + URLEncoder.encode("firstname", "UTF-8") +"="+URLEncoder.encode(firstName, "UTF-8") + "&" + URLEncoder.encode("lastname", "UTF-8") +"="+URLEncoder.encode(lastName, "UTF-8"); bufferedWriter.write(post_data); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); String result = ""; String line = ""; while ((line = reader.readLine()) != null) result +=line; if(result.length() == 0) return null; reader.close(); inputStream.close(); httpURLConnection.disconnect(); return result; }catch (Exception e){ return new String("Exception: " + e.getMessage()); } } } }
package com.salaboy.conferences.agenda.controller; import com.salaboy.conferences.agenda.model.ServiceInfo; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping public class InfoController { @Value("${version:0.0.0}") private String version; @Value("${POD_ID:}") private String podId; @Value("${POD_NODE_NAME:}") private String podNodeName; @Value("${POD_NAMESPACE:}") private String podNamespace; @GetMapping("/info") public ServiceInfo getInfo() { return new ServiceInfo( "Agenda Service", "v"+version, "https://github.com/salaboy/fmtok8s-agenda/releases/tag/v" + version, podId, podNamespace, podNodeName); } }
package com.example.currency.config; import org.ehcache.event.CacheEvent; import org.ehcache.event.CacheEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CacheLogger implements CacheEventListener<Object, Object> { private static Logger logger = LoggerFactory.getLogger(CacheLogger.class); @Override public void onEvent(CacheEvent<?, ?> event) { logger.info("Cache Log: {\nkey: " + event.getKey() + ",\ntype: " + event.getType() + ",\noldValue: " + event.getOldValue() + ",\nnewValue: " + event.getNewValue()); } }
package nl.jtosti.hermes.user; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; /** * Database solution for the {@link User} entity. */ @Repository public interface UserRepository extends CrudRepository<User, Long> { /** * @param email Email of the user * @return optional user */ Optional<User> findByEmail(String email); /** * @return List of all users ordered by {@link User#getId()} */ List<User> findAllByOrderByIdAsc(); @Query("select u from users u inner join u.companies cu ON cu.id = :companyId") List<User> findUsersByCompanyId(@Param("companyId") Long id); }
package br.com.hbsis.testeandroidnatan.impl.dao.base; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.Date; import java.util.List; import br.com.hbsis.testeandroidnatan.base.IDao; /** * Created by natan on 07/02/17. */ public class DaoPessoaLocal implements IDao<Pessoa> { private static final String DATABASE = "DATABAASE"; private Context context; private SQLiteOpenHelper dbHelper; private String SELECT_SQL="Select * from pessoa"; private final String COLUNA_ID = "id"; private final String COLUNA_NOME = "nome"; private final String COLUNA_SOBRENOME = "sobrenome"; private final String COLUNA_DATANASCIMENTO = "dataNascimento"; private final String TABLE_NAME = "pessoa"; public DaoPessoaLocal(Context c){ this.context = c; this.dbHelper = getNewDBHelper(); } public long insert(Pessoa p){ SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select max("+COLUNA_ID+") from " + TABLE_NAME, null); cursor.moveToFirst(); int last = cursor.getInt(0)+1; ContentValues values = new ContentValues(); values.put(COLUNA_ID, last); values.put(COLUNA_NOME, p.getNome()); values.put(COLUNA_SOBRENOME, p.getSobrenome()); values.put(COLUNA_DATANASCIMENTO, p.getDataNascimento().getTime()); long newRowId = db.insert(TABLE_NAME, null, values); db.close(); return newRowId; } @Override public List<Pessoa> getAll() { Cursor c = dbHelper.getReadableDatabase().rawQuery(SELECT_SQL, null); List<Pessoa> pessoas = new ArrayList<>(); if(c.moveToFirst()) { do { String id = c.getString(0); String nome = c.getString(c.getColumnIndex(COLUNA_NOME)); String sobrenome = c.getString(c.getColumnIndex(COLUNA_SOBRENOME)); long longdataNascimenot = c.getLong(c.getColumnIndex(COLUNA_DATANASCIMENTO)); Date dataNascimento = new Date(longdataNascimenot); Pessoa p = new Pessoa(); p.setNome(nome); p.setSobrenome(sobrenome); p.setDataNascimento(dataNascimento); pessoas.add(p); c.moveToNext(); } while (!c.isLast()); } return pessoas; } public SQLiteOpenHelper getNewDBHelper() { return new PessoaDBHelper(context); } }
package com.ibm.esc.xml.parser.sax; // import java.util.Locale; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.Locale; import org.xml.sax.AttributeList; import org.xml.sax.DTDHandler; import org.xml.sax.DocumentHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.HandlerBase; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.ibm.esc.xml.parser.AbstractMicroXMLParser; import com.ibm.esc.xml.parser.XMLAttributeList; import com.ibm.esc.xml.parser.XMLException; import com.ibm.xml.parser.TXDOMException; /** * This parser implements the SAX APIs */ public class MicroXMLParser extends AbstractMicroXMLParser implements Parser, Locator { private DocumentHandler documentHandler; private ErrorHandler errorHandler; //private InputSource source; private String systemId; private String publicId; public void setLocale(Locale l) {} /** * Method comment */ public MicroXMLParser() { super(); // Set a Defauult DocumentHandler to avoid // any kind of test like: // if (documentHandler != null) ... setDocumentHandler(new HandlerBase()); } /** */ public void characters (char ch[], int start, int length) throws XMLException { try { documentHandler.characters(ch, start, length); } catch (SAXException e) { throw new XMLException(e); } } /** */ protected void endDocument() throws XMLException { try { documentHandler.endDocument(); } catch (SAXException e) { throw new XMLException(e); } } /** */ protected void endElement(String tagName) throws XMLException { try { documentHandler.endElement(tagName); } catch (SAXException e) { throw new XMLException(e); } } /** */ protected void fatalError(int errorID, String parameter) throws XMLException { SAXParseException e = new SAXParseException( errorMsg(errorID, parameter), this); if (errorHandler != null) { try { errorHandler.fatalError(e); } catch (SAXException exception) { throw new XMLException(exception); } } // If the errorhandler didn't throw the exception // it is time to do it throw new XMLException(e); } /** * Allow an application to register a document event handler. * * <p>If the application does not register a document handler, all * document events reported by the SAX parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase).</p> * * <p>Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately.</p> * * @param handler The document handler. * @see DocumentHandler * @see HandlerBase */ public DocumentHandler getDocumentHandler() { return documentHandler; } public String getPublicId() { return publicId; } public String getSystemId() { return systemId; } /** */ protected XMLAttributeList newAttributeList() { return new AttributeListImpl(); } /** * Parse an XML document from a system identifier (URI). * @see org.xml.sax.Parser#parse(java.lang.String) */ public void parse (String systemId) throws SAXException { // This parser must be independent from java.net throw new SAXException(com.ibm.esc.xml.parser.Messages.getString("EmbeddedXMLParser.MicroXMLParser_does_not_support_any_system_identofier_or_URL._1")); } /** * Parse an XML document. * * <p>The application can use this method to instruct the SAX parser * to begin parsing an XML document from any valid input * source (a character stream, a byte stream, or a URI).</p> * * <p>Applications may not invoke this method while a parse is in * progress (they should create a new Parser instead for each * additional XML document). Once a parse is complete, an * application may reuse the same Parser object, possibly with a * different input source.</p> * * @param source The input source for the top-level of the * XML document. * @exception org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. * @see org.xml.sax.InputSource * @see #parse(java.lang.String) * @see #setEntityResolver * @see #setDTDHandler * @see #setDocumentHandler * @see #setErrorHandler */ public void parse (InputSource source) throws SAXException, IOException { setSource(source); Reader reader = null; if (source.getCharacterStream() != null) { reader = source.getCharacterStream(); } else if (source.getByteStream() != null) { reader = new InputStreamReader(source.getByteStream()); } if (reader == null) return; setStream(reader); try { doParse(); } catch (XMLException e) { Exception we = e.getWrappedException(); throw (SAXException)we; } } /** */ protected void processingInstruction(String target, String data) throws XMLException { try { documentHandler.processingInstruction(target, data); } catch (SAXException e) { throw new XMLException(e); } } /** * Allow an application to register a document event handler. * * <p>If the application does not register a document handler, all * document events reported by the SAX parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase).</p> * * <p>Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately.</p> * * @param handler The document handler. * @see DocumentHandler * @see HandlerBase */ public void setDocumentHandler(DocumentHandler documentHandler) { this.documentHandler = documentHandler; documentHandler.setDocumentLocator(this); } /** * Allow an application to register a DTD event handler. * * <p>If the application does not register a DTD handler, all DTD * events reported by the SAX parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase).</p> * * <p>Applications may register a new or different * handler in the middle of a parse, and the SAX parser must * begin using the new handler immediately.</p> * * @param handler The DTD handler. * @see DTDHandler * @see HandlerBase */ /* * This current release doesn't manage any DTD handler */ public void setDTDHandler (DTDHandler handler) { // nop } /** * Allow an application to register a custom entity resolver. * * <p>If the application does not register an entity resolver, the * SAX parser will resolve system identifiers and open connections * to entities itself (this is the default behaviour implemented in * HandlerBase).</p> * * <p>Applications may register a new or different entity resolver * in the middle of a parse, and the SAX parser must begin using * the new resolver immediately.</p> * * @param resolver The object for resolving entities. * @see EntityResolver * @see HandlerBase */ /* * This current release doesn't support any Entity resolver */ public void setEntityResolver (EntityResolver resolver) { // nop } /** * Allow an application to register an error event handler. * * <p>If the application does not register an error event handler, * all error events reported by the SAX parser will be silently * ignored, except for fatalError, which will throw a SAXException * (this is the default behaviour implemented by HandlerBase).</p> * * <p>Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately.</p> * * @param handler The error handler. * @see ErrorHandler * @see SAXException * @see HandlerBase */ public void setErrorHandler (ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** */ protected void setPublicId (String publicId) { this.publicId = publicId; } /** */ protected void setSource (InputSource source) { //this.source = source; setPublicId(source.getPublicId()); setSystemId(source.getSystemId()); } /** */ protected void setSystemId (String systemId) { this.systemId = systemId; } /** */ protected void startDocument() throws XMLException { try { documentHandler.startDocument(); } catch (SAXException e) { throw new XMLException(e); } } /** */ protected void startElement(String tagName, XMLAttributeList attributeList) throws XMLException { try { documentHandler.startElement(tagName, (AttributeList)attributeList); } catch (SAXException e) { throw new XMLException(e); } catch (TXDOMException e) { throw new XMLException(e); } } /** */ protected void warning(int errorID, String parameter) throws XMLException { try { SAXParseException e = new SAXParseException( errorMsg(errorID, parameter), this); if (errorHandler != null) { errorHandler.warning(e); } } catch (SAXException exception) { throw new XMLException(exception); } } }
package com.appareldiving.dataretriever.controller.feign; import com.appareldiving.dataretriever.dto.RequestData; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; @FeignClient("zuul-api-gateway") public interface ZuulProxy { @PostMapping("data-parsing-adidas-service/process") boolean processData(@RequestBody RequestData requestData); @GetMapping(path = "adidas-data-scraping/{parser}/{quantity}") List<String> collectAndHandOnProductLinks(@PathVariable String parser, @PathVariable int quantity); }
/** */ package ErdiagramDSL.util; import ErdiagramDSL.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see ErdiagramDSL.ErdiagramDSLPackage * @generated */ public class ErdiagramDSLSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ErdiagramDSLPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ErdiagramDSLSwitch() { if (modelPackage == null) { modelPackage = ErdiagramDSLPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case ErdiagramDSLPackage.ERDIAGRAM: { Erdiagram erdiagram = (Erdiagram)theEObject; T result = caseErdiagram(erdiagram); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.DIAGRAM_ELEMENT: { DiagramElement diagramElement = (DiagramElement)theEObject; T result = caseDiagramElement(diagramElement); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_ELEMENT: { ChenElement chenElement = (ChenElement)theEObject; T result = caseChenElement(chenElement); if (result == null) result = caseDiagramElement(chenElement); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_ENTITY: { ChenEntity chenEntity = (ChenEntity)theEObject; T result = caseChenEntity(chenEntity); if (result == null) result = caseChenElement(chenEntity); if (result == null) result = caseDiagramElement(chenEntity); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_RELATIONSHIP: { ChenRelationship chenRelationship = (ChenRelationship)theEObject; T result = caseChenRelationship(chenRelationship); if (result == null) result = caseChenElement(chenRelationship); if (result == null) result = caseDiagramElement(chenRelationship); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_ATTRIBUTE: { ChenAttribute chenAttribute = (ChenAttribute)theEObject; T result = caseChenAttribute(chenAttribute); if (result == null) result = caseChenElement(chenAttribute); if (result == null) result = caseDiagramElement(chenAttribute); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_CONNECTION: { ChenConnection chenConnection = (ChenConnection)theEObject; T result = caseChenConnection(chenConnection); if (result == null) result = caseDiagramElement(chenConnection); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_NORMAL_TO_WEAK_CONNECTION: { ChenNormalToWeakConnection chenNormalToWeakConnection = (ChenNormalToWeakConnection)theEObject; T result = caseChenNormalToWeakConnection(chenNormalToWeakConnection); if (result == null) result = caseDiagramElement(chenNormalToWeakConnection); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_WEAK_ELEMENT: { ChenWeakElement chenWeakElement = (ChenWeakElement)theEObject; T result = caseChenWeakElement(chenWeakElement); if (result == null) result = caseDiagramElement(chenWeakElement); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_WEAK_ENTITY: { ChenWeakEntity chenWeakEntity = (ChenWeakEntity)theEObject; T result = caseChenWeakEntity(chenWeakEntity); if (result == null) result = caseChenWeakElement(chenWeakEntity); if (result == null) result = caseDiagramElement(chenWeakEntity); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_WEAK_RELATIONSHIP: { ChenWeakRelationship chenWeakRelationship = (ChenWeakRelationship)theEObject; T result = caseChenWeakRelationship(chenWeakRelationship); if (result == null) result = caseChenWeakElement(chenWeakRelationship); if (result == null) result = caseDiagramElement(chenWeakRelationship); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_WEAK_ATTRIBUTE: { ChenWeakAttribute chenWeakAttribute = (ChenWeakAttribute)theEObject; T result = caseChenWeakAttribute(chenWeakAttribute); if (result == null) result = caseChenWeakElement(chenWeakAttribute); if (result == null) result = caseDiagramElement(chenWeakAttribute); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.CHEN_WEAK_CONNECTION: { ChenWeakConnection chenWeakConnection = (ChenWeakConnection)theEObject; T result = caseChenWeakConnection(chenWeakConnection); if (result == null) result = caseDiagramElement(chenWeakConnection); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.MARTIN_ELEMENT: { MartinElement martinElement = (MartinElement)theEObject; T result = caseMartinElement(martinElement); if (result == null) result = caseDiagramElement(martinElement); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.MARTIN_ENTITY: { MartinEntity martinEntity = (MartinEntity)theEObject; T result = caseMartinEntity(martinEntity); if (result == null) result = caseMartinElement(martinEntity); if (result == null) result = caseDiagramElement(martinEntity); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.MARTIN_CONNECTION: { MartinConnection martinConnection = (MartinConnection)theEObject; T result = caseMartinConnection(martinConnection); if (result == null) result = caseDiagramElement(martinConnection); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.MINMAX_ENTITY: { MinmaxEntity minmaxEntity = (MinmaxEntity)theEObject; T result = caseMinmaxEntity(minmaxEntity); if (result == null) result = caseDiagramElement(minmaxEntity); if (result == null) result = defaultCase(theEObject); return result; } case ErdiagramDSLPackage.MINMAX_CONNECTION: { MinmaxConnection minmaxConnection = (MinmaxConnection)theEObject; T result = caseMinmaxConnection(minmaxConnection); if (result == null) result = caseDiagramElement(minmaxConnection); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Erdiagram</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Erdiagram</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseErdiagram(Erdiagram object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Diagram Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Diagram Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDiagramElement(DiagramElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenElement(ChenElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Entity</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Entity</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenEntity(ChenEntity object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Relationship</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Relationship</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenRelationship(ChenRelationship object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Attribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Attribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenAttribute(ChenAttribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Connection</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Connection</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenConnection(ChenConnection object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Normal To Weak Connection</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Normal To Weak Connection</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenNormalToWeakConnection(ChenNormalToWeakConnection object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Weak Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Weak Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenWeakElement(ChenWeakElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Weak Entity</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Weak Entity</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenWeakEntity(ChenWeakEntity object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Weak Relationship</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Weak Relationship</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenWeakRelationship(ChenWeakRelationship object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Weak Attribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Weak Attribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenWeakAttribute(ChenWeakAttribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Chen Weak Connection</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Chen Weak Connection</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChenWeakConnection(ChenWeakConnection object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Martin Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Martin Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMartinElement(MartinElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Martin Entity</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Martin Entity</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMartinEntity(MartinEntity object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Martin Connection</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Martin Connection</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMartinConnection(MartinConnection object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Minmax Entity</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Minmax Entity</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMinmaxEntity(MinmaxEntity object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Minmax Connection</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Minmax Connection</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMinmaxConnection(MinmaxConnection object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //ErdiagramDSLSwitch
package com.yinghai.a24divine_user.module.login.phone; import com.example.fansonlib.base.BaseView; import com.yinghai.a24divine_user.bean.PersonInfoBean; import com.yinghai.a24divine_user.callback.IHandleCodeCallback; import io.rong.imlib.RongIMClient; /** * @author Created by:fanson * Created on:2017/10/25 14:19 * Describe:登录的契约管理类 */ public interface ContractLogin { interface ILoginView extends BaseView { /** * 登陸失敗 */ void onLoginFailure(String msg); /** * 登录成功 */ void loginSuccess(boolean isHasPassword); /** * 获取验证码失敗 */ void getCodeFailure(String msg); /** * 获取验证码成功 */ void getCodeSuccess(); /** * 获取区号 * @return */ String getCountryCode(); /** * 获取手机号码 * @return */ String getTelNo(); /** * 获取密码 * @return */ String getPassword(); /** * 获取验证码 * @return */ String getVerifyCode(); void setGetVerifyCodeEnable(boolean enable); } interface ILoginPresenter { /** * 登录验证 * * @param countryCode * @param telNo * @param verifyCode */ void onLogin(String countryCode, String telNo, String verifyCode); void onLoingPwd(String countryCode,String telNo, String pwd); /** * 获取验证码 */ void onGetCode(final String countryCode, String telNo); } interface ILoginModel { /** * 验证码登录验证 * @param countryCode * @param telNo * @param verifyCode * @param callback */ void verifyLogin(String countryCode, String telNo, String verifyCode, ILoginCallback callback); /** * 密码登录 * @param countryCode * @param telNo * @param password * @param callback */ void pwdLogin(String countryCode, String telNo, String password, ILoginCallback callback); interface ILoginCallback extends IHandleCodeCallback{ void onLoginSuccess(PersonInfoBean bean); void onLoginFailure(String errorMsg); } /** * 获取验证码 */ void getVerifyCode(final String countryCode, String telNo, IGetCodeCallback callback); interface IGetCodeCallback extends IHandleCodeCallback { void onGetCodeSuccess(); void onGetCodeFailure(String errorMsg); } /** * 登录融云的服务器 * @param token * @param mConnectCallback */ void rongIMLogin(String token, RongIMClient.ConnectCallback mConnectCallback); } }
/* * Sonar C-Rules Plugin * Copyright (C) 2010 SonarSource * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.c.checks; import java.util.Stack; import org.sonar.check.BelongsToProfile; import org.sonar.check.IsoCategory; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.check.RuleProperty; import com.sonar.sslr.api.AstNode; import com.sonarsource.c.plugin.CCheck; @Rule(key = "C.NestedIfDepth", name = "Nested if depth", isoCategory = IsoCategory.Maintainability, priority = Priority.MAJOR, description = "<p>Restricts nested if-else blocks to a specified depth.</p>") @BelongsToProfile(title = CChecksConstants.SONAR_C_WAY_PROFILE_KEY, priority = Priority.MAJOR) public class NestedIfDepthCheck extends CCheck { private final static int DEFAULT_MAXIMUM_NESTED_IF_LEVEL = 5; @RuleProperty(key = "maximumNestedIfLevel", description = "The maximum number of nested if that are authorized.", defaultValue = "" + DEFAULT_MAXIMUM_NESTED_IF_LEVEL) private int maximumNestedIfLevel = DEFAULT_MAXIMUM_NESTED_IF_LEVEL; private Stack<AstNode> nestedIf = new Stack<AstNode>(); public void init() { subscribeTo(getCGrammar().ifStatement); } public void visitFile(AstNode node) { nestedIf = new Stack<AstNode>(); } public void visitNode(AstNode astNode) { nestedIf.add(astNode); if (nestedIf.size() == maximumNestedIfLevel + 1) { log("There should not be more than {0,number,integer} nested if statements.", astNode, maximumNestedIfLevel); } } public void leaveNode(AstNode astNode) { nestedIf.pop(); } @Override public void leaveFile(AstNode astNode) { nestedIf = new Stack<AstNode>(); } public void setMaximumNestedIfLevel(int threshold) { this.maximumNestedIfLevel = threshold; } }
package cz.kojotak.udemy.vertx.stockBroker.api.quote; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.kojotak.udemy.vertx.stockBroker.api.asset.GetAssetsFromDatabase; import cz.kojotak.udemy.vertx.stockBroker.db.DbHandler; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.Handler; import io.vertx.core.http.HttpHeaders; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import io.vertx.jdbcclient.JDBCPool; import io.vertx.sqlclient.templates.SqlTemplate; public class GetQuoteFromDatabaseHandler implements Handler<RoutingContext> { private static final Logger LOG = LoggerFactory.getLogger(GetQuoteFromDatabaseHandler.class); private final JDBCPool dbPool; public GetQuoteFromDatabaseHandler(JDBCPool dbPool) { this.dbPool = dbPool; } @Override public void handle(RoutingContext ctx) { String assetParam = ctx.pathParam("asset"); LOG.debug("asset parameter {}", assetParam); SqlTemplate .forQuery(dbPool, "select q.asset, q.bid, q.ask, q.last_price, q.volume from quotes q where asset=#{asset}") .mapTo(QuoteEntity.class) .execute(Collections.singletonMap("asset", assetParam)) .onFailure(DbHandler.error(ctx, "failed to read quotes for asset "+assetParam+" from DB")) .onSuccess( quotes->{ if(!quotes.iterator().hasNext()) { DbHandler.notFound(ctx, "no quotes found"); return; } //assume only one var res = quotes.iterator().next().toJsonObject(); ctx.response() .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON) .end(res.toBuffer()); LOG.debug("asset parameter {} and response {}", assetParam, res); }); } }
package algorithm.DataStructure; /** * 可持久化线段树(精简) */ public abstract class PersistSegTree { int[] roots;//各版本的根节点 int[]val,l,r; int size,len;//根节点数量,节点数量 PersistSegTree(int len,int VersionNum){ roots=new int[VersionNum+1]; val=new int[len]; l=new int[len]; r=new int[len]; clear(); } void clear(){ len=size=0; } int update(int BaseVersion,int start,int end,int pos,int val){ roots[++size]=copy(roots[BaseVersion]); upd(roots[size],start,end,pos,val); return size; } void upd(int p,int s,int t,int pos,int v){ if(s==t){ val[p]=updateValue(val[p],v); return; } int mid=(s+t)>>>1; if(pos<=mid){ l[p]=copy(l[p]); upd(l[p],s,mid,pos,v); }else { r[p]=copy(r[p]); upd(r[p],mid+1,t,pos,v); } val[p]=pushup(val[l[p]],val[r[p]]); } int query(int p1,int p2,int k,int s,int t){ if(s==t)return t; int mid=(s+t)>>1; int x=val[l[p2]]-val[l[p1]]; if(k<=x)return query(l[p1],l[p2],k,s,mid); else return query(r[p1],r[p2],k-x,mid+1,t); } abstract int updateValue(int original,int val); abstract int pushup(int left,int right); private int copy(int a){ len++; val[len]=val[a]; l[len]=l[a]; r[len]=r[a]; return len; } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.panel.center; import com.google.gwt.user.client.ui.Composite; import com.openkm.frontend.client.panel.left.Navigator; /** * Desktop * * @author jllort * */ public class Desktop extends Composite { private final static int PANEL_LEFT_WIDTH = 225; public final static int SPLITTER_WIDTH = 10; private HorizontalSplitLayoutExtended horizontalSplitLayoutPanel; public Navigator navigator; public Browser browser; private int totalWidthSize = 0; private int width = 0; private int height = 0; private int left = PANEL_LEFT_WIDTH; private int right = 0; private int contractPreviousLeft = 0; /** * Desktop */ public Desktop() { horizontalSplitLayoutPanel = new HorizontalSplitLayoutExtended(new HorizontalResizeHandler() { @Override public void onResize(int leftWidth, int rightHeight) { resizePanels(); } }); navigator = new Navigator(); browser = new Browser(); horizontalSplitLayoutPanel.addWest(navigator,PANEL_LEFT_WIDTH); horizontalSplitLayoutPanel.add(browser); initWidget(horizontalSplitLayoutPanel); } /** * Sets the size on initialization * * @param width The max width of the widget * @param height The max height of the widget */ public void setSize(int width, int height) { totalWidthSize = width; this.width = width; this.height = height; left = (int) (width * 0.2); left = left < PANEL_LEFT_WIDTH ? PANEL_LEFT_WIDTH : left; right = width - (left + SPLITTER_WIDTH); if (right < 0) { right = 0; } horizontalSplitLayoutPanel.setPixelSize(width, height); navigator.setSize(left, height); browser.setSize(right, height); horizontalSplitLayoutPanel.setSplitPosition(navigator, left, false); } /** * expandTreeView */ public void expandTreeView() { contractPreviousLeft = left; left = totalWidthSize - SPLITTER_WIDTH; right = 0; horizontalSplitLayoutPanel.setSplitPosition(navigator, left, false); navigator.setSize(left, height); browser.setSize(right, height); } /** * closeTreeView */ public void closeTreeView() { contractPreviousLeft = left; left = 0; right = totalWidthSize - SPLITTER_WIDTH; horizontalSplitLayoutPanel.setSplitPosition(navigator, left, false); navigator.setSize(left, height); browser.setSize(right, height); } /** * restoreNormalView */ public void restoreNormalView() { left = contractPreviousLeft; right = totalWidthSize - (left + SPLITTER_WIDTH); horizontalSplitLayoutPanel.setSplitPosition(navigator, left, false); navigator.setSize(left, height); browser.setSize(right, height); } /** * Sets the panel width on resizing */ private void resizePanels() { left = horizontalSplitLayoutPanel.getLeftWidth(); right = horizontalSplitLayoutPanel.getRightWidth(); navigator.setSize(left, height); if (right > 0) { browser.setWidth(right); } } /** * refreshSpliterAfterAdded */ public void refreshSpliterAfterAdded() { horizontalSplitLayoutPanel.setSplitPosition(navigator, left, false); } /** * getWidth */ public int getWidth() { return width; } /** * getHeight */ public int getHeight() { return height; } /** * getLeft */ public int getLeft() { return left; } /** * getRight */ public int getRight() { return right; } }
package kh.cocoa.service; import kh.cocoa.dao.TeamDAO; import kh.cocoa.dto.TeamDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class TeamService implements TeamDAO { @Autowired TeamDAO tdao; @Override public List<TeamDTO> getTeamList(int code){ return tdao.getTeamList(code); } @Override public TeamDTO getTeamName(int code) { return tdao.getTeamName(code); } @Override public List<TeamDTO> getSearchTeamList(String name) { return tdao.getSearchTeamList(name); } @Override public List<TeamDTO> getSearchTeamCode(String name) { return tdao.getSearchTeamCode(name); } /* 소형 관리자 사용자관리*/ @Override public List<TeamDTO> getAllTeamList(){ return tdao.getAllTeamList(); }; @Override public List<TeamDTO> getTeamListByDeptCode(int dept_code){ return tdao.getTeamListByDeptCode(dept_code); }; @Override public int addTeam(List<TeamDTO> dto) { return tdao.addTeam(dto); }; @Override public int updateTeam(List<TeamDTO> dto) { return tdao.updateTeam(dto); }; @Override public int deleteTeam(List<TeamDTO> dto) { return tdao.deleteTeam(dto); } @Override public int countNoTeam(int dept_code) { return tdao.countNoTeam(dept_code); } }
package com.lizogub.HomeWork4; import java.lang.reflect.Array; import java.util.Arrays; public class Codewars { /** * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. * The sum of these multiples is 23. * Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. * Note: If the number is a multiple of both 3 and 5, only count it once. * @param a * @return int */ public double getSumMult35(int a){ double sum = 0; for (int i = 0; i < a; i++){ if((i%3 == 0) || (i%5 == 0)){ sum += i; } } return sum; } /** * There is an array with some numbers. All numbers are equal except for one. Try to find it! * @param arr * @return */ public double findUniq(double arr[]) { double a = arr[0]; double result = arr[0]; int same = 0; for (int i = 1; i < arr.length;i++){ if(arr[i] != a){ result = arr[i]; } else { same++; } } if(same == 0){ return arr[0]; } return result; } /** * Complete the function to return true if the two arguments given are anagrams of theeach other; return false otherwise. * @param test * @param original * @return */ public boolean isAnagram(String test, String original) { char tmpTest[] = test.toLowerCase().toCharArray(); char tmpOriginal[] = original.toLowerCase().toCharArray(); Arrays.sort(tmpTest); Arrays.sort(tmpOriginal); String newTest = new String(tmpTest); String newOriginal = new String(tmpOriginal); if(newOriginal.equals(newTest)){ return true; } return false; } /** * The goal of this kata is to write a function that takes two inputs: * a string and a character. * The function will count the number of times that character appears in the string. * The count is case insensitive. * @param str * @param c * @return */ public int charCount(String str, char c) { int count = 0; char tmpStr[] = str.toLowerCase().toCharArray(); c = Character.toLowerCase(c); for(char c1 : tmpStr){ if(c1 == c){ count++; } } return count; } }
package com.deltastuido.user.interfaces; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import com.deltastuido.user.User; import com.deltastuido.user.application.UserFacade; @Named @ApplicationScoped public class UserIndex { @EJB private UserFacade facade; public List<User> popular() { return facade.getPopular(0, 4); } public long countUserProjects(String userId) { return facade.countUserProjects(userId); } }
package io.github.apfelcreme.Pipes.Listener; import io.github.apfelcreme.Pipes.Exception.ChunkNotLoadedException; import io.github.apfelcreme.Pipes.Exception.PipeTooLongException; import io.github.apfelcreme.Pipes.Exception.TooManyOutputsException; import io.github.apfelcreme.Pipes.Manager.PipeManager; import io.github.apfelcreme.Pipes.Pipe.AbstractPipePart; import io.github.apfelcreme.Pipes.Pipe.Pipe; import io.github.apfelcreme.Pipes.Pipes; import io.github.apfelcreme.Pipes.PipesConfig; import io.github.apfelcreme.Pipes.PipesItem; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import java.util.Set; /* * Copyright (C) 2016 Lord36 aka Apfelcreme * <p> * This program is free software; * you can redistribute it and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * <p> * You should have received a copy of the GNU General Public License along with * this program; if not, see <http://www.gnu.org/licenses/>. * * @author Lord36 aka Apfelcreme */ public class PlayerListener implements Listener { private final Pipes plugin; public PlayerListener(Pipes plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { if (event.getHand() != EquipmentSlot.HAND) { return; } if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { String action = plugin.getRegisteredRightClick(event.getPlayer()); if ("info".equals(action)) { event.setCancelled(true); try { plugin.unregisterRightClick(event.getPlayer()); Set<Pipe> pipes = PipeManager.getInstance().getPipes(event.getClickedBlock()); for (Pipe pipe : pipes) { Pipes.sendMessage(event.getPlayer(), pipe.getString()); pipe.highlight(event.getPlayer()); } if (pipes.isEmpty()) { Pipes.sendMessage(event.getPlayer(), PipesConfig.getText("error.noPipe")); } } catch (ChunkNotLoadedException e) { Pipes.sendMessage(event.getPlayer(), PipesConfig.getText("error.chunkNotLoaded")); } catch (TooManyOutputsException e) { Pipes.sendMessage(event.getPlayer(), PipesConfig.getText("error.tooManyOutputs", String.valueOf(PipesConfig.getMaxPipeOutputs()))); } catch (PipeTooLongException e) { Pipes.sendMessage(event.getPlayer(), PipesConfig.getText("error.pipeTooLong", String.valueOf(PipesConfig.getMaxPipeLength()))); } } else if (!event.isCancelled() && (!event.getPlayer().isSneaking() || ( (event.getItem() == null || !event.getItem().getType().isBlock() && !event.getItem().getType().isEdible()) && !event.getPlayer().hasPermission("Pipes.gui.bypass")))) { AbstractPipePart pipePart = PipeManager.getInstance().getPipePart(event.getClickedBlock()); if (pipePart != null) { event.setCancelled(true); pipePart.showGui(event.getPlayer()); } } } else if (event.getAction() == Action.LEFT_CLICK_BLOCK && event.getPlayer().isSneaking() && event.getPlayer().hasPermission("Pipes.applybook")) { if (!PipesItem.SETTINGS_BOOK.check(event.getItem())) { return; } AbstractPipePart part = PipeManager.getInstance().getPipePart(event.getClickedBlock()); if (part == null) { return; } event.setCancelled(true); try { part.applyBook(event.getItem()); Pipes.sendMessage(event.getPlayer(), PipesConfig.getText("info.settings.bookApplied")); } catch (IllegalArgumentException e){ Pipes.sendMessage(event.getPlayer(), e.getMessage()); } } } }
package LeetCode.sortingAndSearching; public class SortColor { public void sortColors(int[] nums) { int s = 0, e = nums.length - 1, i=0; while (i <= e){ if(nums[i] == 0) { swap(nums, i, s); s++; } else if(nums[i] == 2) { swap(nums, i, e); e--; } else { i++; } } } public void swap(int[] nums, int s, int e) { int temp = nums[s]; nums[s] = nums[e]; nums[e] = temp; } public static void main(String[] args) { int[] inp = {2,0,2,1,1,0}; SortColor s = new SortColor(); s.sortColors(inp); for (int i = 0; i < inp.length; i++) { System.out.print(inp[i]); System.out.print('\t'); } } }
package eu.lsem.bakalarka.dao.categories; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import eu.lsem.bakalarka.model.Category; import java.util.List; public class FieldsOfStudyDaoImpl extends SqlMapClientDaoSupport implements CategoryDao{ public Category getCategory(Integer id) { return (Category) getSqlMapClientTemplate().queryForObject("FieldsOfStudy.getFieldOfStudy", id); } @SuppressWarnings("unchecked") public List<Category> getCategories() { final List<Category> list = getSqlMapClientTemplate().queryForList("FieldsOfStudy.getFieldOfStudy", null); return list; } public void updateCategory(Category category) { getSqlMapClientTemplate().update("FieldsOfStudy.updateFieldOfStudy", category); } public void saveCategory(Category category) { getSqlMapClientTemplate().insert("FieldsOfStudy.insertFieldOfStudy", category); } public void deleteCategory(Integer id) { getSqlMapClientTemplate().delete("FieldsOfStudy.deleteFieldOfStudy", id); } }
package main; import java.util.Scanner; import person.Author; import biblio.Entry; import csv.CSV; import biblio.Query; import biblio.Bibliography; public class Main { public static void main(String[] args) { Author author = null; String publisher = null; int format = Entry.FORMAT_RAW; for (int i = 0; i < args.length; i+=2) { if (i+1 == args.length) break; String paramName = args[i]; String paramValue = args[i+1]; if (paramName.equals("publisher=")) { publisher = paramValue; author = null; } else if (paramName.equals("author=")) { author = Author.make(paramValue); publisher = null; } else if (paramName.equals("format=")) { if (paramValue.equals("raw")) format = Entry.FORMAT_RAW; else if (paramValue.equals("authorYear")) format = Entry.FORMAT_AUTHOR_YEAR; else if (paramValue.equals("authorYearCompact")) format = Entry.FORMAT_AUTHOR_YEAR_COMPACT; } } Query q = null; if (publisher != null) q = Query.byPublisher(publisher); else if (author != null) q = Query.byAuthor(author); CSV csv = CSV.read(new Scanner(System.in)); Bibliography b = new Bibliography(csv); if (q != null) b.filter(q); System.out.print(b.show(format)); } }
/* * 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 edu.prueba.co; /** * * @author ESTUDIANTE */ public class Cliente extends Persona { private String CodigoCliente; public Cliente(String Nombre, String Apellido, String Documento) { super(Nombre, Apellido, Documento); } public Cliente(){} public String getCodigoCliente() { return CodigoCliente; } public void setCodigoCliente(String CodigoCliente) { this.CodigoCliente = CodigoCliente; } @Override public String Saludar() { return "Mi nombre es "+this.Nombre+" Mi apellido es "+this.Apellido+" y mi codigoCliente es:"+this.CodigoCliente; } }
package fr.projetcookie.boussole; import android.location.Location; public interface LocationListener { public void locationChanged(Location l); }
package lecturauno; // Este programa prueba la clase LeerArchivoTexto. public class PruebaLeerArchivoTexto { public static void main(String args[]) { //LeerArchivoTexto.leerRegistros01(); //LeerArchivoTexto.leerRegistros02(); LeerArchivoTexto.leerRegistros03(); } // fin de main } // fin de la clase PruebaLeerArchivoTexto /** * ************************************************************************ * (C) Copyright 1992-2007 por Deitel & Associates, Inc. y * Pearson Education, * Inc. Todos los derechos reservados. * * ************************************************************************ */
package bot_output; import java.io.IOException; import java.util.HashMap; import utils.StaticVariables; //Basic program to convert english phrases to morse code public class Morse_Code { private String morseCode; private Writer writer = new Writer(); public Morse_Code() { StaticVariables.programRunning = true; } //Displays program instructions message to user public void introduce_morse() { try { writer.writeMessage("Please enter a string to be encoded ($exit to leave program):"); } catch (IOException e) { e.printStackTrace(); } } //Converts from english to morse public void encode(String englishString) { System.out.println(englishString); String letter; String stringToMorse = ""; morseCode = englishString; morseCode = morseCode.trim(); for (int i = 0; i < morseCode.length(); i++) { letter = morseCode.substring(i, i + 1); if (letter.equals(" ")) { stringToMorse = stringToMorse + EnglishToMorse.get(letter); } else { letter = letter.toUpperCase(); stringToMorse = stringToMorse + EnglishToMorse.get(letter) + " "; } } stringToMorse.trim(); //If program is running and user isn't trying to exit //Send message of results if(englishString.equals("$exit")) { StaticVariables.programRunning = false; } else { try { //results writer.writeMessage(englishString + " encoded: " + stringToMorse); introduce_morse(); } catch (IOException e) { e.printStackTrace(); } } } //Hashmap stores morse code data private static HashMap<String, String> EnglishToMorse = new HashMap<String, String>(); static { EnglishToMorse.put("A", ".-"); EnglishToMorse.put("B", "-..."); EnglishToMorse.put("C", "-.-."); EnglishToMorse.put("D", "-.."); EnglishToMorse.put("E", "."); EnglishToMorse.put("F", "..-."); EnglishToMorse.put("G", "--."); EnglishToMorse.put("H","...."); EnglishToMorse.put("I", ".."); EnglishToMorse.put("J", ".---"); EnglishToMorse.put("K", "-.-"); EnglishToMorse.put("L", ".-.."); EnglishToMorse.put("M", "--"); EnglishToMorse.put("N", "-."); EnglishToMorse.put("O", "---"); EnglishToMorse.put("P", ".--."); EnglishToMorse.put("Q", "--.-"); EnglishToMorse.put("R", ".-."); EnglishToMorse.put("S", "..."); EnglishToMorse.put("T", "-"); EnglishToMorse.put("U", "..-"); EnglishToMorse.put("V", "...-"); EnglishToMorse.put("W", ".--"); EnglishToMorse.put("X", "-..-"); EnglishToMorse.put("Y", "-.--"); EnglishToMorse.put("Z", "--.."); EnglishToMorse.put(" ", " "); EnglishToMorse.put("0", "-----"); EnglishToMorse.put("1", ".----"); EnglishToMorse.put("2", "..---"); EnglishToMorse.put("3", "...--"); EnglishToMorse.put("4", "....-"); EnglishToMorse.put("5", "....."); EnglishToMorse.put("6", "-...."); EnglishToMorse.put("7", "--..."); EnglishToMorse.put("8", "---.."); EnglishToMorse.put("9", "----."); EnglishToMorse.put(".", ".-.-"); EnglishToMorse.put(",", "--..--"); EnglishToMorse.put("?", "..--.."); EnglishToMorse.put("!", "-.-.--"); EnglishToMorse.put("SOS", "···−−−···."); } }
/* 1. Создать класс Автомобиль (англ. Car), с полями “Год выпуска”, “Цвет”, “Модель”. Создать геттеры и сеттеры для каждого поля. Создать экземпляр класса Автомобиль, задать сеттером каждое поле, вывести в консоль значение каждого поля геттером. Созданный вами класс должен отвечать принципам инкапсуляции. */ package day5; public class Task1 { public static void main(String[] args) { Car audi = new Car(); audi.setYearOfManufacture(2017); System.out.println(audi.getYearOfManufacture()); audi.setColor("Blue"); System.out.println(audi.getColor()); audi.setModel("A4"); System.out.println(audi.getModel()); } }
package collectiondemos; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class ArrayListDemo3 { public static void main(String[] args) { //Array String arr[] = {"Dog","Cat","Elephant","Deer","Tiger"}; for(String value:arr) { System.out.println(value); } //Converting array in to arraylist object : Using of Arrays.asList(array); ArrayList al= new ArrayList(Arrays.asList(arr)); System.out.println(al); } }
package com.cszjkj.aisc.dms_customer.service; import com.cszjkj.aisc.cm_common.dto.CustomerDTO; import com.cszjkj.aisc.cm_customer.ICustomerService; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class TDmsCustomerService { public final static Logger logger = Logger.getLogger(TDmsCustomerService.class.getCanonicalName()); public final static List<Integer> tests = new ArrayList<>(); private final static String zookeeperHost = "192.168.2.38"; private final static String zookeeperPort = "2181"; @BeforeAll public static void init() { tests.add(1); // 用户接口测试 tests.add(2); } @DisplayName("测试查询符合条件客户列表接口") @Test public void call_getCustomers_001() { int testId = 1; if (!tests.contains(testId)) { return; } String targetRst = "ok"; String rst = "ok"; ICustomerService service = getCustomerService(); List<CustomerDTO> customers = service.getCustomers("", null, null, 0, 1000); logger.info("customer:" + customers + "! v0.0.1"); Assertions.assertEquals(targetRst, rst); } @DisplayName("测试添加新客户接口") @Test public void test_addCustomer_001() { int testId = 2; if (!tests.contains(testId)) { return; } String targetRst = "ok"; String rst = "ok"; ICustomerService service = getCustomerService(); CustomerDTO dto = new CustomerDTO(); service.addCustomer(dto); Assertions.assertEquals(targetRst, rst); } private ICustomerService getCustomerService() { ReferenceConfig<ICustomerService> reference = new ReferenceConfig<>(); reference.setApplication(new ApplicationConfig("first-dubbo-consumer")); reference.setRegistry(new RegistryConfig("zookeeper://" + zookeeperHost + ":" + zookeeperPort)); reference.setInterface(ICustomerService.class); return reference.get(); } @DisplayName("单元测试模板") @Test public void test_template() { int testId = 2; if (!tests.contains(testId)) { return; } String targetRst = "ok"; String rst = "ok"; Assertions.assertEquals(targetRst, rst); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.util.models; import static de.hybris.platform.cmsfacades.util.builder.CMSSiteModelBuilder.fromModel; import static de.hybris.platform.cmsfacades.util.models.CMSSiteModelMother.TemplateSite.APPAREL; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.joda.time.DateTime.now; import de.hybris.platform.catalog.model.CatalogVersionModel; import de.hybris.platform.cms2.model.contents.ContentCatalogModel; import de.hybris.platform.cms2.model.site.CMSSiteModel; import de.hybris.platform.cms2.servicelayer.daos.CMSContentCatalogDao; import de.hybris.platform.cms2.servicelayer.daos.CMSSiteDao; import de.hybris.platform.cmsfacades.util.builder.CMSSiteModelBuilder; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.springframework.beans.factory.annotation.Required; public class CMSSiteModelMother extends AbstractModelMother<CMSSiteModel> { public enum TemplateSite { APPAREL(buildName(Locale.ENGLISH, "Apparel"), SiteModelMother.APPAREL, "http://apparel.com", "url-media-thumbnail"), // POWER_TOOLS(buildName(Locale.ENGLISH, "Power Tools"), SiteModelMother.POWERTOOL, "http://power.com", "url-media-thumbnail"), // ELECTRONICS(buildName(Locale.ENGLISH, "Electronics"), SiteModelMother.ELECTRONICS, "http://electric.com", "url-media-thumbnail"); private final String uid; private final Map<String, String> name; private final String baseUrl; private final String thumbnailUri; TemplateSite(final Map<String, String> name, final String uid, final String baseUrl, final String thumbnailUri) { this.name = name; this.uid = uid; this.baseUrl = baseUrl; this.thumbnailUri = thumbnailUri; } public String getUid() { return uid; } public Map<String, String> getNames() { return name; } public String getName(final Locale locale) { return name.get(locale.getLanguage()); } public String getFirstInstanceOfName() { final Map<String, String> value = getNames(); final String firstKey = value.keySet().stream().findFirst().get(); return value.get(firstKey); } public String getBaseUrl() { return baseUrl; } public String getThumbnailUri() { return thumbnailUri; } public static Map<String, String> buildName(final Locale locale, final String value) { final Map<String, String> map = new HashMap<>(); map.put(locale.getLanguage(), value); return map; } } private CMSSiteDao cmsSiteDao; private CMSContentCatalogDao cmsContentCatalogDao; public CMSSiteModel createSiteWithTemplate(final TemplateSite site, final CatalogVersionModel... catalogs) { return createSiteWithMinimumParameters(site.getFirstInstanceOfName(), site.getUid(), site.getBaseUrl(), catalogs); } protected CMSSiteModel createSiteWithMinimumParameters(final String name, final String uid, final String url, final CatalogVersionModel[] catalogs) { final List<ContentCatalogModel> contentCatalogs = asList(catalogs).stream().map(this::getContentCatalogFromCatalogVersion) .collect(toList()); return getFromCollectionOrSaveAndReturn(() -> getCmsSiteDao().findCMSSitesById(uid), () -> fromModel(defaultSite()) .withEnglishName(name).withUid(uid).withRedirectUrl(url).usingCatalogs(contentCatalogs).build()); } protected ContentCatalogModel getContentCatalogFromCatalogVersion(final CatalogVersionModel catalogVersionModel) { return getCmsContentCatalogDao().findContentCatalogById(catalogVersionModel.getCatalog().getId()); } protected CMSSiteModel defaultSite() { return CMSSiteModelBuilder.aModel().withEnglishName(APPAREL.getFirstInstanceOfName()).active() .from(now().minusDays(5).withTimeAtStartOfDay().toDate()).until(now().plusDays(5).withTimeAtStartOfDay().toDate()) .withUid(APPAREL.getUid()).withRedirectUrl(APPAREL.getBaseUrl()).build(); } public CMSSiteDao getCmsSiteDao() { return cmsSiteDao; } @Required public void setCmsSiteDao(final CMSSiteDao cmsSiteDao) { this.cmsSiteDao = cmsSiteDao; } @Required public void setCmsContentCatalogDao(final CMSContentCatalogDao cmsContentCatalogDao) { this.cmsContentCatalogDao = cmsContentCatalogDao; } public CMSContentCatalogDao getCmsContentCatalogDao() { return cmsContentCatalogDao; } }
package com.example.xyzreader.remote; import android.os.AsyncTask; import android.util.Log; import com.example.xyzreader.database.DatabaseBook; import com.example.xyzreader.database.XYZDatabase; import com.example.xyzreader.domain.Book; import com.example.xyzreader.utils.JsonUtils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class BooksTask extends AsyncTask<URL, Void, Boolean> { private final XYZDatabase mXYZDatabase; private final RemoteListener mRemoteListener; private static final String TAG = BooksTask.class.getSimpleName(); public BooksTask(XYZDatabase xyzDatabase, RemoteListener remoteListener) { mXYZDatabase = xyzDatabase; mRemoteListener = remoteListener; } @Override protected void onPreExecute() { super.onPreExecute(); mRemoteListener.preExecute(); } @Override public Boolean doInBackground(URL... params) { URL url = params[0]; StringBuilder result = new StringBuilder(); HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null){ result.append(line); } Log.d(TAG, result.toString()); List<Book> books = JsonUtils.parseBooksJson(result.toString()); for (int i = 0; i < books.size(); i++) { Book book = books.get(i); final DatabaseBook databaseRecipe = new DatabaseBook( book.getId(), book.getTitle(), book.getAuthor(), book.getBody(), book.getThumb(), book.getPhoto(), book.getAspect_ratio(), book.getPublished_date() ); mXYZDatabase.xyzDao().insertBook(databaseRecipe); } } catch (IOException e) { e.printStackTrace(); return false; } finally { urlConnection.disconnect(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean data) { mRemoteListener.postExecute(); } @Override protected void onCancelled() { super.onCancelled(); mRemoteListener.postExecute(); } }
package com.hotv.springboot.entity; /** * 角色资源 * * @author hotv * @since 2017-11-11 */ public class SysRoleResource { /** * roleId */ private Long roleId; /** * 角色资源 */ private String resource; /** * roleId */ public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } /** * 角色资源 */ public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } }
package com.trs.om.service.impl; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.trs.om.rbac.AuthorizationException; import com.trs.om.rbac.IPrivilegeManager; import com.trs.om.bean.Privilege; import com.trs.om.bean.DataPermission; import com.trs.om.dao.DataPermissionDao; import com.trs.om.exception.TRSOMException; import com.trs.om.service.DataPermissionService; import com.trs.om.service.EncryptService; import com.trs.om.service.UserService; /** * 接口{@link DataPermissionService}的实现类。 * @author wengjing * */ public class DataPermissionServiceImpl implements DataPermissionService { //fields --------------------------------------------------------------------- private DataPermissionDao dataPermissionDao; private IPrivilegeManager privilegeManager; private UserService userService; public DataPermissionServiceImpl() { EncryptService obj; try { obj = EncryptService.getInstance(); obj.checkLicence(); } catch (Exception e) { throw new TRSOMException("无法获得或者校验注册码:"+e.getMessage(),e); } } //methods --------------------------------------------------------------------- @Transactional public void addDataPermission(DataPermission dataPermission) { //dataPermission.setId(IdGenerator.newId()); dataPermission.setModule("数据权限"); dataPermissionDao.makePersistent(dataPermission); } @SuppressWarnings("unchecked") @Transactional public void deleteDataPermissions(Long[] ids) { if(null!=ids&&ids.length>0){ for(Long id:ids){ DataPermission permission=dataPermissionDao.findById(id, false); if(null!=permission){ try { //删除权限与角色之间的关系 List<Privilege> privileges=privilegeManager.findPrivileges(id, null); for(Privilege privilege:privileges) privilegeManager.deletePrivilege(privilege.getId()); } catch (AuthorizationException e) { throw new TRSOMException(e); } //删除权限 dataPermissionDao.makeTransient(permission); } } } } @Transactional public boolean isNameExisting(String name, Long excluedId) { return dataPermissionDao.isNameExisting(name, excluedId); } @Transactional public List<DataPermission> listAllDataPermissions() { return dataPermissionDao.findAll(); } @Transactional public void updateDataPermission(DataPermission dataPermission) { dataPermissionDao.makePersistent(dataPermission); } @Transactional public List<DataPermission> listDataPermissionsByUserId(Long userId,String tableName) { return dataPermissionDao.find(userId,tableName); } //accessors --------------------------------------------------------------------- public DataPermissionDao getDataPermissionDao() { return dataPermissionDao; } public void setDataPermissionDao(DataPermissionDao dataPermissionDao) { this.dataPermissionDao = dataPermissionDao; } public IPrivilegeManager getPrivilegeManager() { return privilegeManager; } public void setPrivilegeManager(IPrivilegeManager privilegeManager) { this.privilegeManager = privilegeManager; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } }
package zen.users; import java.util.Scanner; public abstract class Usuarios { protected int codigoId; protected String nome; protected String senha; protected String email; protected String tipoUsuario; protected Scanner sc = new Scanner(System.in); public int getCodigoId() { return codigoId; } public void setCodigoId(int codigoId) { this.codigoId = codigoId; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getTipoUsuario() { return tipoUsuario; } public void setTipoUsuario(String tipoUsuario) { this.tipoUsuario = tipoUsuario; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } // Método cadastrar usuario public void cadastrar() { System.out.print("INFORME O NOME: "); String nome = sc.next(); this.setNome(nome); System.out.print("INFORME A SENHA: "); String senha = sc.next(); this.setSenha(senha); System.out.print("INFORME O EMAIL: "); String email = sc.next(); this.setEmail(email); } }
/** * */ package mas2019.group8; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import mas2019.group8.help_components.Gahboninho_Offering; import mas2019.group8.help_components.NiceTitForTat_Offering; import mas2019.group8.help_components.TKI; import mas2019.group8.help_components.TheNegotiatorReloaded_Offering; import mas2019.group8.help_components.Yushu_Offering; import genius.core.Bid; import genius.core.bidding.BidDetails; import genius.core.boaframework.NegotiationSession; import genius.core.boaframework.OMStrategy; import genius.core.boaframework.OfferingStrategy; import genius.core.boaframework.OpponentModel; import genius.core.boaframework.SortedOutcomeSpace; import genius.core.issue.Issue; import genius.core.issue.Value; import genius.core.utility.AbstractUtilitySpace; /** * @author Andrea Scorza, Diego Staphorst, Erik Lokhorst, Ingmar van der Geest * */ public class Group8_BS extends OfferingStrategy { // /** Outcome space */ private SortedOutcomeSpace outcomespace; TKI tki = new TKI(); /** Bidding strategies */ public List<OfferingStrategy> bid_methods = new ArrayList<OfferingStrategy>(); /** Bidding weights for current bid */ public List<Double> bid_weights = new ArrayList<Double>(); /** Bidding utility space of current negotiation */ private AbstractUtilitySpace abstractUtilitySpace; // counter int counter = 0; public Group8_BS() { // TODO Auto-generated constructor stub } /** * Initiate agents, weights for the bidding strategy */ @Override public void init(NegotiationSession negoSession, OpponentModel model, OMStrategy oms, Map<String, Double> parameters) throws Exception { this.negotiationSession = negoSession; this.opponentModel = model; this.omStrategy = oms; // Initiate bidding strategies bid_methods.add(new TheNegotiatorReloaded_Offering(negoSession, model, oms)); bid_methods.add(new Gahboninho_Offering(negoSession, model, oms, parameters)); bid_methods.add(new Yushu_Offering(negoSession, model, oms, parameters)); bid_methods.add(new NiceTitForTat_Offering(negoSession, model, oms, parameters)); // Initiate bidding weights, those weight are the static basic weight and were calculated outside genius //Explanation in the report bid_weights.add(0.190416149); //NEGO bid_weights.add(0.197129227); //GAHBO bid_weights.add(0.242762364); //YUSHU bid_weights.add(0.169692259); //NICE outcomespace = new SortedOutcomeSpace(negotiationSession.getUtilitySpace()); negotiationSession.setOutcomeSpace(outcomespace); } //This method uses the TKI values, and the coefficient calculated before to //redistribute the weight of our panel member based on the opponent //We decided to call this method after five rounds in order to have a minimum sufficient amount of data public void Weight() { //calculation of the weights based on opponent double[] sd_coeff = new double[4]; double[] coop_coeff = new double[4]; double[] sd_cut = new double[4]; double[] coop_cut = new double[4]; //bid_weights.set(0, 0.3); //Those are the coefficients calculated with the training data //More info in the report sd_coeff[0] = 0.742159262; //NEGO sd_coeff[1] = 1.105698694; //GABO sd_coeff[2] = 1.46240313; //YUSHU sd_coeff[3] = -0.96443325; //NICE coop_coeff[0] = -0.343431038; coop_coeff[1] = 0.859597362; coop_coeff[2] = 1.29910522; coop_coeff[3] = -3.074196406; sd_cut[0] = 0.832969372; sd_cut[1] = 0.819401409; sd_cut[2] = 0.689557158; sd_cut[3] = 0.814648053; coop_cut[0] = 0.884449006; coop_cut[1] = 1.105698694; coop_cut[2] = 0.757832995; coop_cut[3] = 0.775181624; double[] x = new double[4]; double stand_dev = TKI.standard_deviation(); //implementation of the value collected by the TKI double avg_coop = TKI.average_cooperat(); for (int i = 0; i < 4 ; i++) { x[i] = (sd_coeff[i] * stand_dev) + sd_cut[i]; double y = (coop_coeff[i] * avg_coop) + coop_cut[i]; x[i] = (x[i] + y) / 2; } //Normalization of the weights double sum = x[0] + x[1] + x[2] + x[3]; double coeff = 1 / sum; bid_weights.set(0, coeff * x[0]); bid_weights.set(1, coeff * x[1]); bid_weights.set(2, coeff * x[2]); bid_weights.set(3, coeff * x[3]); } @Override public BidDetails determineOpeningBid() { return determineNextBid(); } /** * Offering strategy which retrieves the bids of multiple agents. * The function loops over all the bids and determines the values with * the highest weight. */ @Override public BidDetails determineNextBid() { counter++; if (counter > 4) this.Weight(); // Pools all bids, separated in issues, with its value and determined // weight for this bid per agent in the variable bids HashMap<Issue, HashMap<Value, Double>> bids = new HashMap<Issue, HashMap<Value, Double>>(); HashMap<Value, Double> bid_with_weight; for (int i = 0; i < bid_methods.size(); i++) { OfferingStrategy agent_bs = bid_methods.get(i); Double agent_weight = bid_weights.get(i); Bid agent_bid = agent_bs.determineNextBid().getBid(); for (Issue issue : negotiationSession.getIssues()) { if (i == 0) bid_with_weight = new HashMap<Value, Double>(); else bid_with_weight = bids.get(issue); bid_with_weight.merge(agent_bid.getValue(issue), agent_weight, Double::sum); bids.put(issue, bid_with_weight); } } // Get issues with highest overall weight // If multiple with same values randomly pick one int i = 1; HashMap<Integer, Value> bid_to_determine = new HashMap<>(); for (Issue issue : negotiationSession.getIssues()) { Double max_weight = 0.0; Value value_with_heighest_weight = null; for (Entry<Value, Double> value_with_weight : bids.get(issue).entrySet()) { if (max_weight < value_with_weight.getValue()) { max_weight = value_with_weight.getValue(); value_with_heighest_weight = value_with_weight.getKey(); } } bid_to_determine.put(i, value_with_heighest_weight); i++; } // Our Acceptance strategy is based on the Utility we offer to the other agent double utility_bid = this.abstractUtilitySpace.getUtility(new Bid(negotiationSession.getDomain(), bid_to_determine)); nextBid = new BidDetails(new Bid(negotiationSession.getDomain(), bid_to_determine), utility_bid); return nextBid; } /** * To determine the utility for the offer we make */ public void setAbstractUtilitySpace(AbstractUtilitySpace abstractUtilitySpace) { this.abstractUtilitySpace = abstractUtilitySpace; } public NegotiationSession getNegotiationSession() { return negotiationSession; } @Override public String getName() { return "Group8_BS"; } }
package com.todolist.app.ws.io.repositories; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.todolist.app.ws.io.entity.ToDoItemEntity; import com.todolist.app.ws.io.entity.ToDoListEntity; public interface TodoItemRepository extends CrudRepository<ToDoItemEntity, Long> { List<ToDoItemEntity> findAllBytoDoListDetails(ToDoListEntity todolistEntity); ToDoItemEntity findByTodoItemId(String todoitemId); ToDoItemEntity findByName(String todoitemName); }
package xdpm.nhom11.angrybirdsproject.xmlbird; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.andengine.entity.IEntity; import org.andengine.util.SAXUtils; import org.andengine.util.level.EntityLoader; import org.andengine.util.level.simple.SimpleLevelEntityLoaderData; import org.andengine.util.level.simple.SimpleLevelLoader; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import android.content.ContextWrapper; import android.content.res.AssetManager; import android.util.Log; public class DAOBlock { static final String X = "x"; static final String Y = "y"; static final String ROTATION = "rotation"; public static final String TAG_LISTWORLD = "LISTWORLD"; public static final String TAG_LISTBIRD = "LISTBIRD"; public static final String TAG_LISTPIG = "LISTPIG"; public static final String TAG_LISTBlOCK = "LISTBLOCK"; public static final String TAG_WORLD = "WORLD"; public static final String TAG_CHAPTER = "CHAPTER"; public static final String TAG_LEVEL = "LEVEL"; public static final String TAG_BACKGROUND = "BACKGROUND"; public static final String TAG_SLINGSHOT = "SLINGSHOT"; public static final String TAG_BIRD = "BIRD"; public static final String TAG_PIG = "PIG"; public static final String TAG_BLOCK = "BLOCK"; public static final String KEY_ID = "id"; public static final String KEY_LOCKED = "locked"; public static final String KEY_HIGHSCORE = "highscore"; public static final String KEY_NUMSTAR = "numstar"; public static final String KEY_WIDTH = "width"; public static final String KEY_HEIGHT = "height"; public static final String KEY_BGCOLOR = "bgcolor"; public static final String KEY_X = "x"; public static final String KEY_Y = "y"; public static final String KEY_ROTATION = "rotation"; public static final String KEY_TYPE = "type"; public static final String KEY_FINALSCORE = "finalscore"; public static final String KEY_LIFEVALUE = "lifevalue"; public static final String KEY_SCORE = "score"; public ArrayList<DTOBlock> load(ContextWrapper contextwrapper) throws IOException, ParserConfigurationException, SAXException { ArrayList<DTOBlock> ListBlock = new ArrayList<DTOBlock>(); AssetManager assetManager = contextwrapper.getAssets(); InputStream in = assetManager.open("gfx/dataxml/BLOCK.xml"); DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document doc = builder.parse(in, null); NodeList blocks = doc.getElementsByTagName("BLOCK"); for (int i = 0; i < blocks.getLength(); i++) { DTOBlock block = new DTOBlock(); block.id = blocks.item(i).getAttributes().getNamedItem(KEY_ID) .getNodeValue().toString(); block.lifevalue = Integer.parseInt(blocks.item(i).getAttributes() .getNamedItem(KEY_LIFEVALUE).getNodeValue().toString()); block.score = Float.parseFloat(blocks.item(i).getAttributes() .getNamedItem(KEY_SCORE).getNodeValue().toString()); block.x = Float.parseFloat(blocks.item(i).getAttributes() .getNamedItem(X).getNodeValue().toString()); block.y = Float.parseFloat(blocks.item(i).getAttributes() .getNamedItem(Y).getNodeValue().toString()); block.rotation = Float.parseFloat(blocks.item(i).getAttributes() .getNamedItem(KEY_ROTATION).getNodeValue().toString()); ListBlock.add(block); } return ListBlock; } public static ArrayList<DTOBlock> load(SimpleLevelLoader loader) { final ArrayList<DTOBlock> ListBlock = new ArrayList<DTOBlock>(); loader.registerEntityLoader(new EntityLoader<SimpleLevelEntityLoaderData>( TAG_BLOCK) { @Override public IEntity onLoadEntity(String pEntityName, IEntity pParent, Attributes pAttributes, SimpleLevelEntityLoaderData pEntityLoaderData) throws IOException { // TODO Auto-generated method stub DTOBlock dtoblock = new DTOBlock(); dtoblock.id = SAXUtils.getAttributeOrThrow(pAttributes, KEY_ID); dtoblock.x = SAXUtils.getFloatAttribute(pAttributes, KEY_X, 0); dtoblock.y = SAXUtils.getFloatAttribute(pAttributes, KEY_Y, 0); dtoblock.rotation = SAXUtils.getFloatAttribute(pAttributes, ROTATION, 0); dtoblock.lifevalue = SAXUtils.getFloatAttribute(pAttributes, KEY_LIFEVALUE, 5000); dtoblock.score = SAXUtils.getIntAttribute(pAttributes, KEY_SCORE, 0); dtoblock.type = SAXUtils.getAttribute(pAttributes, KEY_TYPE, "ice"); ListBlock.add(dtoblock); return null; } }); return ListBlock; } }
package com.jim.multipos.utils.rxevents.main_order_events; import com.jim.multipos.data.db.model.customer.Customer; /** * Created by developer on 27.02.2018. */ public class CustomerEvent { private Customer customer; private Customer newCustomer; private int type; public CustomerEvent(Customer customer, int type) { this.customer = customer; this.type = type; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Customer getNewCustomer() { return newCustomer; } public void setNewCustomer(Customer newCustomer) { this.newCustomer = newCustomer; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
/* * Copyright (c) 2021. Alpha Coders */ package com.abhishek.Videogy.download; import java.io.Serializable; public class DownloadVideo implements Serializable { public String size; public String type; public String link; public String name; public String page; public String website; public boolean chunked; }
import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlSeeAlso; import java.util.ArrayList; import java.util.List; @XmlRootElement @XmlSeeAlso(Aftale.class) public class AftaleListe { List<Aftale> aftaleliste = new ArrayList<>(); public List<Aftale> getAftaler() { return aftaleliste; } public void addAftaler(Aftale aftale) { aftaleliste.add(aftale); } }
package es.utils.mapper.impl.element; import java.util.Objects; import java.util.function.BiConsumer; /** * This class handle the logic of a generic {@code setter} operation.<br> * @author eschoysman * * @param <U> the type of the destination object * @param <SETTER_IN> the type of the input of the {@code setter} operation */ public class Setter<U,SETTER_IN> { private static int id_incr = 0; private int id = ++id_incr; private String name; private BiConsumer<U,SETTER_IN> setter; private static final Setter<?,?> EMPTY = new Setter<>("setter_id_0",(obj,setter)->{}); /** * Create a {@code Ssetter} instance with a identifier and a operation * @param setter the {@code setter} operation */ public Setter(BiConsumer<U,SETTER_IN> setter) { setName("setter_id_"+id); setSetter(setter); } /** * Create a {@code Setter} instance with a identifier and a operation * @param name the name identifier of the current {@code setter} * @param setter the {@code setter} operation */ public Setter(String name, BiConsumer<U,SETTER_IN> setter) { setName(name); setSetter(setter); } /** * Returns an empty {@code setter} with no name and empty operation * @return an empty {@code setter} with no name and empty operation * @param <U> the type of the origin object * @param <SETTER_IN> the type of the result of the {@code setter} operation */ public static <U,SETTER_IN> Setter<U,SETTER_IN> empty() { @SuppressWarnings("unchecked") Setter<U,SETTER_IN> empty = (Setter<U,SETTER_IN>)EMPTY; return empty; } /** * The unique id identifier of the current {@code setter} * @return the unique id identifier of the current {@code setter} */ public int getId() { return id; } /** * The name identifier of the current {@code setter} * @return the name identifier of the current {@code setter} */ public String getName() { return name; } private void setName(String name) { this.name = Objects.requireNonNull(name,"The name of the setter cannot be null"); } private void setSetter(BiConsumer<U,SETTER_IN> setter) { this.setter = Objects.requireNonNull(setter,"The setter operation cannot be null"); } /** * Apply the current {@code setter} operation to the destination object * @param dest the destination object * @param data the value to set in the destination object */ public void apply(U dest, SETTER_IN data) { setter.accept(dest,data); } /** * Returns a human readable string of the current {@code Setter} */ @Override public String toString() { return "Setter[id="+id+",name="+getName()+"]"; } }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.query; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import edu.umich.verdict.VerdictJDBCContext; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.parser.VerdictSQLBaseVisitor; import edu.umich.verdict.parser.VerdictSQLParser; import edu.umich.verdict.util.VerdictLogger; public class CreateTableQuery extends Query { public CreateTableQuery(VerdictJDBCContext vc, String q) { super(vc, q); } @Override public void compute() throws VerdictException { VerdictLogger.error(this, "Not supported."); // VerdictSQLLexer l = new VerdictSQLLexer(new ANTLRInputStream(queryString)); // VerdictSQLParser p = new VerdictSQLParser(new CommonTokenStream(l)); // CreateTableQueryParser parser = new CreateTableQueryParser(); // parser.visit(p.create_table()); // // // read parameters and print them for test // System.out.println("table name: " + parser.getTableName()); // // for (Pair<String, String> colDef : parser.getColumnDefinitions()) { // System.out.println(String.format("col name: %s, col type: %s", // colDef.getKey(), colDef.getValue())); // } // // for (Map.Entry<String, String> e : parser.getOptions().entrySet()) { // System.out.println(String.format("option: %s, value: %s", e.getKey(), // e.getValue())); // } // // return null; } } class CreateTableQueryParser extends VerdictSQLBaseVisitor<Void> { private String tableName; private List<Pair<String, String>> columnDefinitions; private Map<String, String> options; public CreateTableQueryParser() { columnDefinitions = new ArrayList<Pair<String, String>>(); options = new HashMap<String, String>(); } public String getTableName() { return tableName; } public List<Pair<String, String>> getColumnDefinitions() { return columnDefinitions; } public Map<String, String> getOptions() { return options; } @Override public Void visitCreate_table(VerdictSQLParser.Create_tableContext ctx) { tableName = ctx.table_name().getText(); System.out.println(ctx.getText()); return visitChildren(ctx); } @Override public Void visitColumn_definition(VerdictSQLParser.Column_definitionContext ctx) { String colName = ctx.column_name().getText(); String type = ctx.data_type().getText(); columnDefinitions.add(Pair.of(colName, type)); return visitChildren(ctx); } // @Override // public Void // visitCreate_table_option(VerdictSQLParser.Create_table_optionContext ctx) { // String key = ctx.table_option_key.getText(); // String value = ctx.table_option_value.getText(); // options.put(key, value); // return visitChildren(ctx); // } }
import java.io.BufferedReader; import java.io.InputStreamReader; public class CoinsGame { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input; int numOfLinesRead = 0; int k=0,l=0,m=0; String [] strArray = null; while (((input = br.readLine()) != null && input.trim().length() != 0)) { numOfLinesRead++; if(numOfLinesRead == 1) { strArray = input.split(" "); k = Integer.parseInt(strArray[0]); l = Integer.parseInt(strArray[1]); m = Integer.parseInt(strArray[2]); } else { strArray = input.split(" "); int [] towers = new int [m]; for(int i=0;i<m;i++){ towers[i] = Integer.parseInt(strArray[i]); } printWinner(towers,k,l,m); break; } } } catch(Exception e) { e.printStackTrace(); } } private static void printWinner(int[] towers, int k, int l, int m) { int MAX = 1000000; boolean [] bool = new boolean [MAX+1]; for(int i=1;i<=MAX;i++){ int tmp1 = i-k; int tmp2 = i-l; if(i==1 || i==k || i==l){ bool[i]= true; } else if(!bool[i-1]){ bool[i] = true; } else if(tmp1>=1 && !bool[tmp1]){ bool[i] = true; } else if(tmp2>=1 && !bool[tmp2]){ bool[i] = true; } } for(int j=0;j<m;j++){ int n = towers[j]; if(bool[n]){ log("A"); } else { log("B"); } } } static void log(Object o) { System.out.print(o.toString()); } }
package com.example.recycleviewactivity; import android.content.Context; import android.icu.util.UniversalTimeScale; import android.text.Layout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyTViewHolder> { private Context context; private List<Film> dataList; public class MyTViewHolder extends RecyclerView.ViewHolder { RelativeLayout backgroundColor; ImageView photo; TextView name; TextView genre; TextView minute; public MyTViewHolder(View view){ super(view); name = view.findViewById(R.id.film_name); genre = view.findViewById(R.id.film_zhanr); minute = view.findViewById(R.id.film_minute); photo = view.findViewById(R.id.film_photo); } } public RecyclerViewAdapter(Context context,List<Film> dataList){ this.context = context; this.dataList = dataList; } @NonNull @Override public MyTViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView; itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.film_item,parent,false); return new MyTViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MyTViewHolder holder, int position) { Film item = dataList.get(position); Glide.with(context.getApplicationContext()).load(item.getPhoto()) .placeholder(R.drawable.ic_baseline_live_tv_24) .into(holder.photo); holder.name.setText(item.getname()); holder.genre.setText(item.getGenre()); holder.minute.setText(item.getminute()); } @Override public int getItemCount() { return dataList.size(); } }
package com.wipe.zc.journey.util; import java.util.Calendar; /** * 时间工具包 */ public class TimeUtil { /** * 毫秒值转换为时间 */ public static Calendar longToTime(long millis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(millis); return calendar; } /** * 判断是否是当天 * * @param calendar 用于判断的Calendar对象 * @return 判断结果 */ public static boolean isToday(Calendar calendar) { int year = Calendar.getInstance().get(Calendar.YEAR); int month = Calendar.getInstance().get(Calendar.MONTH); int date = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); return year == calendar.get(Calendar.YEAR) && month == calendar.get(Calendar.MONTH) && date == calendar.get(Calendar.DAY_OF_MONTH); } /** * 获取格式化的时间 * * @param calendar 进行格式化的Calendar对象 * @param needSecond 格式是否需要秒单位 * @return 格式化后时间 XX:XX:XX */ public static String getFromatTime(Calendar calendar, boolean needSecond) { int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); String min ; if(minute < 10){ min = "0"+minute; }else{ min = String.valueOf(minute); } int second = calendar.get(Calendar.SECOND); if (needSecond) { return hour + ":" + min + ":" + second; } else { return hour + ":" + min; } } /** * 获取格式化的日期 * * @param calendar 进行格式化的Calendar对象 * @param needYear 格式是否需要年单位 * @return 格式化后时间 XXXX-XX-XX */ public static String getFromatDate(Calendar calendar, boolean needYear) { int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int date = calendar.get(Calendar.DAY_OF_MONTH); if (needYear) { return year + "-" + month + "-" + date; } else { return month + "-" + date; } } /** * 比较两个Calendar对象之间时间差 * @param now 当前年 * @param last 之前年 * @return -1:显示年月时分 0:显示月时分 1:显示时分 2:不显示 * */ public static int compareCalendar10(Calendar now, Calendar last) { int year1 = now.get(Calendar.YEAR); int month1 = now.get(Calendar.MONTH) + 1; int date1 = now.get(Calendar.DAY_OF_MONTH); int hour1 = now.get(Calendar.HOUR_OF_DAY); int minute1 = now.get(Calendar.MINUTE); int year2 = last.get(Calendar.YEAR); int month2 = last.get(Calendar.MONTH) + 1; int date2 = last.get(Calendar.DAY_OF_MONTH); int hour2 = last.get(Calendar.HOUR_OF_DAY); int minute2 = last.get(Calendar.MINUTE); if (year1 > year2) { //小于当前年,一年前通话 return -1; } else { if (month1 > month2) { //小于当前月,一月前通话 return 0; } else { if (date1 > date2) { //小于当前日,一天前通话 return 0; } else { if (hour1 > hour2) { //一小时前 return 1; } else { if (minute1 - minute2 > 10) { //10分钟前 return 1; } else { return 2; } } } } } } }
package com.tencent.mm.plugin.voiceprint.ui; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import com.tencent.mm.R; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.model.at; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.plugin.appbrand.s$l; import com.tencent.mm.plugin.voiceprint.model.i; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.preference.CheckBoxPreference; import com.tencent.mm.ui.base.preference.MMPreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.f; public class SettingsVoicePrintUI extends MMPreference implements e { private ProgressDialog eHw = null; private f eOE; private boolean iSc = false; private View ilW; private VoiceHeaderPreference oFZ; public void onCreate(Bundle bundle) { super.onCreate(bundle); setMMTitle(R.l.settings_voiceprint); au.DF().a(615, this); this.ilW = findViewById(R.h.mm_preference_list_content); initView(); this.ilW.setBackgroundResource(R.e.white); au.HU(); c.DT().a(a.sPp, Boolean.valueOf(false)); au.HU(); c.DT().a(a.sPq, Boolean.valueOf(false)); au.HU(); c.DT().a(a.sPr, Boolean.valueOf(false)); au.HU(); c.DT().a(a.sPs, Boolean.valueOf(false)); x.i("MicroMsg.VoiceSettingsUI", "unset all voiceprint config"); } public void onResume() { super.onResume(); if (this.iSc) { this.iSc = false; if (this.eHw != null && this.eHw.isShowing()) { this.eHw.dismiss(); } ActionBarActivity actionBarActivity = this.mController.tml; getString(R.l.app_tip); this.eHw = h.a(actionBarActivity, getString(R.l.app_waiting), true, new 1(this)); x.d("MicroMsg.VoiceSettingsUI", "resume after create voiceprint, get switch status"); au.DF().a(new i(1), 0); } } public void onDestroy() { super.onDestroy(); au.DF().b(615, this); if (this.eHw != null) { this.eHw.dismiss(); } } public final void initView() { au.HU(); int p = bi.p(c.DT().get(40, Integer.valueOf(0)), 0); x.i("MicroMsg.VoiceSettingsUI", "plugSwitch " + p + " " + (p & 131072)); this.eOE = this.tCL; this.oFZ = (VoiceHeaderPreference) this.eOE.ZZ("settings_voiceprint_header"); ((CheckBoxPreference) this.eOE.ZZ("settings_voiceprint_title")).lM(true); this.eOE.notifyDataSetChanged(); if (this.eHw != null && this.eHw.isShowing()) { this.eHw.dismiss(); } ActionBarActivity actionBarActivity = this.mController.tml; getString(R.l.app_tip); this.eHw = h.a(actionBarActivity, getString(R.l.app_waiting), true, new 2(this)); au.DF().a(new i(0), 0); this.eOE.bw("settings_voiceprint_unlock", true); this.eOE.bw("settings_voiceprint_reset", true); this.eOE.bw("settings_voiceprint_create", true); setBackBtn(new 3(this)); } public final int Ys() { return R.o.settings_voice_print; } public final boolean a(f fVar, Preference preference) { String str = preference.mKey; Intent intent = new Intent(); if (str.equals("settings_voiceprint_title")) { CheckBoxPreference checkBoxPreference = (CheckBoxPreference) fVar.ZZ("settings_voiceprint_title"); x.d("MicroMsg.VoiceSettingsUI", "checkPref.isChecked() " + checkBoxPreference.isChecked()); if (this.eHw != null && this.eHw.isShowing()) { this.eHw.dismiss(); } ActionBarActivity actionBarActivity = this.mController.tml; getString(R.l.app_tip); this.eHw = h.a(actionBarActivity, getString(R.l.app_waiting), true, new 4(this)); if (checkBoxPreference.isChecked()) { au.DF().a(new i(1), 0); } else { au.DF().a(new i(2), 0); } return true; } else if (str.equals("settings_voiceprint_unlock")) { intent.setClass(this, VoiceUnLockUI.class); intent.putExtra("kscene_type", 73); startActivity(intent); return true; } else if (!str.equals("settings_voiceprint_reset")) { return false; } else { intent.setClass(this, VoiceCreateUI.class); intent.putExtra("KvoicePrintReset", true); intent.putExtra("kscene_type", 73); startActivityForResult(intent, 1); return true; } } public final void a(int i, int i2, String str, l lVar) { x.d("MicroMsg.VoiceSettingsUI", "onSceneEnd, errType:%d, errCode:%d, sceneType:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(lVar.getType())}); if (i == 0 || i2 == 0) { if (lVar.getType() == 615) { i iVar = (i) lVar; if (iVar.mStatus == 1) { int i3; x.d("MicroMsg.VoiceSettingsUI", "voiceprint exist"); this.eOE.bw("settings_voiceprint_unlock", false); this.eOE.notifyDataSetChanged(); int GL = q.GL(); CheckBoxPreference checkBoxPreference = (CheckBoxPreference) this.eOE.ZZ("settings_voiceprint_title"); x.d("MicroMsg.VoiceSettingsUI", "opScene.getSwitch:%d", new Object[]{Integer.valueOf(iVar.oFh)}); if (iVar.oFh > 0) { x.d("MicroMsg.VoiceSettingsUI", "voiceprint open"); checkBoxPreference.lM(true); this.eOE.bw("settings_voiceprint_reset", false); this.eOE.bw("settings_voiceprint_unlock", false); i3 = 131072 | GL; this.oFZ.cH(getString(R.l.voice_start_open), ""); } else { x.d("MicroMsg.VoiceSettingsUI", "voiceprint close"); checkBoxPreference.lM(false); this.eOE.bw("settings_voiceprint_reset", true); this.eOE.bw("settings_voiceprint_unlock", true); i3 = -131073 & GL; this.oFZ.cH(getString(R.l.voice_start_close), ""); } x.i("MicroMsg.VoiceSettingsUI", "scene end plugSwitch %d", new Object[]{Integer.valueOf(i3)}); at.dBv.T("last_login_use_voice", String.valueOf(i3)); au.HU(); c.DT().set(40, Integer.valueOf(i3)); this.eOE.bw("settings_voiceprint_create", true); this.eOE.bw("settings_voiceprint_title", false); this.oFZ.a(null); this.eOE.notifyDataSetChanged(); } else { x.d("MicroMsg.VoiceSettingsUI", "voiceprint not exist"); com.tencent.mm.plugin.report.service.h.mEJ.h(11390, new Object[]{Integer.valueOf(2)}); this.eOE.bw("settings_voiceprint_unlock", true); this.eOE.bw("settings_voiceprint_reset", true); this.eOE.bw("settings_voiceprint_create", true); this.eOE.bw("settings_voiceprint_title", true); this.oFZ.cH(getString(R.l.voice_start_title), getString(R.l.voice_start_tip)); this.oFZ.a(new 5(this)); this.eOE.notifyDataSetChanged(); } } if (this.eHw != null) { this.eHw.dismiss(); return; } return; } this.eOE.bw("settings_voiceprint_unlock", true); this.eOE.bw("settings_voiceprint_reset", true); this.eOE.bw("settings_voiceprint_create", true); ((CheckBoxPreference) this.eOE.ZZ("settings_voiceprint_title")).lM(false); this.oFZ.cH(getString(R.l.voice_start_close), ""); this.eOE.notifyDataSetChanged(); if (this.eHw != null) { this.eHw.dismiss(); } } private void bJh() { com.tencent.mm.plugin.report.service.h.mEJ.h(11390, new Object[]{Integer.valueOf(3)}); Intent intent = new Intent(); intent.setClass(this, VoiceCreateUI.class); intent.putExtra("kscene_type", 71); intent.putExtra("createVoicePrint", true); startActivityForResult(intent, 1); this.iSc = false; } protected void onActivityResult(int i, int i2, Intent intent) { super.onActivityResult(i, i2, intent); if (i == 1 && intent != null) { this.iSc = intent.getBooleanExtra("KIsCreateSuccess", false); } } public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { x.i("MicroMsg.VoiceSettingsUI", "summerper onRequestPermissionsResult requestCode[%d],grantResults[%d] tid[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(iArr[0]), Long.valueOf(Thread.currentThread().getId())}); switch (i) { case s$l.AppCompatTheme_panelMenuListTheme /*80*/: if (iArr[0] == 0) { bJh(); return; } else { h.a(this, getString(R.l.permission_microphone_request_again_msg), getString(R.l.permission_tips_title), getString(R.l.jump_to_settings), getString(R.l.cancel), false, new 6(this), new 7(this)); return; } default: return; } } }
public class HelloWorldExternalD { public void HelloWorldD() { System.out.println("HelloWorldD"); } }
package com.vilio.fms.util; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.persistence.criteria.CriteriaBuilder; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.zip.ZipInputStream; /** * Created by dell on 2017/6/5. */ public class ZipUtil { private static final String zipTempFile = "./zipTempFile/"; public static void writeZip(String[] strs,String zipname) throws IOException { String[] files = strs; OutputStream os = new BufferedOutputStream( new FileOutputStream( "./tempFile/" + zipname +".zip" ) ); ZipOutputStream zos = new ZipOutputStream( os ); byte[] buf = new byte[8192]; int len; for (int i=0;i<files.length;i++) { File file = new File( files[i] ); if ( !file.isFile() ) continue; ZipEntry ze = new ZipEntry( file.getName() ); zos.putNextEntry( ze ); BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) ); while ( ( len = bis.read( buf ) ) > 0 ) { zos.write( buf, 0, len ); } zos.closeEntry(); } zos.setEncoding("gbk"); zos.closeEntry(); zos.close(); for(int i=0;i<files.length;i++){ File file= new File(files[i] ); file.delete(); } } /** * * @param files * @param zipname * @return * @throws IOException */ public static InputStream writeZip(MultipartFile[] files, String zipname) throws IOException { File outFile = new File(zipTempFile + zipname + ".zip" ); File parentFile = outFile.getParentFile(); boolean flag = false; //如果输出目标文件夹不存在,则创建 if (!parentFile.exists()){ flag = parentFile.mkdirs(); } if(!outFile.exists()){ flag = outFile.createNewFile(); } OutputStream os = new BufferedOutputStream( new FileOutputStream( zipTempFile + zipname +".zip" ) ); ZipOutputStream zos = new ZipOutputStream( os ); byte[] buf = new byte[8192]; int len; for (int i=0;i<files.length;i++) { ZipEntry ze = new ZipEntry( ((CommonsMultipartFile)files[i]).getFileItem().getName() ); zos.putNextEntry( ze ); BufferedInputStream bis = new BufferedInputStream(files[i].getInputStream()); while ( ( len = bis.read( buf ) ) > 0 ) { zos.write( buf, 0, len ); } zos.closeEntry(); } zos.setEncoding("gbk"); zos.closeEntry(); zos.close(); os.close(); InputStream returnInputStream = new FileInputStream(zipTempFile + zipname +".zip" ); return returnInputStream; } /** * 删出生成的本地压缩文件 * @param zipname 压缩文件的文件名(不含后缀) * @return 删除是否成功 * @throws IOException */ public static boolean deleteZipFile(String zipname, InputStream in) throws IOException { if(null != in){ in.close(); } boolean deleteSuccess = false; //删除本地文件 File localFile = new File(zipTempFile + zipname +".zip" ); if(localFile.exists() && localFile.isFile()){ deleteSuccess = localFile.delete(); } return deleteSuccess; } public static InputStream writeZip(List<Map<String, InputStream>> streamList, String zipname) throws IOException { zipname = zipTempFile + zipname + ".zip"; byte[]buffer=new byte[1024]; ZipOutputStream out=null; try{ out = new ZipOutputStream(new FileOutputStream(zipname)); for(int i = 0,len = streamList.size(); i < len; i++) { Map<String, InputStream> inputStreamMap = streamList.get(i); Iterator it = inputStreamMap.keySet().iterator(); while(it.hasNext()){ String name = (String) it.next(); out.putNextEntry(new ZipEntry(name)); InputStream in = inputStreamMap.get(name); int dataLen; //读入需要下载的文件的内容,打包到zip文件 while((dataLen = in.read(buffer)) > 0){ out.write(buffer,0,dataLen); } out.closeEntry(); in.close(); } } out.close(); } catch(Exception ex) { ex.printStackTrace(); } //读取压缩包 File filezip = new File(zipname); InputStream returnIn = new FileInputStream(filezip); return returnIn; } public static void main(String[] args) { String[] strs = {"D:\\ss/JavaScript语言精粹.pdf","D:\\ss/seo实战密码.pdf","D:\\ss/蚂蚁金服.pdf"}; try { ZipUtil.writeZip(strs,"test"); } catch (IOException e) { e.printStackTrace(); } } }
package com.xampy.namboo.api.database; import android.database.sqlite.SQLiteDatabase; public abstract class DAOBase { protected DataBaseHandler dbHandler = null; protected SQLiteDatabase redableDataBase = null; protected SQLiteDatabase writableDataBase = null; public DAOBase(DataBaseHandler dbHandler){ this.dbHandler= dbHandler; this.redableDataBase = this.dbHandler.getReadableDatabase(); this.writableDataBase = this.dbHandler.getWritableDatabase(); } }
package com.tencent.mm.plugin.gallery.model; import android.os.Bundle; import com.tencent.mm.R; import com.tencent.mm.modelsfs.FileOp; import com.tencent.mm.platformtools.r; import com.tencent.mm.plugin.gallery.stub.a; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; public final class c { private static int bkq = 0; public static boolean jAA = false; public static boolean jAB = false; public static boolean jAC = false; private static c jAy = null; public static boolean jAz = false; private HashSet<GalleryItem$MediaItem> jAD = new HashSet(); private ArrayList<Bundle> jAE = new ArrayList(); private HashMap<Integer, Boolean> jAF = new HashMap(); private l jAt; private a jAu; private e jAv; private ArrayList<GalleryItem$MediaItem> jAw = null; private LinkedHashSet<GalleryItem$MediaItem> jAx = new LinkedHashSet(); public static GalleryItem$MediaItem CS(String str) { GalleryItem$MediaItem a = GalleryItem$MediaItem.a(0, 0, str, "", ""); if (aRd().jAw != null) { int indexOf = aRd().jAw.indexOf(a); if (indexOf >= 0) { return (GalleryItem$MediaItem) aRd().jAw.get(indexOf); } } return null; } private c() { if (this.jAu == null) { this.jAu = new a(); } if (this.jAt == null) { this.jAt = new l(); } if (this.jAv == null) { this.jAv = new e(); } } private static c aRd() { if (jAy == null) { jAy = new c(); } return jAy; } public static a aRe() { return aRd().jAu; } public static l aRf() { return aRd().jAt; } public static e aRg() { return aRd().jAv; } public static void initialize() { synchronized (c.class) { bkq++; } } public static void release(boolean z) { synchronized (c.class) { if (bkq > 0) { bkq--; } if (z && bkq == 0) { aRd().jAt = null; if (aRd().jAu != null) { b bVar = aRd().jAu.jAe; if (bVar.jAp != null) { bVar.jAp.a(new b$4(bVar)); bVar.jAp = null; } if (bVar.jAq != null) { d dVar = bVar.jAq; dVar.aRo(); dVar.aRp(); dVar.aRr(); bVar.jAq = null; } aRd().jAu = null; } e eVar = aRd().jAv; if (eVar.jAK != null) { eVar.jAK.quit(); eVar.jAK = null; } eVar.jAN = null; if (eVar.jAL != null) { eVar.jAL.quit(); eVar.jAL = null; } eVar.jAO = null; if (eVar.jAM != null) { eVar.jAM.quit(); eVar.jAM = null; } eVar.jAP = null; aRd().jAv = null; jAy = null; } } } public static ArrayList<GalleryItem$MediaItem> aRh() { return aRd().jAw; } public static HashSet<GalleryItem$MediaItem> aRi() { return aRd().jAD; } public static ArrayList<Bundle> aRj() { return aRd().jAE; } public static LinkedHashSet<GalleryItem$MediaItem> aRk() { return aRd().jAx; } public static void v(ArrayList<GalleryItem$MediaItem> arrayList) { aRd().jAw = arrayList; } public static void qn(int i) { aRd().jAF.put(Integer.valueOf(i), Boolean.valueOf(true)); } public static void aRl() { aRd().jAF.clear(); } public static int aRm() { return aRd().jAF.size(); } public static void a(a aVar, int i, boolean z, boolean z2) { x.i("MicroMsg.GalleryCore", "[handlePhotoEditInfo] selectSize:%s isSendRaw:%s", new Object[]{Integer.valueOf(i), Boolean.valueOf(z)}); if (aVar == null) { x.e("MicroMsg.GalleryCore", "invoker is null"); return; } int i2; int size; if (aRd().jAt.aRI() == 3) { i2 = 1; } else if (aRd().jAt.aRI() == 4) { i2 = 2; } else { i2 = 0; } if (aRd().jAD != null) { size = aRd().jAD.size(); } else { size = 0; } x.i("MicroMsg.GalleryCore", "[reportPhotoEdit] fromScene:%s,selectSize:%s,editSize:%s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i), Integer.valueOf(size)}); if (size > 0) { aVar.al(13858, i2 + "," + i + "," + size + ",0"); } x.i("MicroMsg.GalleryCore", "[handlePhotoEditInfo] imageState:%s", new Object[]{Boolean.valueOf(aVar.fi(true))}); Iterator it = aRd().jAE.iterator(); while (it.hasNext()) { Bundle bundle = (Bundle) it.next(); String string = bundle.getString("after_photo_edit"); if (!(r4 && z2)) { x.i("MicroMsg.GalleryCore", "[handlePhotoEditInfo] delete file:%s", new Object[]{string}); FileOp.deleteFile(string); r.a(string, ad.getContext()); } int i3 = bundle.getInt("report_info_emotion_count"); int i4 = bundle.getInt("report_info_text_count"); int i5 = bundle.getInt("report_info_mosaic_count"); int i6 = bundle.getInt("report_info_doodle_count"); boolean z3 = bundle.getBoolean("report_info_iscrop"); int i7 = bundle.getInt("report_info_undo_count"); boolean z4 = bundle.getBoolean("report_info_is_rotation"); String str = "MicroMsg.GalleryCore"; String str2 = "[reportPhotoEdit] emojiCount:%s,textCount:%s,mosaicCount:%s,penCount:%s,isCrop:%s,undoCount:%s,isRotation:%s"; Object[] objArr = new Object[7]; objArr[0] = Integer.valueOf(i3); objArr[1] = Integer.valueOf(i4); objArr[2] = Integer.valueOf(i5); objArr[3] = Integer.valueOf(i6); objArr[4] = Integer.valueOf(z3 ? 1 : 0); objArr[5] = Integer.valueOf(i7); objArr[6] = Integer.valueOf(z4 ? 1 : 0); x.i(str, str2, objArr); if (size > 0) { try { aVar.al(13857, i2 + "," + z + "," + i3 + "," + i4 + "," + i5 + "," + i6 + "," + (z3 ? 1 : 0) + "," + i7 + ",2" + (z4 ? 1 : 0)); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.GalleryCore", e, "", new Object[0]); } } } } public static void a(a aVar, String str, int[] iArr, boolean z, boolean z2) { int i = 2; switch (aRd().jAt.aRI()) { case 3: i = 1; break; case 4: if (!bi.oW(str) && str.equals(ad.getContext().getString(R.l.favorite))) { i = 6; break; } case 7: case 8: i = 3; break; default: i = 0; break; } x.i("MicroMsg.GalleryCore", "[handleSelectImagePreviewReport] source:%s", new Object[]{Integer.valueOf(r4)}); if (aVar == null) { x.e("MicroMsg.GalleryCore", "invoker is null"); return; } try { aVar.al(14205, i + "," + i + "," + iArr[0] + "," + iArr[1] + "," + iArr[2] + "," + iArr[3] + "," + z + "," + z2 + "," + jAz + "," + jAA + "," + jAB + "," + jAC); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.GalleryCore", e, "", new Object[0]); } jAz = false; jAA = false; jAB = false; jAC = false; } }
package Chapter6Review; public class Bank { private double principal; private double interest; private int year; public Bank(double principal, double interest) { this.principal = principal; this.interest = interest; } public void calculateFV(double targetPayout) { interest = interest / 100; for (year = 0; principal < targetPayout; year++) { principal = (principal * interest) + principal; System.out.printf("%.2f %9d%n", principal, year); //%n instead of \n for a new line } } public double getFV() { return principal; } public int getYears() { return year; } }
/* * Copyright (c) 2008-2011 by Jan Stender, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.mrc.database.babudb; import java.nio.ByteBuffer; import java.util.List; import java.util.Map.Entry; import org.xtreemfs.babudb.api.database.Database; import org.xtreemfs.babudb.api.database.DatabaseRO; import org.xtreemfs.babudb.api.database.ResultSet; import org.xtreemfs.babudb.api.exception.BabuDBException; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.mrc.database.DatabaseResultSet; import org.xtreemfs.mrc.metadata.ACLEntry; import org.xtreemfs.mrc.metadata.BufferBackedACLEntry; import org.xtreemfs.mrc.metadata.BufferBackedFileMetadata; import org.xtreemfs.mrc.metadata.BufferBackedRCMetadata; import org.xtreemfs.mrc.metadata.BufferBackedXAttr; import org.xtreemfs.mrc.metadata.FileMetadata; import org.xtreemfs.mrc.metadata.XAttr; public class BabuDBStorageHelper { static class ChildrenIterator implements DatabaseResultSet<FileMetadata> { private final DatabaseRO database; private final ResultSet<byte[], byte[]> it; private Entry<byte[], byte[]> next; private String prevFileName; private byte[][] keyBufs; private byte[][] valBufs; private int remaining; public ChildrenIterator(DatabaseRO database, ResultSet<byte[], byte[]> it, int from, int num) { this.database = database; this.it = it; this.keyBufs = new byte[BufferBackedFileMetadata.NUM_BUFFERS][]; this.valBufs = new byte[BufferBackedFileMetadata.NUM_BUFFERS][]; remaining = Integer.MAX_VALUE; // move to the 'from' element for (int i = 0; i < from && hasNext(); i++) next(); remaining = num; } @Override public boolean hasNext() { return (next != null || it.hasNext()) && remaining > 0; } @Override public FileMetadata next() { while (next != null || it.hasNext()) { if (next == null) next = it.next(); final String currFileName = new String(next.getKey(), 8, next.getKey().length - 9); if (prevFileName != null && !prevFileName.equals(currFileName)) { assert (valBufs[FileMetadata.RC_METADATA] != null) : "*** DATABASE CORRUPTED *** incomplete file metadata"; break; } final byte currType = next.getKey()[next.getKey().length - 1]; keyBufs[currType] = next.getKey(); valBufs[currType] = next.getValue(); next = null; prevFileName = currFileName; } byte[][] tmpKeys = keyBufs; byte[][] tmpVals = valBufs; keyBufs = new byte[BufferBackedFileMetadata.NUM_BUFFERS][]; valBufs = new byte[BufferBackedFileMetadata.NUM_BUFFERS][]; // if (tmpVals[FileMetadata.RC_METADATA] == null) { // //dump the record // for (int i = 0; i < tmpVals.length; i++) { // System.out.println("index "+i); // if (tmpVals[i] == null) { // System.out.println("IS NULL!"); // continue; // } // String content = new String(tmpVals[i]); // System.out.println("content: "+content); // } // System.exit(1); // } BufferBackedFileMetadata md = null; // in case of a hardlink ... if (tmpVals[FileMetadata.RC_METADATA][0] == 2) try { md = BabuDBStorageHelper.resolveLink(database, tmpVals[FileMetadata.RC_METADATA], prevFileName); } catch (BabuDBException exc) { Logging.logMessage(Logging.LEVEL_ERROR, Category.storage, this, "could not resolve hard link"); } else md = new BufferBackedFileMetadata(tmpKeys, tmpVals, BabuDBStorageManager.FILE_INDEX); remaining--; prevFileName = null; return md; } @Override public void remove() { throw new UnsupportedOperationException(); } public void destroy() { it.free(); } } static class XAttrIterator implements DatabaseResultSet<XAttr> { private ResultSet<byte[], byte[]> it; private String owner; private BufferBackedXAttr next; public XAttrIterator(ResultSet<byte[], byte[]> it, String owner) { this.it = it; this.owner = owner; } @Override public boolean hasNext() { if (owner == null) return it.hasNext(); if (next != null) return true; if (!it.hasNext()) return false; while (it.hasNext()) { Entry<byte[], byte[]> tmp = it.next(); next = new BufferBackedXAttr(tmp.getKey(), tmp.getValue()); if (!owner.equals(next.getOwner())) continue; return true; } return false; } @Override public XAttr next() { if (next != null) { XAttr tmp = next; next = null; return tmp; } for (;;) { Entry<byte[], byte[]> tmp = it.next(); next = new BufferBackedXAttr(tmp.getKey(), tmp.getValue()); if (owner != null && !owner.equals(next.getOwner())) continue; BufferBackedXAttr tmp2 = next; next = null; return tmp2; } } @Override public void remove() { throw new UnsupportedOperationException(); } public void destroy() { it.free(); } } static class ACLIterator implements DatabaseResultSet<ACLEntry> { private ResultSet<byte[], byte[]> it; public ACLIterator(ResultSet<byte[], byte[]> it) { this.it = it; } @Override public boolean hasNext() { return it.hasNext(); } @Override public ACLEntry next() { Entry<byte[], byte[]> entry = it.next(); return new BufferBackedACLEntry(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } public void destroy() { it.free(); } } public static byte[] getLastAssignedFileId(Database database) throws BabuDBException { byte[] bytes = database.lookup(BabuDBStorageManager.VOLUME_INDEX, BabuDBStorageManager.LAST_ID_KEY, null).get(); if (bytes == null) { bytes = new byte[8]; ByteBuffer tmp = ByteBuffer.wrap(bytes); tmp.putLong(0); } return bytes; } public static byte[] getVolumeMetadata(DatabaseRO database, byte[] key) throws BabuDBException { byte[] bytes = database.lookup(BabuDBStorageManager.VOLUME_INDEX, key, null).get(); if (bytes == null) { bytes = new byte[8]; ByteBuffer tmp = ByteBuffer.wrap(bytes); tmp.putLong(0); } return bytes; } /** * Returns the collision number assigned to an extended attribute, -1 if the * attribute does not exist. * * @param database * @param fileId * @param owner * @param attrKey * @return the collision number * @throws BabuDBException */ public static short findXAttrCollisionNumber(Database database, long fileId, String owner, String attrKey) throws BabuDBException { // first, determine the collision number byte[] prefix = createXAttrPrefixKey(fileId, owner, attrKey); ResultSet<byte[], byte[]> it = database.prefixLookup(BabuDBStorageManager.XATTRS_INDEX, prefix, null) .get(); Entry<byte[], byte[]> next = null; while (it.hasNext()) { Entry<byte[], byte[]> curr = it.next(); BufferBackedXAttr attr = new BufferBackedXAttr(curr.getKey(), curr.getValue()); if (owner.equals(attr.getOwner()) && attrKey.equals(attr.getKey())) { next = curr; break; } } it.free(); if (next == null) return -1; return getXAttrCollisionNumber(next.getKey()); } /** * Returns the collision number assigned to an extended attribute, or the * next largest unused number if the attribute does not exist. * * @param database * @param fileId * @param owner * @param attrKey * @return the collision number * @throws BabuDBException */ public static short findUsedOrNextFreeXAttrCollisionNumber(Database database, long fileId, String owner, String attrKey) throws BabuDBException { // first, determine the collision number byte[] prefix = createXAttrPrefixKey(fileId, owner, attrKey); ResultSet<byte[], byte[]> it = database.prefixLookup(BabuDBStorageManager.XATTRS_INDEX, prefix, null) .get(); Entry<byte[], byte[]> next = null; Entry<byte[], byte[]> curr = null; while (it.hasNext()) { curr = it.next(); BufferBackedXAttr attr = new BufferBackedXAttr(curr.getKey(), curr.getValue()); if (owner.equals(attr.getOwner()) && attrKey.equals(attr.getKey())) { next = curr; break; } } it.free(); if (next == null) return curr == null ? 0 : (short) (getXAttrCollisionNumber(curr.getKey()) + 1); return getXAttrCollisionNumber(next.getKey()); } public static byte[] createFileKey(long parentId, String fileName, byte type) { byte[] bytes = fileName.getBytes(); byte[] prefix = new byte[(type >= 0 ? 9 : 8) + bytes.length]; ByteBuffer buf = ByteBuffer.wrap(prefix); buf.putLong(parentId).put(bytes); if (type >= 0) buf.put(type); return prefix; } public static byte[] createXAttrPrefixKey(long fileId, String owner, String attrKey) { byte[] prefix = new byte[owner == null ? 8 : attrKey == null ? 12 : 16]; ByteBuffer buf = ByteBuffer.wrap(prefix); buf.putLong(fileId); if (owner != null) buf.putInt(owner.hashCode()); if (attrKey != null) buf.putInt(attrKey.hashCode()); return prefix; } public static byte[] createFilePrefixKey(long parentId) { byte[] prefix = new byte[8]; ByteBuffer buf = ByteBuffer.wrap(prefix); buf.putLong(parentId); return prefix; } public static byte[] createACLPrefixKey(long fileId, String entityName) { byte[] entityBytes = entityName == null ? new byte[0] : entityName.getBytes(); byte[] prefix = new byte[8 + entityBytes.length]; ByteBuffer buf = ByteBuffer.wrap(prefix); buf.putLong(fileId).put(entityBytes); return prefix; } public static byte[] createFileIdIndexValue(long parentId, String fileName) { byte[] nameBytes = fileName.getBytes(); byte[] buf = new byte[8 + nameBytes.length]; ByteBuffer tmp = ByteBuffer.wrap(buf); tmp.putLong(parentId).put(nameBytes); return buf; } public static byte[] createFileIdIndexKey(long fileId, byte type) { byte[] buf = new byte[type == -1 ? 8 : 9]; ByteBuffer tmp = ByteBuffer.wrap(buf); tmp.putLong(fileId); if (type != -1) tmp.put(type); return buf; } public static byte[] createLinkTarget(long fileId) { byte[] buf = new byte[9]; ByteBuffer tmp = ByteBuffer.wrap(buf); tmp.put((byte) 2).putLong(fileId); return buf; } public static short getXAttrCollisionNumber(byte[] key) { short collNum = 0; ByteBuffer tmp = ByteBuffer.wrap(key); if (key.length == 16) collNum = 0; else collNum = tmp.getShort(16); return collNum; } public static BufferBackedFileMetadata getMetadata(DatabaseRO database, long parentId, String fileName) throws BabuDBException { byte[] rcKey = BabuDBStorageHelper.createFileKey(parentId, fileName, FileMetadata.RC_METADATA); byte[] rcValue = database.lookup(BabuDBStorageManager.FILE_INDEX, rcKey, null).get(); if (rcValue != null) { // if the value refers to a link, resolve the link if (rcValue[0] == 2) return resolveLink(database, rcValue, fileName); byte[] fcKey = BabuDBStorageHelper.createFileKey(parentId, fileName, FileMetadata.FC_METADATA); byte[] fcValue = database.lookup(BabuDBStorageManager.FILE_INDEX, fcKey, null).get(); byte[][] keyBufs = new byte[][] { fcKey, rcKey }; byte[][] valBufs = new byte[][] { fcValue, rcValue }; return new BufferBackedFileMetadata(keyBufs, valBufs, BabuDBStorageManager.FILE_INDEX); } else return null; } public static long getId(Database database, long parentId, String fileName, Boolean directory) throws BabuDBException { byte[] key = createFileKey(parentId, fileName, BufferBackedFileMetadata.RC_METADATA); byte[] value = database.lookup(BabuDBStorageManager.FILE_INDEX, key, null).get(); if (value == null) return -1; return ByteBuffer.wrap(value).getLong(1); } public static byte getType(byte[] key, int index) { return key[index == BabuDBStorageManager.FILE_ID_INDEX ? 8 : 12]; } public static BufferBackedFileMetadata resolveLink(DatabaseRO database, byte[] target, String fileName) throws BabuDBException { ResultSet<byte[], byte[]> it = null; try { // determine the key for the link index byte[] fileIdBytes = new byte[8]; System.arraycopy(target, 1, fileIdBytes, 0, fileIdBytes.length); byte[][] valBufs = new byte[BufferBackedFileMetadata.NUM_BUFFERS][]; // retrieve the metadata from the link index it = database.prefixLookup(BabuDBStorageManager.FILE_ID_INDEX, fileIdBytes, null).get(); while (it.hasNext()) { Entry<byte[], byte[]> curr = it.next(); int type = getType(curr.getKey(), BabuDBStorageManager.FILE_ID_INDEX); if (type == 3) { long fileId = ByteBuffer.wrap(fileIdBytes).getLong(); Logging.logMessage(Logging.LEVEL_WARN, Category.storage, (Object) null, "MRC database contains redundant data for file %d", fileId); continue; } valBufs[type] = curr.getValue(); } assert (valBufs[FileMetadata.RC_METADATA] != null) : "*** DATABASE CORRUPTED *** dangling hardlink"; if (valBufs[FileMetadata.RC_METADATA] == null) return null; // replace the file name with the link name BufferBackedRCMetadata tmp = new BufferBackedRCMetadata(null, valBufs[FileMetadata.RC_METADATA]); BufferBackedRCMetadata tmp2 = tmp.isDirectory() ? new BufferBackedRCMetadata(0, fileName, tmp .getOwnerId(), tmp.getOwningGroupId(), tmp.getId(), tmp.getPerms(), tmp.getW32Attrs(), tmp .getLinkCount()) : new BufferBackedRCMetadata(0, fileName, tmp.getOwnerId(), tmp .getOwningGroupId(), tmp.getId(), tmp.getPerms(), tmp.getW32Attrs(), tmp.getLinkCount(), tmp .getEpoch(), tmp.getIssuedEpoch(), tmp.isReadOnly()); if (!tmp2.isDirectory()) tmp2.setXLocList(tmp.getXLocList()); valBufs[FileMetadata.RC_METADATA] = tmp2.getValue(); byte[][] keyBufs = new byte[][] { null, tmp2.getKey() }; return new BufferBackedFileMetadata(keyBufs, valBufs, BabuDBStorageManager.FILE_ID_INDEX); } finally { if (it != null) it.free(); } } public static ChildrenIterator getChildren(DatabaseRO database, long parentId, int from, int num) throws BabuDBException { byte[] prefix = BabuDBStorageHelper.createFilePrefixKey(parentId); ResultSet<byte[], byte[]> it = database.prefixLookup(BabuDBStorageManager.FILE_INDEX, prefix, null) .get(); return new ChildrenIterator(database, it, from, num); } public static void getNestedFiles(List<FileMetadata> files, Database database, long dirId, boolean recursive) throws BabuDBException { ChildrenIterator children = getChildren(database, dirId, 0, Integer.MAX_VALUE); while (children.hasNext()) { FileMetadata metadata = children.next(); files.add(metadata); if (recursive && metadata.isDirectory()) getNestedFiles(files, database, metadata.getId(), recursive); } children.destroy(); } public static long getRootParentId(DatabaseRO database) throws BabuDBException { ResultSet<byte[], byte[]> it = database.prefixLookup(BabuDBStorageManager.FILE_INDEX, null, null) .get(); if (!it.hasNext()) return -1; byte[] key = it.next().getKey(); it.free(); return ByteBuffer.wrap(key).getLong(); } public static String getRootDirName(DatabaseRO database, long rootParentId) throws BabuDBException { byte[] rootParentIdBytes = ByteBuffer.wrap(new byte[8]).putLong(rootParentId).array(); ResultSet<byte[], byte[]> it = database.prefixLookup(BabuDBStorageManager.FILE_INDEX, rootParentIdBytes, null).get(); if (!it.hasNext()) return null; byte[] key = it.next().getKey(); it.free(); return new String(key, 8, key.length - 9); } }
package Pages; import static org.testng.Assert.assertEquals; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import com.google.j2objc.annotations.Property; import Setup.TestBase; import Utilty.Util; public class KOCH_Page extends TestBase{ @FindBy(xpath = "//img[contains(@id,'ixiLogoImg')]") WebElement Ixigo_Logo; @FindBy(xpath = "//span[contains(text(),'Round Trip')]") WebElement Round_Trip; @FindBy(xpath = "//div[contains(@class,'clear-input ixi-icon-cross')]") WebElement Frm_City_Cross_Btn; @FindBy(xpath="//div[contains(@class,'form-fields')]//div[contains(text(),'From')]/following-sibling::input[contains(@placeholder,'Enter city')]") WebElement From_City; @FindBy(xpath="//div[contains(@class,'form-fields')]//div[contains(text(),'To')]/following-sibling::input[contains(@placeholder,'Enter city')]") WebElement To_City; @FindBy(xpath="//div[contains(text(),'PNQ - Pune, India')]") WebElement From_City_Option; @FindBy(xpath="//div[contains(text(),'HYD - Hyderabad, India')]") WebElement To_City_Option; @FindBy(xpath="//td[contains(@class,'//div[contains(text(),'Departure')]/following-sibling::input')]") WebElement Departure; @FindBy(xpath="//td[contains(@class,'//div[contains(text(),'Return')]/following-sibling::input')]") WebElement Return; //@FindBy(xpath="//td[contains(@class,'selected')]") @FindBy(xpath="//div[contains(@class,'dep')]//td[contains(@data-date,'22112020')]") WebElement From_Date; @FindBy(xpath="//div[contains(@class,'ret')]//td[contains(@data-date,'30122020')]") WebElement To_Date; @FindBy(xpath="//div[contains(text(),'Travellers | Class')]/following-sibling::input") WebElement Passenger_Link; @FindBy(xpath="//div[contains(text(),'Adult')]//../..//span[contains(text(),'2')]") WebElement Passenger_Count; @FindBy(xpath="//button[contains(text(),'Search')]") WebElement Search_Button; @FindBy(xpath="//div[contains(text(),'Stop')]") WebElement Stop_Text; @FindBy(xpath="//div[contains(@class,'stops')]//div[@data-checkboxindex='0']") WebElement Non_Stop_Checkbox; @FindBy(xpath="//div[@class='stop-info' and text()='Non stop']") WebElement Non_Stop_Text; @FindBy(xpath="//div[contains(@class,'stops')]//div[@data-checkboxindex='1']") WebElement One_Stop_Checkbox; @FindBy(xpath="//div[@class='stop-info' and text()='1 stop']") WebElement One_Stop_Text; @FindBy(xpath="//div[contains(@class,'stops')]//div[@data-checkboxindex='2']") WebElement OnePlus_Stop_Checkbox; @FindBy(xpath="//div[@class='stop-info' and text()='1+ stops']") WebElement OnePlus_Stop_Text; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]") WebElement Departure1_Text; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//button[text()='00:00 - 06:00']") WebElement Departure1_00_00_06_00; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//div[text()='Early Morning']") WebElement Departure1_Early_Morning; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//button[text()='06:00 - 12:00']") WebElement Departure1_00_06_12_00; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//div[text()='Morning']") WebElement Departure1_Morning; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//button[text()='12:00 - 18:00']") WebElement Departure1_12_00_18_00; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//div[text()='Mid Day']") WebElement Departure1_Mid_Day; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//button[text()='18:00 - 24:00']") WebElement Departure1_18_00_24_00; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//div[text()='Night']") WebElement Departure1_Night; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]") WebElement Departure2_Text; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//button[text()='00:00 - 06:00']") WebElement Departure2_00_00_06_00; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//div[text()='Early Morning']") WebElement Departure2_Early_Morning; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//button[text()='06:00 - 12:00']") WebElement Departure2_00_06_12_00; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//div[text()='Morning']") WebElement Departure2_Morning; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//button[text()='12:00 - 18:00']") WebElement Departure2_12_00_18_00; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//div[text()='Mid Day']") WebElement Departure2_Mid_Day; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//button[text()='18:00 - 24:00']") WebElement Departure2_18_00_24_00; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//div[text()='Night']") WebElement Departure2_Night; @FindBy(xpath="//div[contains(text(),'Departure from PNQ')]/parent::div//div[@class='time-sldr']") WebElement Departure1_Time_Slider; @FindBy(xpath="//div[contains(text(),'Departure from HYD')]/parent::div//div[@class='time-sldr']") WebElement Departure2_Time_Slider; @FindBy(xpath="//div[contains(text(),'Prices')]/parent::div//div[@class='slider-cntr lower']") WebElement Price_Slider; @FindBy(xpath="//div[contains(text(),'Airlines')]") WebElement Airlines_Text; @FindBy(xpath="//div[@title='Air India']") WebElement Air_india_Text; @FindBy(xpath="//div[contains(@class,'arln')]//div[@data-checkboxindex='0']") WebElement Air_india_Checkbox; @FindBy(xpath="//div[@title='AirAsia India']") WebElement AirAsia_india_Text; @FindBy(xpath="//div[contains(@class,'arln')]//div[@data-checkboxindex='1']") WebElement AirAsia_India_Checkbox; @FindBy(xpath="//div[@title='IndiGo']") WebElement IndiGo_Text; @FindBy(xpath="//div[contains(@class,'arln')]//div[@data-checkboxindex='2']") WebElement IndiGo_Checkbox; @FindBy(xpath="//div[@title='SpiceJet']") WebElement SpiceJet_Text; @FindBy(xpath="//div[contains(@class,'arln')]//div[@data-checkboxindex='3']") WebElement SpiceJet_Checkbox; @FindBy(xpath="//div[@title='Vistara']") WebElement Vistara_Text; @FindBy(xpath="//div[contains(@class,'arln')]//div[@data-checkboxindex='4']") WebElement Vistara_Checkbox; @FindBy(xpath="//button[text()='APPLY']") WebElement Apply_Button; @FindBy(xpath="//div[text()='LESS FILTERS']") WebElement Less_Filters_Button; @FindBy(xpath="//div[text()='MORE FILTERS']") WebElement More_Filters_Button; @FindBy(xpath="//div[text()='MORE FILTERS']") WebElement First_Trip_Flight_Results; @FindBy(xpath="//div[text()='MORE FILTERS']") WebElement Return_Trip_Flight_Results; public KOCH_Page() { PageFactory.initElements(driver, this); } public void search_Flight_With_Data() { Util.waitForPageLoader(); wait.until(ExpectedConditions.visibilityOf(Ixigo_Logo)); String title = driver.getCurrentUrl(); assertEquals(title, prop.getProperty("url")); Round_Trip.click(); Frm_City_Cross_Btn.click(); From_City.sendKeys("Pune"); From_City_Option.click(); To_City.sendKeys("Hyderabad"); To_City_Option.click(); From_Date.click(); To_Date.click(); Passenger_Count.click(); Search_Button.click(); Util.waitForPageLoader(); String title_Serach_Page = driver.getCurrentUrl(); title_Serach_Page.contains(prop.getProperty("serach_page_url")); wait.until(ExpectedConditions.visibilityOf(First_Trip_Flight_Results)); wait.until(ExpectedConditions.visibilityOf(Return_Trip_Flight_Results)); More_Filters_Button.click(); wait.until(ExpectedConditions.visibilityOf(Stop_Text)); wait.until(ExpectedConditions.visibilityOf(Non_Stop_Text)); Non_Stop_Checkbox.click(); wait.until(ExpectedConditions.visibilityOf(One_Stop_Text)); One_Stop_Checkbox.click(); wait.until(ExpectedConditions.visibilityOf(OnePlus_Stop_Text)); //OnePlus_Stop_Checkbox.click(); wait.until(ExpectedConditions.visibilityOf(Departure1_Text)); //Departure1_00_00_06_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure1_Early_Morning)); //Departure1_00_06_12_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure1_Morning)); Departure1_12_00_18_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure1_Mid_Day)); Departure1_18_00_24_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure1_Night)); wait.until(ExpectedConditions.visibilityOf(Departure2_Text)); Departure2_00_00_06_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure2_Early_Morning)); //Departure2_00_06_12_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure2_Morning)); Departure2_12_00_18_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure2_Mid_Day)); Departure2_18_00_24_00.click(); wait.until(ExpectedConditions.visibilityOf(Departure2_Night)); wait.until(ExpectedConditions.visibilityOf(Departure1_Time_Slider)); wait.until(ExpectedConditions.visibilityOf(Departure2_Time_Slider)); wait.until(ExpectedConditions.visibilityOf(Price_Slider)); wait.until(ExpectedConditions.visibilityOf(Airlines_Text)); Air_india_Checkbox.click(); //wait.until(ExpectedConditions.visibilityOf(Air_india_Text)); AirAsia_India_Checkbox.click(); //wait.until(ExpectedConditions.visibilityOf(AirAsia_india_Text)); IndiGo_Checkbox.click(); //wait.until(ExpectedConditions.visibilityOf(IndiGo_Text)); SpiceJet_Checkbox.click(); //wait.until(ExpectedConditions.visibilityOf(SpiceJet_Text)); //Vistara_Checkbox.click(); //wait.until(ExpectedConditions.visibilityOf(Vistara_Text)); Apply_Button.click(); Util.waitForPageLoader(); System.out.println("Please find below flight details from Pune to Hyderabad"); List<WebElement> ls1=driver.findElements(By.xpath("//div[@class='result-col outr']//div[@class='price']//span/following-sibling::span")); ls1.size(); for(int i=1;i<=ls1.size();i++) { String amount=driver.findElement(By.xpath("(//div[@class='result-col outr']//div[@class='price']//span/following-sibling::span)["+i+"]")).getText(); int price=Integer.parseInt(amount); if(price<5000) { String flight=driver.findElement(By.xpath("(//div[@class='result-col outr']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='u-text-ellipsis']")).getText(); String[] Details=flight.split(" "); System.out.println("\nFlight Name is "+Details[0]); System.out.println("Flight Number is "+Details[1]); String Departure_time=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='time-group']/div[@class='time'][1]")).getText(); String Arrival_time=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='time-group']/div[@class='time'][2]")).getText(); System.out.println("Flight Departure_time is "+Departure_time); System.out.println("Flight Arrival_time is "+Arrival_time); } } System.out.println("Please find below flight details from Hyderabad to Pune"); List<WebElement> ls2=driver.findElements(By.xpath("//div[@class='result-col']//div[@class='price']//span/following-sibling::span")); ls1.size(); for(int i=1;i<=ls2.size();i++) { String amount=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]")).getText(); int price=Integer.parseInt(amount); if(price<5000) { String flight=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='u-text-ellipsis']")).getText(); String[] Details=flight.split(" "); System.out.println("\nFlight name is "+Details[0]); System.out.println("Flight number is "+Details[1]); String Departure_time=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='time-group']/div[@class='time'][1]")).getText(); String Arrival_time=driver.findElement(By.xpath("(//div[@class='result-col']//div[@class='price']//span/following-sibling::span)["+i+"]/ancestor::div[@class='summary-section']//div[@class='time-group']/div[@class='time'][2]")).getText(); System.out.println("Flight Departure_time is "+Departure_time); System.out.println("Flight Arrival_time is "+Arrival_time); } } } }
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.company.cubavisionclinic.web.invoices; import com.company.cubavisionclinic.entity.Invoices; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.actions.CreateAction; import com.haulmont.cuba.gui.components.actions.EditAction; import com.haulmont.cuba.gui.components.actions.RemoveAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.DataSupplier; import com.haulmont.cuba.gui.data.Datasource; import javax.inject.Inject; import javax.inject.Named; import java.util.Collections; import java.util.Map; import java.util.UUID; import com.haulmont.cuba.core.entity.IdProxy; public class InvoicesBrowse extends AbstractLookup { @Inject private CollectionDatasource<Invoices, IdProxy<Long>> invoicesDs; @Inject private Datasource<Invoices> invoiceDs; @Inject private Table<Invoices> invoicesTable; @Inject private BoxLayout lookupBox; @Inject private BoxLayout actionsPane; @Inject private FieldGroup fieldGroup; @Inject private TabSheet tabSheet; @Named("invoicesTable.remove") private RemoveAction invoicesTableRemove; @Inject private DataSupplier dataSupplier; private boolean creating; @Override public void init(Map<String, Object> params) { invoicesDs.addItemChangeListener(e -> { if (e.getItem() != null) { Invoices reloadedItem = dataSupplier.reload(e.getDs().getItem(), invoiceDs.getView()); invoiceDs.setItem(reloadedItem); } }); invoicesTable.addAction(new CreateAction(invoicesTable) { @Override protected void internalOpenEditor(CollectionDatasource datasource, Entity newItem, Datasource parentDs, Map<String, Object> params) { invoicesTable.setSelected(Collections.emptyList()); invoiceDs.setItem((Invoices) newItem); enableEditControls(true); } }); invoicesTable.addAction(new EditAction(invoicesTable) { @Override protected void internalOpenEditor(CollectionDatasource datasource, Entity existingItem, Datasource parentDs, Map<String, Object> params) { if (invoicesTable.getSelected().size() == 1) { enableEditControls(false); } } }); /** * Handles the {@link Invoices} instance removal from the table. If the selected item is removed, removes the * selection from the table */ invoicesTableRemove.setAfterRemoveHandler(removedItems -> invoiceDs.setItem(null)); disableEditControls(); } public void save() { getDsContext().commit(); Invoices editedItem = invoiceDs.getItem(); if (creating) { invoicesDs.includeItem(editedItem); } else { invoicesDs.updateItem(editedItem); } invoicesTable.setSelected(editedItem); disableEditControls(); } public void cancel() { Invoices selectedItem = invoicesDs.getItem(); if (selectedItem != null) { Invoices reloadedItem = dataSupplier.reload(selectedItem, invoiceDs.getView()); invoicesDs.setItem(reloadedItem); } else { invoiceDs.setItem(null); } disableEditControls(); } private void enableEditControls(boolean creating) { this.creating = creating; initEditComponents(true); fieldGroup.requestFocus(); } private void disableEditControls() { initEditComponents(false); invoicesTable.requestFocus(); } private void initEditComponents(boolean enabled) { ComponentsHelper.walkComponents(tabSheet, (component, name) -> { if (component instanceof FieldGroup) { ((FieldGroup) component).setEditable(enabled); } else if (component instanceof Table) { ((Table) component).getActions().stream().forEach(action -> action.setEnabled(enabled)); } }); actionsPane.setVisible(enabled); lookupBox.setEnabled(!enabled); } }
package baadraan.u.batman.ui; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import baadraan.u.batman.R; import baadraan.u.batman.SnackMessage; import baadraan.u.batman.db.DatabaseHelper; import baadraan.u.batman.service.MoviePresenter; import baadraan.u.batman.service.MovieSingle; import baadraan.u.batman.service.MovieView; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class DetailActivity extends AppCompatActivity implements MovieView.movieSingle { ImageView img , imgBack; ProgressBar pb; TextView title , year , genre , country , moreDetail , actors , director , writers, imdbRate , sumRate, boxOffice , detail ; MoviePresenter presenter; String imdbId; boolean internet; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); internet = isInternetConnection(); init(); } private void init(){ img = (ImageView)findViewById(R.id.img_movie_detail); imgBack = (ImageView)findViewById(R.id.img_back_detail); title = (TextView)findViewById(R.id.tNamedetail); year = (TextView)findViewById(R.id.tYear); genre = (TextView)findViewById(R.id.tZhanr); country = (TextView)findViewById(R.id.tCountry); moreDetail = (TextView)findViewById(R.id.more_detail); actors = (TextView)findViewById(R.id.actors); director = (TextView)findViewById(R.id.director); writers = (TextView)findViewById(R.id.writers); imdbRate = (TextView)findViewById(R.id.txt_rate); sumRate = (TextView)findViewById(R.id.txt_sum_rate); boxOffice = (TextView)findViewById(R.id.boxoffice); detail = (TextView)findViewById(R.id.detail); pb = (ProgressBar)findViewById(R.id.pb); imdbId = getIntent().getStringExtra("imdbId"); CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.coll); collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.colorPrimary)); if (internet){ presenter = new MoviePresenter(this); presenter.getMovieById(imdbId); }else { DatabaseHelper dbh = new DatabaseHelper(getApplicationContext()); MovieSingle movie = dbh.getMovieById(imdbId); setData(movie); } } @Override public void success(MovieSingle movie) { setData(movie); DatabaseHelper dbh = new DatabaseHelper(getApplicationContext()); dbh.update(movie); } @Override public void error(String error) { new SnackMessage(this , error , img).showMessage(); } public boolean isInternetConnection() { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; } private void setData(MovieSingle movie){ Picasso.get().load(movie.getPoster()).into(img); Picasso.get().load(movie.getPoster()).into(imgBack, new Callback() { @Override public void onSuccess() { pb.setVisibility(View.GONE); } @Override public void onError(Exception e) { } }); title.setText(movie.getTitle()); year.setText("سال : " + movie.getYear()); genre.setText( "ژانر : " + movie.getGenre()); country.setText("محصول کشور : " + movie.getCountry()); moreDetail.setText(movie.getLanguage() + " - " + movie.getRuntime()); actors.setText(movie.getActors()); director.setText(movie.getDirector()); writers.setText(movie.getWriter()); imdbRate.setText(movie.getImdbRating()); sumRate.setText(movie.getImdbVotes()); boxOffice.setText("فروش : "+movie.getBoxOffice()); detail.setText(movie.getPlot()); } }
package work; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * 做接口测试 * @author SL * @date 2016-10-28 * * */ public class Upgrade { public CloseableHttpClient httpclient= HttpClients.createDefault(); public CloseableHttpResponse response = null; /** * 登录功能 * @param urlLogin post方法的url * @param userP user参数 * @param pwdP password 参数 * @return 0 说明登录失败,200说明登录成功 * * */ public int login (String urlLogin,String userP,String pwdP,String user,String pwd){ HttpPost httppost = new HttpPost(urlLogin); // 创建参数队列 List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); formparams.add(new BasicNameValuePair(userP, user)); formparams.add(new BasicNameValuePair(pwdP, pwd)); UrlEncodedFormEntity uefEntity; int resultCode = 0; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); response = httpclient.execute(httppost); resultCode = response.getStatusLine().getStatusCode(); } catch (Exception e) { e.printStackTrace(); } return resultCode; } /** * 发送 get请求 * @param url get方法的url * @return 0 说明登录失败,200说明登录成功 */ public int get(String url) { int result = 0; try { // 创建httpget. HttpGet httpget = new HttpGet(url); // 执行get请求. response = httpclient.execute(httpget); try { System.out.println("------------------------------------"); // 打印响应状态 result = response.getStatusLine().getStatusCode(); System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8")); System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.synchronization.populator; import de.hybris.platform.cmsfacades.data.ItemTypeData; import de.hybris.platform.cmsfacades.data.SyncItemInfoJobStatusData; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import org.springframework.beans.factory.annotation.Required; /** * Simple class for populating {@link ItemTypeData} from {@link SyncItemInfoJobStatusData}. */ public class ItemTypeDataPopulator implements Populator<SyncItemInfoJobStatusData, ItemTypeData> { private static final String DOT = "."; private String prefix; private String suffix; @Override public void populate(final SyncItemInfoJobStatusData source, final ItemTypeData target) throws ConversionException { final String i18nKey = getPrefix() + DOT + source.getItem().getItemtype() + DOT + getSuffix(); target.setI18nKey(i18nKey.toLowerCase()); target.setItemType(source.getItem().getItemtype()); } protected String getPrefix() { return prefix; } @Required public void setPrefix(final String prefix) { this.prefix = prefix; } protected String getSuffix() { return suffix; } @Required public void setSuffix(final String suffix) { this.suffix = suffix; } }
import java.util.Scanner; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.scene.Group ; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; public class GlowAirHockeyApp extends Application { private Table table; final static int DELAY = 10; public static void main(String[] args) { Application.launch(args); } public void start(Stage primaryStage) throws Exception { Scanner scanner = new Scanner(System.in); // The following takes input from the user, which is then used to create a new game. System.out.print("Enter a username for player one: "); String player_one_name = scanner.nextLine(); System.out.println(""); System.out.print("Enter a colour for player one's paddle: "); String player_one_colour = scanner.nextLine(); System.out.println(""); System.out.print("Enter a username for player one: "); String player_two_name = scanner.nextLine(); System.out.println(""); System.out.print("Enter a colour for player two's paddle: "); String player_two_colour = scanner.nextLine(); System.out.println(""); System.out.print("Enter a colour for the puck: "); String puck_colour = scanner.nextLine(); scanner.close(); // Creating a new table. table = new Table(new Player(player_one_name, player_one_colour), new Player(player_two_name, player_two_colour), new Puck(puck_colour)); // Setting the puck and paddles to their starting positions. table.resetPuck(); table.resetPlayerOne(); table.resetPlayerTwo(); Group g = new Group(); Pane root = new Pane(); root.setPrefSize(table.WIDTH, table.HEIGHT); root.setStyle("-fx-background-color: BLACK;"); // Timeline to call the event handler every 10ms to update the table. Timeline timeline = new Timeline( new KeyFrame(Duration.millis(DELAY), new EventHandler <ActionEvent>() { @Override public void handle(ActionEvent event) { updateGame(); } } ) ) ; timeline.setCycleCount(Timeline.INDEFINITE); timeline.setAutoReverse(true); timeline.play(); Circle center_circle = new Circle(); center_circle.setRadius(80); center_circle.setFill(Color.RED); center_circle.setCenterX(table.CENTER_X); center_circle.setCenterY(table.CENTER_Y); Circle center_circle_cover = new Circle(); center_circle_cover.setRadius(75); center_circle_cover.setFill(Color.BLACK); center_circle_cover.setCenterX(table.CENTER_X); center_circle_cover.setCenterY(table.CENTER_Y); Circle center = new Circle(); center.setRadius(5); center.setFill(Color.RED); center.setCenterX(table.CENTER_X); center.setCenterY(table.CENTER_Y); Rectangle left_border = new Rectangle(); left_border.setX(0); left_border.setY(0); left_border.setHeight(table.HEIGHT); left_border.setWidth(10); left_border.setFill(Color.DARKRED); Rectangle right_border = new Rectangle(); right_border.setX(table.WIDTH - 10); right_border.setY(0); right_border.setHeight(800); right_border.setWidth(10); right_border.setFill(Color.DARKRED); Rectangle top_border = new Rectangle(); top_border.setX(0); top_border.setY(table.HEIGHT - 10); top_border.setHeight(10); top_border.setWidth(table.WIDTH); top_border.setFill(Color.DARKRED); Rectangle bottom_border = new Rectangle(); bottom_border.setX(0); bottom_border.setY(0); bottom_border.setHeight(10); bottom_border.setWidth(table.WIDTH); bottom_border.setFill(Color.DARKRED); Rectangle center_line = new Rectangle(); center_line.setX(0); center_line.setY(table.CENTER_Y + -3); center_line.setHeight(6); center_line.setWidth(table.WIDTH); center_line.setFill(Color.RED); Rectangle player_one_goal = new Rectangle(); player_one_goal.setX(table.CENTER_X - table.GOAL_SIZE / 2); player_one_goal.setY(0); player_one_goal.setHeight(10); player_one_goal.setWidth(table.GOAL_SIZE); player_one_goal.setFill(Color.CHARTREUSE); Rectangle player_two_goal = new Rectangle(); player_two_goal.setX(table.CENTER_X - table.GOAL_SIZE / 2); player_two_goal.setY(table.HEIGHT - 10); player_two_goal.setHeight(10); player_two_goal.setWidth(table.GOAL_SIZE); player_two_goal.setFill(Color.CHARTREUSE); root.getChildren().addAll(center_line, left_border, right_border, top_border, bottom_border, player_one_goal, player_two_goal, center_circle, center_circle_cover, center); root.getChildren().add(table.getPuck()); root.getChildren().add(table.getPlayerOne()); root.getChildren().add(table.getPlayerTwo()); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.setTitle("Glow Air Hockey"); primaryStage.show(); } // This function updates what is necessary with each tick in the timeline. public void updateGame() { table.applyFriction(DELAY); table.updatePuckPosition(DELAY); table.updatePaddlePositions(DELAY); table.checkForGoal(); table.paddleCollision(table.getPlayerOne(), DELAY); table.paddleCollision(table.getPlayerTwo(), DELAY); table.keepPuckIn(); table.keepPaddlesIn(); } }
package script.groovy.servlet.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = {ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) @Documented public @interface ControllerMapping { public String interceptClass() default ""; }
package com.computerstudent.madpractical.Practical_19; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.provider.Settings; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action=intent.getAction(); if(action != null){ if(action.equals(Intent.ACTION_BOOT_COMPLETED)){ Toast.makeText(context,"BOOT COMPLETED",Toast.LENGTH_LONG).show(); } if(Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0)==0) { Toast.makeText(context, "Airplane mode off",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(context,"Airplane mode on",Toast.LENGTH_LONG).show(); } } } }
package com.raggiadolf.connectfour; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import org.honorato.multistatetogglebutton.MultiStateToggleButton; public class MainMenuActivity extends AppCompatActivity { MultiStateToggleButton m_difficultySelector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu); m_difficultySelector = (MultiStateToggleButton) this.findViewById(R.id.difficulty_selector); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void startSinglePlayer(View view) { Intent intent = new Intent(this, SinglePlayerActivity.class); switch(m_difficultySelector.getValue()) { case 0: intent.putExtra("difficulty", "easy"); break; case 1: intent.putExtra("difficulty", "medium"); break; case 2: intent.putExtra("difficulty", "hard"); break; default: intent.putExtra("difficulty", "easy"); break; } startActivity(intent); } public void startMultiPlayer(View view) { Intent intent = new Intent(this, MultiPlayerFragmentActivity.class); startActivity(intent); } }
package com.fordprog.matrix.interpreter; import org.antlr.v4.runtime.ParserRuleContext; public class CodePoint { private final int lineNumber; private final int columnNumber; public CodePoint(int lineNumber, int columnNumber) { this.lineNumber = lineNumber; this.columnNumber = columnNumber; } public static CodePoint from(ParserRuleContext ctx) { return new CodePoint(ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine()); } public int getLineNumber() { return lineNumber; } public int getColumnNumber() { return columnNumber; } @Override public String toString() { return "line: " + lineNumber + ", column: " + columnNumber; } }
package com.tencent.mm.ui.chatting; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import com.tencent.mm.R; import com.tencent.mm.ak.e; import com.tencent.mm.ak.f; import com.tencent.mm.ak.o; import com.tencent.mm.bp.a; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.modelvideo.r; import com.tencent.mm.modelvideo.s; import com.tencent.mm.modelvideo.t; import com.tencent.mm.pluginsdk.model.app.ao; import com.tencent.mm.pluginsdk.model.app.l; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.bd; import com.tencent.mm.storage.bd.b; import com.tencent.mm.ui.base.h; import com.tencent.mm.y.g$a; import com.tencent.tmassistantsdk.downloadservice.DownloadHelper; import com.tencent.wework.api.IWWAPI; import com.tencent.wework.api.WWAPIFactory; import com.tencent.wework.api.model.BaseMessage; import com.tencent.wework.api.model.WWMediaConversation; import com.tencent.wework.api.model.WWMediaFile; import com.tencent.wework.api.model.WWMediaImage; import com.tencent.wework.api.model.WWMediaLink; import com.tencent.wework.api.model.WWMediaLocation; import com.tencent.wework.api.model.WWMediaMergedConvs; import com.tencent.wework.api.model.WWMediaMessage.WWMediaObject; import com.tencent.wework.api.model.WWMediaText; import com.tencent.wework.api.model.WWMediaVideo; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.List; public final class an { public static void a(Context context, ab abVar, List<bd> list, boolean z) { IWWAPI ii = WWAPIFactory.ii(context); try { BaseMessage c; if (list.size() == 1) { c = c((bd) list.get(0), z); } else { c = a(abVar, list, z); } ii.a(c); } catch (a e) { h.i(context, R.l.sending_ww_file_too_large_warning, R.l.app_tip); } } private static WWMediaObject c(bd bdVar, boolean z) { int type = bdVar.getType(); if (type == 1) { return new WWMediaText(j.p(bdVar.field_content, bdVar.field_isSend, z)); } String o; WWMediaObject wWMediaImage; if (type == 3) { e br; if (bdVar.field_msgId > 0) { br = o.Pf().br(bdVar.field_msgId); } else { br = null; } if ((br == null || br.dTK <= 0) && bdVar.field_msgSvrId > 0) { br = o.Pf().bq(bdVar.field_msgSvrId); } if (br == null) { return null; } o = o.Pf().o(f.c(br), "", ""); wWMediaImage = new WWMediaImage(); wWMediaImage.filePath = o; x.i("MicroMsg.SendToWeWorkHelper", "send img2, path:%s", new Object[]{wWMediaImage.filePath}); return wWMediaImage; } else if (type == 43) { wWMediaImage = new WWMediaVideo(); r nW = t.nW(bdVar.field_imgPath); com.tencent.mm.modelvideo.o.Ta(); wWMediaImage.filePath = s.nK(nW.getFileName()); x.i("MicroMsg.SendToWeWorkHelper", "send video2, path:%s", new Object[]{wWMediaImage.filePath}); return wWMediaImage; } else if (type == 48) { wWMediaImage = new WWMediaLocation(); o = j.p(bdVar.field_content, bdVar.field_isSend, z); au.HU(); b GS = c.FT().GS(o); wWMediaImage.title = GS.kFa; wWMediaImage.dRH = GS.label; wWMediaImage.longitude = GS.kCx; wWMediaImage.latitude = GS.kCw; wWMediaImage.vzL = (double) GS.bSz; return wWMediaImage; } else if (type == 49 || type == 268435505) { return d(bdVar, z); } else { x.e("MicroMsg.SendToWeWorkHelper", "unsupport msg type: %d", new Object[]{Integer.valueOf(type)}); return null; } } private static WWMediaObject a(ab abVar, List<bd> list, boolean z) { WWMediaMergedConvs wWMediaMergedConvs = new WWMediaMergedConvs(); String str = abVar.field_username; Context context = ad.getContext(); if (z) { str = context.getString(R.l.record_chatroom_title); } else { str = q.GH().equals(com.tencent.mm.model.r.gS(str)) ? context.getString(R.l.favorite_record_chatroom_title, new Object[]{q.GH()}) : context.getString(R.l.favorite_record_chat_title, new Object[]{q.GH(), com.tencent.mm.model.r.gS(str)}); } wWMediaMergedConvs.title = str; for (bd bdVar : list) { WWMediaConversation wWMediaConversation = new WWMediaConversation(); String GF = bdVar.field_isSend == 1 ? q.GF() : !z ? bdVar.field_talker : com.tencent.mm.model.bd.iB(bdVar.field_content); wWMediaConversation.name = com.tencent.mm.model.r.gS(GF); try { Bitmap a = com.tencent.mm.aa.c.a(GF, false, -1); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); a.compress(CompressFormat.JPEG, 100, byteArrayOutputStream); wWMediaConversation.vzJ = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); } catch (Exception e) { } wWMediaConversation.mEo = bdVar.field_createTime; wWMediaConversation.vzK = c(bdVar, z); if (wWMediaConversation.checkArgs()) { wWMediaMergedConvs.vzM.add(wWMediaConversation); } } return wWMediaMergedConvs; } private static WWMediaObject d(bd bdVar, boolean z) { g$a J; String str = bdVar.field_content; if (z) { int indexOf = bdVar.field_content.indexOf(58); if (indexOf != -1) { str = bdVar.field_content.substring(indexOf + 1); } } if (str != null) { J = g$a.J(str, bdVar.field_reserved); } else { J = null; } if (J == null) { return null; } switch (J.type) { case 2: if (J.bGP == null || J.bGP.length() <= 0) { return null; } com.tencent.mm.pluginsdk.model.app.b SR = ao.asF().SR(J.bGP); if (SR == null || !SR.aSc()) { return null; } str = SR.field_fileFullPath; if (com.tencent.mm.a.e.cn(str)) { WWMediaObject wWMediaImage = new WWMediaImage(); wWMediaImage.filePath = str; x.i("MicroMsg.SendToWeWorkHelper", "send img2, path:%s", new Object[]{wWMediaImage.filePath}); return wWMediaImage; } x.i("MicroMsg.SendToWeWorkHelper", "Img not exist, bigImgPath: %s, msgId: %d, msgSvrId: %d", new Object[]{str, Long.valueOf(bdVar.field_msgId), Long.valueOf(bdVar.field_msgSvrId)}); return null; case 5: OutputStream byteArrayOutputStream; WWMediaLink wWMediaLink = new WWMediaLink(); wWMediaLink.webpageUrl = J.url; wWMediaLink.title = J.title; wWMediaLink.description = J.description; Bitmap a = o.Pf().a(bdVar.field_imgPath, a.getDensity(null), false); try { byteArrayOutputStream = new ByteArrayOutputStream(); a.compress(CompressFormat.JPEG, 85, byteArrayOutputStream); wWMediaLink.thumbData = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); } catch (Exception e) { } try { a = o.Pf().a(bdVar.field_imgPath, a.getDensity(null), false); byteArrayOutputStream = new ByteArrayOutputStream(); a.compress(CompressFormat.JPEG, 100, byteArrayOutputStream); wWMediaLink.thumbData = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); } catch (Exception e2) { } return wWMediaLink; case 6: com.tencent.mm.pluginsdk.model.app.b SZ = l.SZ(J.bGP); if (SZ == null) { SZ = ao.asF().fH(bdVar.field_msgId); } if (SZ.field_totalLen > DownloadHelper.SAVE_LENGTH) { throw new a((byte) 0); } WWMediaFile wWMediaFile = new WWMediaFile(); wWMediaFile.fileName = J.title; wWMediaFile.filePath = SZ.field_fileFullPath; wWMediaFile.contentLengthLimit = 104857600; return wWMediaFile; default: return null; } } }
package com.java.featuress; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @FunctionalInterface public interface MyInterface { public Integer addTwoNo(Integer i1, Integer i2); public default Integer mul(Integer i1, Integer i2) { return i1 * i2; } public default Integer div(Integer i1, Integer i2) { return i2 / i1; } public static Integer addArray(Integer[] ar) { return Arrays.asList(ar).stream().collect(Collectors.summingInt(Integer::new)); } public static Integer addList(List<Integer> list) { return list.stream().collect(Collectors.summingInt(Integer::new)); } }
package kimmyeonghoe.cloth.service.logo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kimmyeonghoe.cloth.dao.logo.LogoDao; @Service public class LogoServiceImpl implements LogoService{ @Autowired private LogoDao logoDao; @Override public int addImage(String fileName, String storedName, int fileSize) { return logoDao.insertImage(fileName, storedName, fileSize); } @Override public int addLogo(String logoName, String storedName) { return logoDao.insertLogo(logoName, storedName); } @Override public String getLogoName() { return logoDao.selectLogoName(); } @Override public int getLogoNum() { return logoDao.selectlogoNum(); } @Override public String getStoredName(int logoNum) { return logoDao.selectStoredName(logoNum); } @Override public int delImage(int imageNum) { return logoDao.deleteImage(imageNum); } @Override public int delLogo(int logoNum) { return logoDao.deleteLogo(logoNum); } }
package com.mathpar.students.ukma.Grushka.Module2Part1; import mpi.MPI; import mpi.MPIException; public class TestAllGatherv { public static void main(String[] args) throws MPIException, InterruptedException { // MPI definition MPI.Init(args); // Determine the number of processors and processor amount in a group int myrank = MPI.COMM_WORLD.getRank(); int np = MPI.COMM_WORLD.getSize(); // Input an array size int n = 4; if (args.length != 0) n = Integer.parseInt(args[0]); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i; } int[] q = new int[n * np]; MPI.COMM_WORLD.allGatherv(a, n, MPI.INT, q, new int[]{n, n}, new int[]{0, 2}, MPI.INT); Thread.sleep(60 * myrank); System.out.println("myrank " + myrank + " : "); if (myrank == np - 1) { for (int i = 0; i < q.length; i++) { System.out.println(" " + q[i]); } } System.out.println(); MPI.Finalize(); } } //mpirun -np 2 java -cp out/production/Module2Part1 TestAllGatherv // Result (2 processors & n=4): // myrank 0 : // // myrank 1 : // 0 // 1 // 0 // 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 algorithmlab; import java.util.Arrays; /** * * @author pigrick */ public class Sort4with5Compare { public static int[] sort4with5Compare(int[] n){ int upperbig, lowerBig, biggest, upperSmall, lowerSmall, smallest, upperMiddle, lowerMiddle; if(n[0] > n[1]){ upperbig = n[0]; upperSmall = n[1]; } else { upperbig = n[1]; upperSmall = n[0]; } if(n[2] > n[3]){ lowerBig = n[2]; lowerSmall = n[3]; } else { lowerBig = n[3]; lowerSmall = n[2]; } if(upperSmall > lowerSmall){ upperMiddle = upperSmall; smallest = lowerSmall; } else { upperMiddle = lowerSmall; smallest = upperSmall; } if(upperbig > lowerBig){ lowerMiddle = lowerBig; biggest = upperbig; } else { lowerMiddle = upperbig; biggest = lowerBig; } if(upperMiddle > lowerMiddle){ int[] a = {smallest, lowerMiddle, upperMiddle, biggest}; return a; } else { int[] a = {smallest, upperMiddle, lowerMiddle, biggest}; return a; } } public static void main(String[] args) { int[] b = {2,3,5,1}; System.out.println(Arrays.toString(sort4with5Compare(b))); } }
package tecnicas.u04; import java.util.Scanner; public class Ej19Bis { /* Crear un programa que muestre en pantalla una escalera inversa de asteriscos. * La cantidad de filas de la escalera se ingresa por teclado. Utilice la * instrucción for. */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Cantidad de filas: "); int cantAsteriscos = sc.nextInt(); int lineas = cantAsteriscos; for (int i = 0; i < lineas; i++) { for (int j = 0; j < cantAsteriscos; j++) { System.out.print("*"); } cantAsteriscos--; System.out.println(""); } sc.close(); } }
package ga.islandcrawl.controller.intelligence; import ga.islandcrawl.map.O; import ga.islandcrawl.object.unit.Unit; /** * Created by Ga on 11/20/2015. */ public class Social extends Behavior { public int followers; public int charisma; public Social(Unit host) { super(host); charisma = host.randInt(10); } public void say(String p){ } @Override public void reactAlly(O p){ if (goal == null) setLeader((Unit) p.occupant); reactFree(); } @Override public void goalReached(){ setAction("Idle"); } public boolean setLeader(Unit candidate){ if (candidate.brain instanceof Social){ Social s = (Social)candidate.brain; if (s.charisma-s.followers > charisma){ goal = candidate.pos; s.followers++; return true; } } return false; } }