text
stringlengths
10
2.72M
public class Solucion2 { int i; public void Tmultiplicar() { do{ int j=1; do { System.out.println(i + "x" + j + "=" +(i*j)); j++; }while(j<=10); i++; }while(i<10); } }
package jc.sugar.JiaHui.jmeter.controller; import jc.sugar.JiaHui.jmeter.*; import org.apache.jmeter.control.SwitchController; import java.util.HashMap; import java.util.Map; import static org.apache.jorphan.util.Converter.getString; @JMeterElementMapperFor(value = JMeterElementType.SwitchController, testGuiClass = JMeterElement.SwitchController) public class SwitchControllerMapper extends AbstractJMeterElementMapper<SwitchController> { public static final String WEB_VALUE = "value"; private SwitchControllerMapper(SwitchController element, Map<String, Object> attributes) { super(element, attributes); } public SwitchControllerMapper(Map<String, Object> attributes){ this(new SwitchController(), attributes); } public SwitchControllerMapper(SwitchController element){ this(element, new HashMap<>()); } @Override public SwitchController fromAttributes() { element.setSelection(getString(attributes.get(WEB_VALUE))); return element; } @Override public Map<String, Object> toAttributes() { attributes.put(WEB_CATEGORY, JMeterElementCategory.Controller); attributes.put(WEB_TYPE, JMeterElementType.SwitchController); attributes.put(WEB_VALUE, element.getSelection()); return attributes; } }
/* * Google Calendar Plugin * Copyright (C) 2011 OTS SA * 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.plugins.googlecalendar; import com.google.api.client.googleapis.auth.clientlogin.ClientLogin; import com.google.api.client.http.HttpResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.PostJob; import org.sonar.api.batch.SensorContext; import org.sonar.api.resources.Project; import java.io.IOException; import org.apache.commons.configuration.Configuration; import org.sonar.api.platform.Server; /** * @author Papapetrou P.Patroklos */ public class GoogleCalendarPublisher implements PostJob { /** Sonar Property for Google Account. */ public static final String ACCOUNT_PROP = "sonar.google.calendar.account"; /** Sonar Property for Google Account Password. */ public static final String PASSWORD_PROP = "sonar.google.calendar.password"; /** Sonar Property for Google Calendar ID. */ public static final String CALENDAR_ID_PROP = "sonar.google.calendar.calendarname"; /** Sonar Property for Enabling / Disabling Google Calendar Plugin. */ public static final String ENABLED_PROP = "sonar.google.calendar.enabled"; /** Project Base URI. */ private static final String PROJECT_BASE_URI = "/project/index/"; /** Google Feeds URL. */ private static final String GOOGLE_FEEDS = "http://www.google.com/calendar/feeds/"; /** Google Feeds URL. */ private static final String GOOGLE_PRIV_CAL = "/private/full"; /** Class Logger using SL4J. */ private static final Logger LOGGER = LoggerFactory.getLogger(GoogleCalendarPublisher.class); /** Sonar Server. */ private final Server server; public GoogleCalendarPublisher(final Server serverPrm) { this.server = serverPrm; } public final void executeOn(final Project prj, final SensorContext sensorContext) { final Configuration configuration = prj.getConfiguration(); final String username = configuration.getString(ACCOUNT_PROP); final String password = configuration.getString(PASSWORD_PROP); final String calendarID = configuration.getString(CALENDAR_ID_PROP); final String isEnabled = configuration.getString(ENABLED_PROP); if (isEnabled != null && isEnabled.equals("true")) { ClientLogin authenticator = new ClientLogin(); authenticator.authTokenType = "cl"; authenticator.username = username; authenticator.password = password; authenticator.transport = GoogleHttpTransportFactory.AUTH_TRANSPORT; try { authenticator.authenticate().setAuthorizationHeader(GoogleHttpTransportFactory.DEFAULT_TRANSPORT); GoogleCalendarUrl calendarUrl = new GoogleCalendarUrl(this.getCalendarURL(calendarID)); GoogleEventEntry newEvent = new GoogleEventEntry(); newEvent.title = this.getTitle(prj); newEvent.content = this.getContent(prj); newEvent.executeInsert(calendarUrl); } catch (HttpResponseException ex) { LOGGER.error(ex.getLocalizedMessage(), ex); } catch (IOException ex) { LOGGER.error(ex.getLocalizedMessage(), ex); } } } public final String getTitle(final Project project) { return String.format("Sonar analysis of %s", project.getName()); } public final String getContent(final Project project) { final StringBuilder url = new StringBuilder(server.getURL()).append(PROJECT_BASE_URI).append(project.getKey()); return String.format( "New Sonar analysis of %s is available online at %s", project.getName(), url); } public final String getCalendarURL(final String calendarID) { final StringBuilder calendarURL = new StringBuilder(GOOGLE_FEEDS); calendarURL.append(calendarID); calendarURL.append(GOOGLE_PRIV_CAL); return calendarURL.toString(); } }
package io.vlabs.test; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import io.vlabs.CalculatorTesting; public class CalcTest { @Test public void checkAdd() { assertEquals(3, new CalculatorTesting().add(1, 2)); } // @Test(expected=ArithmeticException.class) // public void testArithmeticException() { // new CalculatorTesting().mul(1, 0); // } // @Parameter // public void testParameterised() { // assertEquals(2, new CalculatorTesting().add(a, b)); // } }
package com.Epsilon.deliveryservice.app.service; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import com.Epsilon.deliveryservice.app.DBHelper; import com.Epsilon.deliveryservice.app.DataController; import com.Epsilon.deliveryservice.app.MainActivity; import com.Epsilon.deliveryservice.app.R; import com.google.android.gms.gcm.GcmListenerService; import com.loopj.android.http.AsyncHttpResponseHandler; import org.apache.http.Header; import org.json.JSONObject; import java.text.SimpleDateFormat; public class GCMIntentService extends GcmListenerService { private static Context context; @Override public void onCreate() { super.onCreate(); context = this; } private void showNotification(int id, String message, String title, String ticker, int deliveryId) { if (id != 1) { try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) // .setContentIntent(contentIntent) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(message) .setTicker(ticker) .setOngoing(false); if (deliveryId >= 0) { Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.putExtra("delivery_id", deliveryId); notificationIntent.putExtra("push_notification", true); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(contentIntent); } else { PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(contentIntent); } mBuilder.setAutoCancel(false); mBuilder.setOnlyAlertOnce(true); NotificationManager notifyMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); notifyMgr.notify(id, mBuilder.build()); } } @Override public void onMessageReceived(String from, Bundle data) { try { String type = data.getString("msg_type", ""); int pushId = Integer.valueOf(data.getString("push_id", "0")); String message = data.getString("message", ""); if (type.equals("new_delivery")) { String deliveryId = data.getString("delivery_id"); showNotification(pushId, message, getString(R.string.push_title_new_delivery).replace("%ID", deliveryId), getString(R.string.push_title_new_delivery).replace("%ID", deliveryId), Integer.valueOf(deliveryId)); } else if (type.equals("new_settings")) { showNotification(pushId, message, data.getString("message"), data.getString("title"), -1); if (DataController.FLAG_NETWORK_SETTINGS) { DataController.clientDM.get("https://dm-project.org/api/v1/courier_management/phone_settings/?format=json", null, new AsyncHttpResponseHandler(Looper.getMainLooper()) { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { JSONObject response = new JSONObject(new String(responseBody)).getJSONArray("results").getJSONObject(0); DataController.memclearMemoryLimit = response.getInt("clean_memory_volume"); DataController.memclearPhotosCount = response.getInt("clean_memory_count_photo"); DataController.yandexDiskUploadPath = response.getString("ya_photo_load_path"); DataController.FLAG_LOCATION_PROVIDER_GPS = response.getBoolean("source_location_is_gps"); DataController.FLAG_LOCATION_PROVIDER_NETWORK = response.getBoolean("source_location_is_wifi"); DataController.GPSUpdateInterval = response.getInt("gps_coords_update_period") * 60000; DataController.wifiAndNetworkUpdateInterval = response.getInt("wifi_coords_update_period") * 60000; DataController.coordinatesUploadInterval = response.getInt("coords_load_period") * 1000 * 60; DataController.locationMinDistance = response.getInt("min_coords_distance"); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); DataController.startUploadCoordinatesTime = format.parse(response.getString("start_time_coordinate_load")).getHours(); DataController.stopUploadCoordinatesTime = format.parse(response.getString("end_time_coordinate_load")).getHours(); DataController.adminPassword = response.getString("admin_password"); UploadService.getInstance().startLocationUpdates(); UploadService.getInstance().restartLocationUpload(); DataController.saveUserData(context); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {} }); } } else if (type.equals("courier_auth")) { // DataController.resetUserData(context); DataController.clientDM.cancelAllRequests(true); DataController.clientDM.removeAllHeaders(); DataController.deliveriesCache = null; // DataController.dbHelper = new DBHelper(context, "DATA"); DataController.dbHelper.deleteCachedJson("deliveries"); DataController.cookieDM = ""; DataController.usernameDM = data.getString("fio"); DataController.usernameYandex = ""; DataController.authTokenDM = data.getString("dm_token"); DataController.tokenYandex = data.getString("ya_token"); DataController.saveUserData(context); if (DataController.activity != null) { Intent intent = new Intent("com.Epsilon.deliveryservice.app.authorized"); // intent.putExtra("authorized", "true"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } // } /* try { FragmentManager fragmentManager = DataController.activity.getSupportFragmentManager(); while (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } } catch (Exception e) {e.printStackTrace();} DataController.activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new DeliveriesListFragment()).commit(); // DataController.activity.getUsernameDM(); // DataController.activity.getUsernameYandex(); // DataController.activity.restartApp(new View(DataController.activity)); }*/ showNotification(pushId, message, data.getString("title"), data.getString("title"), -1); } } catch (Exception e) { e.printStackTrace(); } } }
package com.saes.iptools ; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.net.*; public class TabipcalcActivity extends Activity { private TextView sMask4oct; private TextView sNumHosts; private TextView sNumAddres; private TextView sNumAddresIni; private TextView sNumAddresEnd; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tab1ipcalc); final EditText edittext = (EditText) findViewById(R.id.entry); edittext.setText(""); final EditText ipaddr = (EditText) findViewById(R.id.addrbase); final Button button = (Button) findViewById(R.id.ok); final Button buttonC = (Button) findViewById(R.id.clear); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Toast.makeText(IpsncActivity.this, edittext.getText().toString(), Toast.LENGTH_LONG).show(); int numNodos = 0; InetAddress ipAddr = null; InetAddress ipAddrIni = null; InetAddress ipAddrEnd = null; try { numNodos = Integer.parseInt(edittext.getText().toString()); } catch (Exception e) { TabipcalcActivity.this.showMessage("ip-Calc: Error en dato MASCARA ... "); } if(numNodos>=1 && numNodos <=32){ double nNod; double nAddr; if(32 - numNodos > 1){ nNod = Math.pow(2,(32 - numNodos)) -2; nAddr = nNod + 2; }else{ nNod = 33 - numNodos; nAddr = nNod; } String sNod; if(nNod > 0){ sNod = ""+nNod; }else{ sNod = "1"; } String sAddr = ""+(int)nAddr; byte [] bip = {0,0,0,0}; byte [] bipi = {0,0,0,0}; byte [] bipe = {0,0,0,0}; byte [] bmask = {0,0,0,0}; try{ bip = TabipcalcActivity.this.sip2bip(ipaddr.getText().toString()); bmask = TabipcalcActivity.this.sip2bip(ipMask(numNodos)); } catch (Exception e) { TabipcalcActivity.this.showMessage("ip-Calc: Error en dato IP ..."); } try{ //ipAddrIni ipAddr = InetAddress.getByAddress(bip); for(int i=0; i<=3; i++){ bipi[i] = (byte) (bip[i] & bmask[i]); bipe[i] = (byte) (bip[i] | ~bmask[i]); //TabipcalcActivity.this.showMessage("bipi["+i+"]: "+bipi[i]+" bmask["+i+"]: "+bmask[i]); } ipAddrIni = InetAddress.getByAddress(bipi); ipAddrEnd = InetAddress.getByAddress(bipe); } catch (Exception e) { TabipcalcActivity.this.showMessage("ip-Calc: Error creando InetAddress ..."); } sMask4oct = (TextView) findViewById(R.id.mask4oct); sMask4oct.setText(ipMask(numNodos)); sMask4oct.setVisibility(View.VISIBLE); sNumHosts = (TextView) findViewById(R.id.numHost); sNumHosts.setText(sNod.substring(0, sNod.length()-2)); sNumHosts.setVisibility(View.VISIBLE); sNumAddres = (TextView) findViewById(R.id.numAddr); sNumAddres.setText(sAddr); sNumAddres.setVisibility(View.VISIBLE); sNumAddresIni = (TextView) findViewById(R.id.numAddrIni); sNumAddresIni.setText(ipAddrIni.getHostAddress()); sNumAddresIni.setVisibility(View.VISIBLE); sNumAddresEnd = (TextView) findViewById(R.id.numAddrEnd); sNumAddresEnd.setText(ipAddrEnd.getHostAddress()); sNumAddresEnd.setVisibility(View.VISIBLE); }else{ TabipcalcActivity.this.showMessage("ip-Calc: Numero de bits debe ser \nentre 1 y 32 ..."); edittext.setText(""); sMask4oct = (TextView) findViewById(R.id.mask4oct); sNumHosts = (TextView) findViewById(R.id.numHost); sNumAddres = (TextView) findViewById(R.id.numAddr); sNumAddresIni = (TextView) findViewById(R.id.numAddrIni); sNumAddresEnd = (TextView) findViewById(R.id.numAddrEnd); sNumHosts.setVisibility(View.INVISIBLE); sMask4oct.setVisibility(View.INVISIBLE); sNumAddres.setVisibility(View.INVISIBLE); sNumAddresIni.setVisibility(View.INVISIBLE); sNumAddresEnd.setVisibility(View.INVISIBLE); } } }); buttonC.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { edittext.setText(""); ipaddr.setText(R.string.ipaddr_def); sNumHosts.setVisibility(View.INVISIBLE); sMask4oct.setVisibility(View.INVISIBLE); sNumAddres.setVisibility(View.INVISIBLE); sNumAddresIni.setVisibility(View.INVISIBLE); sNumAddresEnd.setVisibility(View.INVISIBLE); } catch (Exception e) { TabipcalcActivity.this.showMessage("ip-Calc: Sin datos que borrar ..."); } } }); } public byte[] sip2bip(String sip){ byte[] b = {0,1,2,3}; byte[] bip = {0,0,0,0}; String[] sarr = sip.split("[.]",4); for(int i : b){ bip[i] = (byte)Integer.parseInt(sarr[i]); } return bip; } public String ipMask(int nBits){ String sMask = ""; int nSubBits = nBits % 8; double decMask = 0; int k = 7; while((8-k)<=nSubBits) { decMask = decMask + Math.pow(2,k); k--; } int nFullOct = (nBits - (nSubBits))/8; int[] numbers = {1,2,3,4}; for(int i : numbers) { if(i<=nFullOct){ sMask = sMask + "255"; }else if(i==(nFullOct+1)){ sMask = sMask + (int)decMask; }else{ sMask = sMask + "0"; } if(i<4){ sMask=sMask+"."; } } return sMask.substring(0, sMask.length()); } public void showMessage(String txMsg){ LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.icon); TextView text = (TextView) layout.findViewById(R.id.text); text.setText(txMsg); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.TOP, 0, 50); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } }
package com.box.androidsdk.content.requests; import android.content.Context; import com.box.androidsdk.content.BoxApiUser; import com.box.androidsdk.content.models.BoxIteratorUsers; import com.box.androidsdk.content.models.BoxUser; import com.box.androidsdk.content.testUtil.PowerMock; import com.box.androidsdk.content.testUtil.SessionUtil; import com.eclipsesource.json.JsonObject; import junit.framework.Assert; import org.junit.Test; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import java.io.UnsupportedEncodingException; import java.text.ParseException; @PrepareForTest({ BoxHttpResponse.class, BoxHttpRequest.class, BoxRequest.class, BoxRequestsUser.class}) public class BoxUserRequestTest extends PowerMock { private static final String USER_ID = "10543463"; private static final String SAMPLE_USER_JSON = "{ \"type\": \"user\", \"id\": \"10543463\", \"name\": \"Arielle Frey\", \"login\": \"ariellefrey@box.com\", \"created_at\": \"2011-01-07T12:37:09-08:00\", \"modified_at\": \"2014-05-30T10:39:47-07:00\", \"language\": \"en\", \"timezone\": \"America/Los_Angeles\", \"space_amount\": 10737418240, \"space_used\": 558732, \"max_upload_size\": 5368709120, \"status\": \"active\", \"job_title\": \"\", \"phone\": \"\", \"address\": \"\", \"avatar_url\": \"https://app.box.com/api/avatar/deprecated\" }"; @Mock Context mMockContext; @Test public void testCreateEnterpriseUserRequestProperties() throws ParseException { String login = "tester@gmail.com"; String name = "tester"; String address = "4440 El Camino Real"; String jobTitle = "Tester"; String phone = "123-456-7890"; double space = 1000; String timezone = "Asia/Hong_Kong"; BoxApiUser userApi = new BoxApiUser(null); BoxRequestsUser.CreateEnterpriseUser request = userApi.getCreateEnterpriseUserRequest(login, name) .setAddress(address) .setJobTitle(jobTitle) .setPhone(phone) .setSpaceAmount(space) .setRole(BoxUser.Role.COADMIN) .setStatus(BoxUser.Status.ACTIVE) // .setTrackingCodes() .setTimezone(timezone) .setCanSeeManagedUsers(true) .setIsExemptFromDeviceLimits(true) .setIsExemptFromLoginVerification(true) .setIsSyncEnabled(true); Assert.assertEquals(login, request.getLogin()); Assert.assertEquals(name, request.getName()); Assert.assertEquals(address, request.getAddress()); Assert.assertEquals(jobTitle, request.getJobTitle()); Assert.assertEquals(phone, request.getPhone()); Assert.assertEquals(space, request.getSpaceAmount()); Assert.assertEquals(timezone, request.getTimezone()); Assert.assertEquals(BoxUser.Status.ACTIVE, request.getStatus()); Assert.assertEquals(BoxUser.Role.COADMIN, request.getRole()); Assert.assertTrue(request.getCanSeeManagedUsers()); Assert.assertTrue(request.getIsExemptFromDeviceLimits()); Assert.assertTrue(request.getIsExemptFromLoginVerification()); Assert.assertTrue(request.getCanSeeManagedUsers()); Assert.assertTrue(request.getIsSyncEnabled()); } @Test public void testCreateEnterpriseUserRequest() throws UnsupportedEncodingException { String expected = "{\"login\":\"tester@gmail.com\",\"name\":\"tester\",\"address\":\"4440 El Camino Real\",\"job_title\":\"Tester\",\"phone\":\"123-456-7890\",\"space_amount\":\"1000.0\",\"role\":\"coadmin\",\"status\":\"active\",\"timezone\":\"Asia/Hong_Kong\",\"can_see_managed_users\":\"true\",\"is_exempt_from_device_limits\":\"true\",\"is_exempt_from_login_verification\":\"true\",\"is_sync_enabled\":\"true\"}"; String login = "tester@gmail.com"; String name = "tester"; String address = "4440 El Camino Real"; String jobTitle = "Tester"; String phone = "123-456-7890"; double space = 1000; String timezone = "Asia/Hong_Kong"; BoxApiUser userApi = new BoxApiUser(null); BoxRequestsUser.CreateEnterpriseUser request = userApi.getCreateEnterpriseUserRequest(login, name) .setAddress(address) .setJobTitle(jobTitle) .setPhone(phone) .setSpaceAmount(space) .setRole(BoxUser.Role.COADMIN) .setStatus(BoxUser.Status.ACTIVE) // .setTrackingCodes() .setTimezone(timezone) .setCanSeeManagedUsers(true) .setIsExemptFromDeviceLimits(true) .setIsExemptFromLoginVerification(true) .setIsSyncEnabled(true); String json = request.getStringBody(); Assert.assertEquals(expected, json); } @Test public void testUserInfoRequest() throws Exception { final String expectedRequestUrl = "https://api.box.com/2.0/users/" + USER_ID; BoxApiUser userApi = new BoxApiUser(SessionUtil.newMockBoxSession(mMockContext)); BoxRequestsUser.GetUserInfo userInfoRequest = userApi.getUserInfoRequest(USER_ID); mockSuccessResponseWithJson(SAMPLE_USER_JSON); BoxUser boxUser = userInfoRequest.send(); Assert.assertEquals(expectedRequestUrl, userInfoRequest.mRequestUrlString); Assert.assertEquals(JsonObject.readFrom(SAMPLE_USER_JSON), boxUser.toJsonObject()); } @Test public void testCurrentUserInfoRequest() throws Exception { final String expectedRequestUrl = "https://api.box.com/2.0/users/me"; BoxApiUser userApi = new BoxApiUser(SessionUtil.newMockBoxSession(mMockContext)); BoxRequestsUser.GetUserInfo userInfoRequest = userApi.getCurrentUserInfoRequest(); mockSuccessResponseWithJson(SAMPLE_USER_JSON); BoxUser boxUser = userInfoRequest.send(); Assert.assertEquals(expectedRequestUrl, userInfoRequest.mRequestUrlString); Assert.assertEquals(JsonObject.readFrom(SAMPLE_USER_JSON), boxUser.toJsonObject()); } @Test public void testMockCreateEnterpriseUserRequest() throws Exception { final String expectedRequestUrl = "https://api.box.com/2.0/users"; BoxApiUser userApi = new BoxApiUser(SessionUtil.newMockBoxSession(mMockContext)); BoxRequestsUser.CreateEnterpriseUser userInfoRequest = userApi.getCreateEnterpriseUserRequest("ariellefrey@box.com", "Arielle Frey"); mockSuccessResponseWithJson(SAMPLE_USER_JSON); BoxUser boxUser = userInfoRequest.send(); Assert.assertEquals(expectedRequestUrl, userInfoRequest.mRequestUrlString); Assert.assertEquals(JsonObject.readFrom(SAMPLE_USER_JSON), boxUser.toJsonObject()); } @Test public void testGetEnterpriseUsersRequest() throws Exception { final String expectedRequestUrl = "https://api.box.com/2.0/users"; final String enterpriseUsersJson = "{ \"total_count\": 1, \"entries\": [ { \"type\": \"user\", \"id\": \"181216415\", \"name\": \"sean rose\", \"login\": \"sean+awesome@box.com\", \"created_at\": \"2012-05-03T21:39:11-07:00\", \"modified_at\": \"2012-08-23T14:57:48-07:00\", \"language\": \"en\", \"space_amount\": 5368709120, \"space_used\": 52947, \"max_upload_size\": 104857600, \"status\": \"active\", \"job_title\": \"\", \"phone\": \"5555551374\", \"address\": \"10 Cloud Way Los Altos CA\", \"avatar_url\": \"https://app.box.com/api/avatar/large/181216415\" } ] }"; BoxApiUser userApi = new BoxApiUser(SessionUtil.newMockBoxSession(mMockContext)); BoxRequestsUser.GetEnterpriseUsers enterpriseUsersRequest = userApi.getEnterpriseUsersRequest(); mockSuccessResponseWithJson(enterpriseUsersJson); BoxIteratorUsers boxUsers = enterpriseUsersRequest.send(); Assert.assertEquals(expectedRequestUrl, enterpriseUsersRequest.mRequestUrlString); Assert.assertEquals(JsonObject.readFrom(enterpriseUsersJson), boxUsers.toJsonObject()); } }
package com.rednavis.application.impl; import com.fasterxml.jackson.databind.ObjectMapper; import com.rednavis.application.services.JobManagerClientService; import com.rednavis.application.services.JobmanagerSessionService; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import javax.inject.Inject; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Eugene Tsydzik * on 4/14/18. */ @Service @Log4j2 public class JobmanagerSessionServiceImpl implements JobmanagerSessionService { @Inject JobManagerClientService jobManagerClientService; /** * The session mapper. */ private List<WebSocketSession> sessionList = new ArrayList<>(); public void addClientSession(WebSocketSession session) { sessionList.add(session); } @Inject private ObjectMapper mapper; @Override public void newMessage(WebSocketSession session, WebSocketMessage<?> message) throws IOException { session.sendMessage(new TextMessage(mapper.writeValueAsString(jobManagerClientService.getBaselineJobs()))); } @Override public void removeSession(WebSocketSession session) { sessionList.remove(session); } }
package com.ptit.dktran.broadcastandbroadcastreceiver; /** * Created by dktran on 8/12/2017. */ public class Constant { public static final String ACTION_SEND_BROADCAST_DEMO = "ACTION_SEND_BROADCAST_DEMO"; }
package com.classcheck.panel; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.io.File; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JToolBar; import javax.swing.border.LineBorder; import com.classcheck.gen.GenerateTestProgram; import com.classcheck.tree.FileNode; import com.classcheck.window.DebugMessageWindow; public class GenerateToolBar extends JToolBar { Action genAction; ImageIcon genIcon; private File baseDir; private MemberTabPanel mtp; //javaファイルのパスやデータを格納するリストを用意する(import文に使用する) private List<FileNode> javaFileNodeList; public GenerateToolBar(String name, MemberTabPanel mtp, int operation, FileNode baseDir, List<FileNode> javaFileNodeList) { super(name, operation); this.mtp = mtp; this.baseDir = baseDir; this.javaFileNodeList = javaFileNodeList; setLayout(new FlowLayout(FlowLayout.LEFT, 3, 3)); add(Box.createHorizontalGlue()); setBorder(new LineBorder(Color.LIGHT_GRAY,1)); setPreferredSize(null); initComponent(); setVisible(true); } private void initComponent() { //ツールバーにアイコンを入れ,テストプログラムを生成するイベントも作る genIcon = new ImageIcon(GenerateToolBar.class.getResource("/icons/start.png")); genAction = new AbstractAction("genAction",genIcon) { @Override public void actionPerformed(ActionEvent e) { GenerateState gs = GenerateState.NORMAL; if (mtp.getTablePane().isNullItemSelected()) { JOptionPane.showMessageDialog(getParent(), "テーブルのセルにクラスを選択してください", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.TABLENULL; return ; } if(mtp.getTablePane().isSameTableItemSelected()){ JOptionPane.showMessageDialog(getParent(), "テーブルに同じクラスを選択しないでください", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.TABLESAMECLASS; return ; } if(!mtp.isFieldEpmty()){ JOptionPane.showMessageDialog(getParent(), "フィールドの選択ができない空のクラスがあります", "error", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(getParent(), "クラス図の修飾子や型を参考にソースコードを修正してください", "info", JOptionPane.INFORMATION_MESSAGE); gs = GenerateState.FIELDNULL; return ; } if(!mtp.isMethodEmpty()){ JOptionPane.showMessageDialog(getParent(), "メソッドの選択ができない空のクラスがあります", "error", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(getParent(), "クラス図のシグネチャを参考にソースコードを修正してください", "info", JOptionPane.INFORMATION_MESSAGE); gs = GenerateState.METHODNULL; return ; } if (!mtp.isFieldEpmty()) { JOptionPane.showMessageDialog(getParent(), "空のフィールドがあります", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.FIELDNULL; return ; } if (!mtp.isMethodEmpty()) { JOptionPane.showMessageDialog(getParent(), "空のメソッドがあります", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.METHODNULL; return ; } //すべてのクラスのフィールドを調べる if (!mtp.isFieldGeneratable()) { JOptionPane.showMessageDialog(getParent(), "同じフィールドを選択しないでください", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.FIELDSAME; return ; } //すべてのクラスのメソッドを調べる if (!mtp.isMethodGeneratable()) { JOptionPane.showMessageDialog(getParent(), "同じメソッドを選択しないでください", "error", JOptionPane.ERROR_MESSAGE); gs = GenerateState.METHODSAME; return ; } if (gs == GenerateState.NORMAL) { if(new GenerateTestProgram(baseDir,mtp,javaFileNodeList).doExec()){ JOptionPane.showMessageDialog(getParent(), "テストプログラムを生成しました","成功",JOptionPane.INFORMATION_MESSAGE); }else{ //JOptionPane.showMessageDialog(getParent(), "テストプログラムに失敗しました","失敗",JOptionPane.ERROR_MESSAGE); } } DebugMessageWindow.msgToTextArea(); } }; add(genAction); } }
public class Result03 { int data = 0; public Result03() { System.out.println(data); data++; } public Result03(int data) { System.out.println(this.data); this.data += data; } public static void main(String[] args) { Result03 r1 = new Result03(); System.out.println(r1.data); Result03 r2 = new Result03(5); System.out.println(r2.data); } }
//Array Built in Function Demo import java.util.Arrays; public class ArrayFunctionDemo{ public static void main(String[] ags) { int[] arr1={1,2,3}; int[] arr2=new int[3]; //Copy Array Demo System.arraycopy(arr1,0,arr2,0,3); System.out.println("Second element in Arr2 "+arr2[1]); //copy at different position int[] arr3={1,2,3,4,5,6}; System.arraycopy(arr1,0,arr3,3,2); System.out.println("Arr3 elemet at position 4 "+arr3[3]+" and position 6 "+arr3[5]); //array equals int[] arr4={5,6,7}; int[] arr5={5,6,7}; int[] arr6={5,5,7}; System.out.println(arr4.length+" "+arr5.length); System.out.println(Arrays.equals(arr4,arr5)); System.out.println(Arrays.equals(arr5,arr6)); } }
public class LivingRoom { public }
package com.hb.rssai.view.me; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.hb.rssai.R; import com.hb.rssai.base.BaseActivity; import com.hb.rssai.bean.ResMessageList; import com.hb.rssai.presenter.BasePresenter; import com.hb.rssai.util.HttpLoadImg; import butterknife.BindView; public class MessageContentActivity extends BaseActivity { @BindView(R.id.sys_tv_title) TextView mSysTvTitle; @BindView(R.id.sys_toolbar) Toolbar mSysToolbar; @BindView(R.id.app_bar_layout) AppBarLayout mAppBarLayout; @BindView(R.id.mc_tv_title) TextView mMcTvTitle; @BindView(R.id.mc_iv_img) ImageView mMcIvImg; @BindView(R.id.mc_tv_pubTime) TextView mMcTvPubTime; @BindView(R.id.mc_tv_content) TextView mMcTvContent; @BindView(R.id.mc_tv_url) TextView mMcTvUrl; public static final String KEY_MSG_BEAN = "msgBean"; @BindView(R.id.mc_ll_no_data) LinearLayout mMcLlNoData; private ResMessageList.RetObjBean.RowsBean message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void initIntent() { Bundle bundle = getIntent().getExtras(); if (bundle != null) { message = (ResMessageList.RetObjBean.RowsBean) bundle.getSerializable(KEY_MSG_BEAN); } } @Override protected void initView() { if (message != null) { mMcLlNoData.setVisibility(View.GONE); mMcTvTitle.setText(message.getTitle()); if (!TextUtils.isEmpty(message.getImg())) { HttpLoadImg.loadImg(this, message.getImg(), mMcIvImg); } mMcTvPubTime.setText("发布时间:"+message.getPubTime()); mMcTvContent.setText(message.getContent()); mMcTvUrl.setText(message.getUrl()); } else { mMcLlNoData.setVisibility(View.VISIBLE); } } @Override protected int providerContentViewId() { return R.layout.activity_message_content; } @Override protected void setAppTitle() { mSysToolbar.setTitle(""); setSupportActionBar(mSysToolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true);//设置ActionBar一个返回箭头,主界面没有,次级界面有 actionBar.setDisplayShowTitleEnabled(false); } mSysTvTitle.setText(getResources().getString(R.string.str_message_content_title)); } @Override protected BasePresenter createPresenter() { return null; } }
package ru.otus.db; /* * Created by VSkurikhin at winter 2018. */ import ru.otus.models.*; import javax.servlet.ServletContext; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.HashMap; import java.util.Map; public interface DBConf { String userName = "dbuser"; String dbName = "db"; String password = "password"; String TABLE_USERS = "users"; String TABLE_DEP_DIRECTORY = "dep_directory"; String TABLE_EMP_REGISTRY = "emp_registry"; String TABLE_USER_GROUPS = "user_groups"; String TABLE_STATISTIC = "statistic"; String[] TABLES = new String[] { TABLE_USERS, TABLE_DEP_DIRECTORY, TABLE_EMP_REGISTRY, TABLE_USER_GROUPS, TABLE_STATISTIC, }; String[] ORDER_OF_DELETE_TABLES = new String[] { TABLE_EMP_REGISTRY, TABLE_DEP_DIRECTORY, TABLE_STATISTIC, TABLE_USER_GROUPS, TABLE_USERS, }; Map<String, String> FILE_LOCATIONS = new HashMap<String , String>() {{ put(TABLE_DEP_DIRECTORY, "DeptEntitiesXMLDataFileLocation"); put(TABLE_EMP_REGISTRY, "EmpEntitiesXMLDataFileLocation"); put(TABLE_STATISTIC, "StatisticEntitiesXMLDataFileLocation"); put(TABLE_USER_GROUPS, "UsersgroupEntitiesXMLDataFileLocation"); put(TABLE_USERS, "UserEntitiesXMLDataFileLocation"); }}; Class<?>[] CLASSES = new Class<?>[] { DeptEntity.class, DeptEntitiesList.class, EmpEntity.class, EmpEntitiesList.class, GroupEntity.class, GroupEntitiesList.class, StatisticEntity.class, StatisticEntitiesList.class, UserEntity.class, UserEntitiesList.class, }; static <T extends EntitiesList> ImporterSmallXML<T> createImporterXML(ServletContext sc, String s) throws IOException, JAXBException { String entitiesXMLPath = sc.getInitParameter(s); return new ImporterSmallXML<>(sc, entitiesXMLPath, CLASSES); } } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package org.motechproject.server.exception; public class MessageContentExtractionException extends Exception { }
package com.example.hereapi_example; import java.util.ArrayList; import com.here.android.common.GeoCoordinate; import com.here.android.common.GeoPolygon; import com.here.android.mapping.FragmentInitListener; import com.here.android.mapping.InitError; import com.here.android.mapping.Map; import com.here.android.mapping.MapAnimation; import com.here.android.mapping.MapFactory; import com.here.android.mapping.MapFragment; import com.here.android.mapping.MapPolygon; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; public class PolygonDemoActivity extends Activity implements OnSeekBarChangeListener{ private static final double SYDNEY_lat = -33.87365; private static final double SYDNEY_lon = 151.20689; private Map mMap= null; private static final int WIDTH_MAX = 50; private static final int HUE_MAX = 360; private static final int ALPHA_MAX = 255; private MapPolygon mMutablePolygon = null; private SeekBar mColorBar; private SeekBar mAlphaBar; private SeekBar mWidthBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.polygon_demo); mColorBar = (SeekBar) findViewById(R.id.hueSeekBar); mColorBar.setMax(HUE_MAX); mColorBar.setProgress(0); mAlphaBar = (SeekBar) findViewById(R.id.alphaSeekBar); mAlphaBar.setMax(ALPHA_MAX); mAlphaBar.setProgress(127); mWidthBar = (SeekBar) findViewById(R.id.widthSeekBar); mWidthBar.setMax(WIDTH_MAX); mWidthBar.setProgress(10); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { if(mMap == null){ final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map); // initialize the Map Fragment to create a map and // attached to the fragment mapFragment.init(new FragmentInitListener() { @Override public void onFragmentInitializationCompleted(InitError error) { if (error == InitError.NONE) { mMap = (Map) mapFragment.getMap(); setUpMap(); } } }); } } private void setUpMap() { // Create a rectangle with two rectangular holes. if(mMap == null){ return; } ArrayList<GeoPolygon> holesList = new ArrayList<GeoPolygon> (2); holesList.add(createRectangle(-22, 128, 1, 1)); holesList.add(createRectangle(-18, 133, 0.5, 1.5)); GeoPolygon polly = createRectangle(-20, 130, 5, 5); MapPolygon tmpPolyn = MapFactory.createMapPolygon(polly, holesList); tmpPolyn.setFillColor(Color.CYAN); tmpPolyn.setLineColor(Color.BLUE); tmpPolyn.setLineWidth(5); mMap.addMapObject(tmpPolyn); // Create a rectangle centered at Sydney. GeoPolygon options = createRectangle(SYDNEY_lat, SYDNEY_lon, 5, 8); int fillColor = Color.HSVToColor(mAlphaBar.getProgress(), new float[] {mColorBar.getProgress(), 1, 1}); mMutablePolygon = MapFactory.createMapPolygon(options); mMutablePolygon.setFillColor(fillColor); mMutablePolygon.setLineColor(Color.BLACK); mMutablePolygon.setLineWidth(mWidthBar.getProgress()); mMap.addMapObject(mMutablePolygon); mColorBar.setOnSeekBarChangeListener(this); mAlphaBar.setOnSeekBarChangeListener(this); mWidthBar.setOnSeekBarChangeListener(this); // Toast.makeText(this, "zomto: " + options.getBoundingBox().getTopLeft() + ", " + options.getBoundingBox().getBottomRight(), Toast.LENGTH_LONG).show(); // Move the map so that it is centered on the mutable polygon. mMap.zoomTo(options.getBoundingBox(), MapAnimation.NONE, 0); // mMap.setCenter(options.getBoundingBox().getTopLeft(), MapAnimation.NONE); } /** * Creates a List of LatLngs that form a rectangle with the given dimensions. */ private GeoPolygon createRectangle(double lat, double lon, double halfWidth, double halfHeight) { // Create the GeoPolygon required by MapPolygon. GeoPolygon geoPolygon = null; try { ArrayList<GeoCoordinate> pointList = new ArrayList<GeoCoordinate> (5); pointList.add(MapFactory.createGeoCoordinate((lat - halfHeight), (lon - halfWidth))); pointList.add(MapFactory.createGeoCoordinate((lat - halfHeight), (lon + halfWidth))); pointList.add(MapFactory.createGeoCoordinate((lat + halfHeight), (lon + halfWidth))); pointList.add(MapFactory.createGeoCoordinate((lat + halfHeight), (lon - halfWidth))); pointList.add(MapFactory.createGeoCoordinate((lat - halfHeight), (lon - halfWidth))); geoPolygon = MapFactory.createGeoPolygon(pointList); } catch (Exception ex) { // nothing to be done } return geoPolygon; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mMutablePolygon == null) { return; } if (seekBar == mColorBar) { mMutablePolygon.setFillColor(Color.HSVToColor(Color.alpha(mMutablePolygon.getFillColor()), new float[] {progress, 1, 1})); } else if (seekBar == mAlphaBar) { int prevColor = mMutablePolygon.getFillColor(); mMutablePolygon.setFillColor(Color.argb(progress, Color.red(prevColor), Color.green(prevColor),Color.blue(prevColor))); } else if (seekBar == mWidthBar) { mMutablePolygon.setLineWidth(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } }
package com.example.drockot.testapp; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Observer; import ws.wamp.jawampa.WampClient; import ws.wamp.jawampa.WampClientBuilder; import ws.wamp.jawampa.WampError; import ws.wamp.jawampa.transport.netty.NettyWampClientConnectorProvider; public class UhMessageService extends Service { private WampClient client; public UhMessageService() { } private final IBinder myBinder = new MyLocalBinder(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return myBinder; } public class MyLocalBinder extends Binder { UhMessageService getService() { return UhMessageService.this; } } @Override public int onStartCommand(Intent intent, int flags, int startId) { startConnection(); return START_STICKY; } public void setupAuthSubscription (Observer<Boolean> observer, String username, String password) { final Observable<Boolean> stringSubscription = client.call("greenteam.auth", Boolean.class, username, password); stringSubscription.subscribe(observer); } public void setupMessageSubscription (String username) { final Observable<String> stringSubscription = client.makeSubscription("greenteam.user." + username + ".gotmessage", String.class); stringSubscription.subscribe(new Observer<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { Log.d("Debug", s); writeToFile(s); } }); } private void writeToFile(String data) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("inbox.txt", Context.MODE_PRIVATE)); outputStreamWriter.append(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } private void startConnection() { try { // Create a builder and configure the client WampClientBuilder builder = new WampClientBuilder(); builder.withConnectorProvider(new NettyWampClientConnectorProvider()) .withUri("ws://androiddev05.dlss.com:8080/") .withRealm("realm1") .withInfiniteReconnects() .withReconnectInterval(5, TimeUnit.SECONDS); // Create a client through the builder. This will not immediatly start // a connection attempt client = builder.build(); } catch (WampError e) { // Catch exceptions that will be thrown in case of invalid configuration System.out.println(e); return; } catch (Exception e) { // Catch exceptions that will be thrown in case of invalid configuration System.out.println(e); return; } client.statusChanged() .subscribe(new Observer<WampClient.State>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(WampClient.State state) { } }); client.open(); } }
package edu.nju.data.daoImpl; import edu.nju.RuanHuApplication; import edu.nju.data.dao.QuestionDAO; import edu.nju.data.entity.Question; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Created by ss14 on 2016/7/12. */ @RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! @SpringApplicationConfiguration(classes = RuanHuApplication.class) // 指定我们SpringBoot工程的Application启动类 @WebAppConfiguration @Rollback public class QuestionDAOImplTest { @Test public void getRelatedWikiItems() throws Exception { } @Test public void getRelatedDocuments() throws Exception { } @Autowired QuestionDAO questionDAO; @PersistenceContext EntityManager em; @Test public void save() throws Exception { for(int i=1 ; i<35 ;i++){ Question question = new Question(); question.setTitle("q"+i); question.setContent("c"+i); question.setAuthorId(new Long (3)); questionDAO.save(question); } } @Test public void save_id() throws Exception { Question question = new Question(); question.setAuthorId(new Long(1)); // question.getAuthor().setId(new Long (5)); long id = questionDAO.save_id(question); if(id==0){ fail(); }else{ System.out.println("Last inserted question id : "+ id); } } @Test public void save_question() throws Exception { Question question = new Question(); question.setAuthorId(new Long(2)); Question newQuestion= questionDAO.save_question(question); if(newQuestion.getId()==0){ fail(); }else{ System.out.println("Last inserted question id : "+ newQuestion.getId()); } } @Test public void createQuestion() throws Exception { Question question = new Question(); question.setAuthorId(new Long(2)); question.setTitle("如何练习外点归刹?求教"); question.setContent("如题"); List wikiIDs = new ArrayList(); List docuIDs = new ArrayList(); for(long i=1;i<=3;i++){ wikiIDs.add(i); docuIDs.add(2*i-1); } questionDAO.createQuestion(question , wikiIDs , docuIDs ); } @Test public void deleteByQuestionID() throws Exception { long id =2; Question temp = questionDAO.getQuestionByID(id); System.out.println("get questionid: "+temp.getId()); questionDAO.deleteByQuestionID(id); if(questionDAO.getQuestionByID(id)!=null){ fail("null"); } temp.setId(null); questionDAO.save(temp); } @Test public void deleteByAuthorID() throws Exception { Long authorid =new Long (1); int right=2; int result=questionDAO.deleteByAuthorID(authorid); if(result!=right){ fail(); } } @Test public void update() throws Exception { Question question = new Question(); question.setAuthorId(new Long(2)); question.setAnswerCount(new Integer(1)); question.setId(new Long(3)); questionDAO.update(question); } @Test public void getQuestionByID() throws Exception { long id = 1; Question question = questionDAO.getQuestionByID(id); String title = "q1"; String content = "c1"; String name = "ch"; if(question==null){ fail(); }else if (!title.equals(question.getTitle()) || !content.equals(question.getContent())||!question.getAuthor().getUserName().equals(name)){ fail(); } } @Test public void getPaginatedQuestions() throws Exception { // int pageNum=1; // int default_size=10; // List<Question> result = questionDAO.getPaginatedQuestions(pageNum); // if(result==null){ // fail(); // }else if (result.size()!=default_size){ // fail(); // }else if (result.get(0).getId() != 1) { // fail(); // // } } @Test public void getPaginatedQuestions1() throws Exception { // int pageNum=1; // int pageSize=15; // List<Question> result = questionDAO.getPaginatedQuestions(pageNum,pageSize); // if(result==null){ // fail(); // }else if (result.size()!=pageSize){ // fail(); // } } /** * 按参数排序,默认降序 // * @param pageNum // * @param para OrderByPara: createdAt lastUpdatedAt .... * @return */ @Test public void getPaginatedQuestions2() throws Exception { // int pageNum=1; // // List<Question> result = questionDAO.getPaginatedQuestions(pageNum, OrderByPara.answerCount); // if(result==null){ // fail(); // }else if (result.size()!=10){ // fail(); // }else{ // for(Question question : result){ // System.out.println("QuestionID : "+question.getId() +" "+question.getAnswerCount()); // } // } } @Test public void getPaginatedQuestions3() throws Exception { // int pageNum=1; // int pageSize=15; // List<Question> result = questionDAO.getPaginatedQuestions(pageNum,pageSize, OrderByPara.createdAt); // if(result==null){ // fail(); // }else if (result.size()!=pageSize){ // fail(); // }else{ // for(Question question : result){ // System.out.println("QuestionID : "+question.getId() +" "+question.getCreatedAt()); // } // } } @Test public void getPaginatedQuestions4() throws Exception { // int pageNum=1; // // List<Question> result = questionDAO.getPaginatedQuestions // (pageNum, OrderByPara.answerCount, OrderByMethod.ASC); // if(result==null){ // fail(); // }else if (result.size()!=10){ // fail(); // }else{ // for(Question question : result){ // System.out.println("QuestionID : "+question.getId() +" "+question.getAnswerCount()); // } // } } @Test public void getPaginatedQuestions5() throws Exception { // int pageNum=1; // int pageSize=15; // List<Question> result = questionDAO.getPaginatedQuestions // (pageNum,pageSize, OrderByPara.createdAt,OrderByMethod.ASC); // if(result==null){ // fail(); // }else if (result.size()!=pageSize){ // fail(); // }else{ // for(Question question : result){ // System.out.println("QuestionID : "+question.getId() +" "+question.getCreatedAt()); // } // } } @Test public void getQuestionByUsername() throws Exception { // long userID = 1 ; // String username = "ch"; // int resultSize =5; // String q1 = "q1"; // String q2 = "q2"; // List<Question> questionList = questionDAO .getQuestionByUsername(username); // if(questionList==null){ // fail("null"); // }else if ( questionList.size()!=resultSize){ // fail("size"); // // }else if (questionList.get(0).getAuthorId()!=userID){ // // fail("userID"); // }else{ // for (Question question : questionList){ // // System.out.println("questionID: "+question.getId()); // // System.out.println("userID: "+question.getAuthorId()); // // } // } } @Test public void getQuestionCountByUsername() throws Exception { String username = "ss14"; long right=3; long result=questionDAO.getQuestionCountByUsername(username); if(right!=result){ fail(); } } @Test public void getQuestionByUserID() throws Exception { // long userID = 1 ; // int resultSize =5; // String q1 = "q1"; // String q2 = "q2"; // List<Question> questionList = questionDAO .getQuestionByUserID(userID); // if(questionList==null){ // fail("null"); // }else if ( questionList.size()!=resultSize){ // fail("size"); // }else{ // for (Question question : questionList){ // // System.out.println("questionID: "+question.getId()); // // System.out.println("userID: "+question.getAuthorId()); // // } // } } @Test public void getQuestionCountByUserID() throws Exception { long userid=2; long right=3; long result=questionDAO.getQuestionCountByUserID(userid); if(right!=result){ fail(); } } }
package pl.norbgrusz.ui.di; import org.junit.Test; import pl.norbgrusz.keyfinder.StructureProperties; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class StructureControllerModuleTest { @Test public void getStructureProperties() throws IOException { Properties properties = new Properties(); InputStream propertiesFile = new FileInputStream(StructureControllerModule.class.getResource("/structure.properties").getFile()); properties.load(propertiesFile); StructureProperties.create(properties); } }
package de.jmda.app.uml.main.jaxb; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.jmda.core.util.xml.jaxb.MarshallerUtil; public abstract class Tools { private final static Logger LOGGER = LogManager.getLogger(Tools.class); private static JAXBContext JAXB_CONTEXT; private static Marshaller MARSHALLER; private static Unmarshaller UNMARSHALLER; public static JAXBContext getJAXBContext() { if (JAXB_CONTEXT == null) { // TreeSet<Package> packages = PackageFactory.createFromClassPathAndLoader(); // List<String> packageNames = asPackageNameList(packages); try { JAXB_CONTEXT = JAXBContext.newInstance ( // String.join(":", packageNames) new Class<?>[] { WorkspaceData.class, } ); } catch (Throwable t) { LOGGER.error(t); } } return JAXB_CONTEXT; } // private static List<String> asPackageNameList(TreeSet<Package> packages) // { // List<String> result = new ArrayList<>(); // packages.forEach(p -> result.add(p.getName())); // return result; // } /** * @return marshaller with output set to formatted * @throws JAXBException */ public static Marshaller getMarshaller() throws JAXBException { if (MARSHALLER == null) { MARSHALLER = getJAXBContext().createMarshaller(); MarshallerUtil.setOutputToformatted(MARSHALLER); } return MARSHALLER; } public static Unmarshaller getUnmarshaller() throws JAXBException { if (UNMARSHALLER == null) { UNMARSHALLER = getJAXBContext().createUnmarshaller(); } return UNMARSHALLER; } }
package com.jt.test; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import redis.clients.jedis.*; import java.util.*; @SpringBootTest @RunWith(SpringRunner.class) public class TestRedis { private Jedis jedis; @Autowired private ShardedJedis shardedJedis; @Before public void before(){ jedis = new Jedis("192.168.19.137",6379); } @Test public void test01(){ // jedis.set("bin","yehongbin"); //如果当前key已经存在,则不能修改 jedis.setnx("bin","剩下"); String bin = jedis.get("bin"); System.out.println(bin); //需求:1.添加超时时间 2.不允许重复操作 jedis.set("bin","刷新姓名","nx","",10); } /** * * 操作Hash */ @Test public void testHash(){ jedis.hset("person","id","100"); jedis.hset("person","name","人"); jedis.hset("person","age","18"); Map<String, String> person = jedis.hgetAll("person"); System.out.println(person); } /** * 操作list */ @Test public void testList(){ jedis.lpush("list","1","2","3","4","5"); // for (int i=0;i<6;i++){ // String list = jedis.rpop("list"); // System.out.println(list); // } } @Test public void testTx(){ Transaction multi = jedis.multi(); try { multi.set("dd","aaa"); // multi.set("bb","bbb"); // multi.set("cc","ccc"); int a = 1/0; System.out.println(a); multi.exec(); } catch (Exception e){ multi.discard(); } } /** * redis分片测试 */ @Test public void testShards(){ String host = "192.168.19.137"; List<JedisShardInfo> shardInfos = new ArrayList<>(); JedisShardInfo jedisShardInfo = new JedisShardInfo(host, 6379); jedisShardInfo.setPassword("root"); shardInfos.add(jedisShardInfo); JedisShardInfo jedisShardInfo1 = new JedisShardInfo(host, 6380); jedisShardInfo1.setPassword("root"); shardInfos.add(jedisShardInfo1); JedisShardInfo jedisShardInfo2 = new JedisShardInfo(host, 6381); jedisShardInfo2.setPassword("root"); shardInfos.add(jedisShardInfo2); ShardedJedis shardedJedis = new ShardedJedis(shardInfos); shardedJedis.set("dfghoeirer","分片操作"); System.out.println(shardedJedis.get("1904")); } @Test public void testShardsJedis(){ System.out.println(shardedJedis); } /** * 测试哨兵 */ @Test public void testSentinel(){ Set<String> sentinels = new HashSet<>(); sentinels.add("192.168.19.137:26379"); JedisSentinelPool pool = new JedisSentinelPool("mymaster",sentinels); Jedis jedis = pool.getResource(); jedis.set("1904","测试哨兵!"); System.out.println(jedis.get("1904")); } @Test public void testCluster(){ Set<HostAndPort> nodes = new HashSet<>(); nodes.add(new HostAndPort("192.168.19.137",7000)); nodes.add(new HostAndPort("192.168.19.137",7001)); nodes.add(new HostAndPort("192.168.19.137",7002)); nodes.add(new HostAndPort("192.168.19.137",7003)); nodes.add(new HostAndPort("192.168.19.137",7004)); nodes.add(new HostAndPort("192.168.19.137",7005)); JedisCluster cluster = new JedisCluster(nodes); cluster.set("1904","bin连接生"); System.out.println(cluster.get("1904")); } }
/* * Copyright © 2014 YAOCHEN Corporation, All Rights Reserved. */ package com.yaochen.address.data.mapper.address; import java.util.List; import com.easyooo.framework.sharding.annotation.Table; import com.yaochen.address.data.domain.address.AdCollections; import com.yaochen.address.support.Repository; @Repository @Table("AD_COLLECTIONS") public interface AdCollectionsMapper { int insert(AdCollections record); int insertSelective(AdCollections record); List<AdCollections> selectByExample(AdCollections coll); void deleteByAddrAndUser(AdCollections coll); }
package commands; import org.crsh.cli.Command; import org.crsh.command.BaseCommand; /** * @author April Han */ public class Hello extends BaseCommand { @Command public String main() { return "Hello World"; } }
package p9.Server; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import p9.server.netpaks.CharacterDataPackage; import p9.server.netpaks.CharacterList; import p9.server.netpaks.CharacterSpritePackage; import p9.server.netpaks.ClassDataSet; import p9.server.netpaks.EquipmentDataSet; import p9.server.netpaks.EquipmentInventory; import p9.server.netpaks.Item; import p9.server.netpaks.ItemInventory; import p9.server.netpaks.Spell; import p9.server.netpaks.SpellList; import p9.server.netpaks.UserAuthPackage; public class MySQLAccess { private Boolean debug = true; private Integer characterAmount = 3; String dbuser = ""; String dbpass = ""; public MySQLAccess(String du, String dp) throws ClassNotFoundException, SQLException { dbuser = du; dbpass = dp; } /** * This meathod gets the characters for the user, provided that there information is correct. * @param user * @param pass * @return * @throws ClassNotFoundException * @throws SQLException */ public CharacterList getCaharacters(UserAuthPackage uap) throws ClassNotFoundException, SQLException { Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/users?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "Select * from auth where username=\"" + uap.getUsername() + "\" AND password=\"" + uap.getPassword() + "\""; resultSet = statement.executeQuery(query); if(!resultSet.isBeforeFirst()){ return null; } ArrayList<String> sList = new ArrayList<String>(); //Do this to get the available chracters while(resultSet.next()){ for(Integer i = 1; i <= characterAmount; i ++){ sList.add(resultSet.getString("Char"+i.toString())); } } //this will get the character info for all the characters CharacterList cList = new CharacterList(); for(int i =0; i < sList.size(); i++){ cList.add(getCharInfo(sList.get(i))); } //this will pool all hte equipment ids for parsing ArrayList<Integer> eList = new ArrayList<Integer>(); for(int i = 0; i < cList.size();i++){ eList.addAll(cList.get(i).getIds()); } //this will parse the database for the equipment info for each piece of equipment. ArrayList<EquipmentDataSet> eds = new ArrayList<EquipmentDataSet>(); for(int i = 0; i < eList.size();i++){ eds.add(getEquipmentInfo(eList.get(i))); } //this will update all the containers inside the data set. for(int i =0; i< cList.size();i++){ cList.get(i).updateInfo(eds); // updates equpipments data containers cList.get(i).updateAtlas(); //updates the atlas for animation stuff cList.get(i).setClassData(getClass(cList.get(i).cClass));//update the classdata for each character. } //get spells from the DB //close everything so it dosent overload the database with too many connections statement.close(); resultSet.close(); connect.close(); //finally return the list to the Project 9 server return cList; } public CharacterDataPackage getCharInfo(String name) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from characters where name =\"" + name + "\""; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); CharacterDataPackage cis = new CharacterDataPackage(); while (resultSet.next()){ cis.setAll((Integer) resultSet.getObject("id"), (String) resultSet.getObject("name"),(Integer) resultSet.getObject("level"), (Integer) resultSet.getObject("class"), (Integer) resultSet.getObject("headslot"), (Integer) resultSet.getObject("chestSlot"), (Integer) resultSet.getObject("handsSlot"), (Integer) resultSet.getObject("fingerSlot1"), (Integer) resultSet.getObject("fingerSlot2"), (Integer) resultSet.getObject("fingerSlot3"), (Integer) resultSet.getObject("fingerSlot4"), (Integer) resultSet.getObject("fingerSlot5"), (Integer) resultSet.getObject("pantsSlot"), (Integer) resultSet.getObject("feetSlot"),(Integer) resultSet.getObject("leftHand"), (Integer) resultSet.getObject("RightHand"), (String) resultSet.getObject("gender"), (Integer) resultSet.getObject("gold")); } statement.close(); resultSet.close(); connect.close(); return cis; } public ClassDataSet getClass(int id) throws ClassNotFoundException, SQLException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from classes where id =\"" + id + "\""; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); ClassDataSet cis = new ClassDataSet(); while (resultSet.next()){ //int id, String name, String Slot, int armor, int mp, int attack, String imageName cis.setAll((Integer) resultSet.getObject("id"), (String) resultSet.getObject("name"), (Integer) resultSet.getObject("hpmod"), (Integer) resultSet.getObject("mpmod"),(Integer) resultSet.getObject("armormod"), (Integer) resultSet.getObject("attackmod"), (String) resultSet.getObject("imagename"), (Integer) resultSet.getObject("spellmod")); } statement.close(); resultSet.close(); connect.close(); return cis; } public EquipmentDataSet getEquipmentInfo(Integer id) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from equipment where id =\"" + id + "\""; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); EquipmentDataSet cis = new EquipmentDataSet(); while (resultSet.next()){ //int id, String name, String Slot, int armor, int mp, int attack, String imageName cis.setAll((Integer) resultSet.getObject("id"), (String) resultSet.getObject("name"), (String) resultSet.getObject("slot"), (Integer) resultSet.getObject("armor"),(Integer) resultSet.getObject("hp"), (Integer) resultSet.getObject("mp"), (Integer) resultSet.getObject("attack"), (String) resultSet.getObject("imagename")); } statement.close(); resultSet.close(); connect.close(); return cis; } public CharacterDataPackage updateCharacterSpellInventories(CharacterDataPackage cdp) throws ClassNotFoundException, SQLException{ cdp.spells= getSpells(cdp.name); return cdp; } public SpellList getSpells(String characterName) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventories?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from "+characterName+"_spellinventory"; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); SpellList cis = new SpellList(); if(!resultSet.isBeforeFirst()){ return cis; } while (resultSet.next()){ cis.add(getSpellInfo((Integer) resultSet.getObject("spellid"))); } System.out.println(cis.get(0).name); statement.close(); resultSet.close(); connect.close(); return cis; } public Spell getSpellInfo(int id) throws ClassNotFoundException, SQLException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from spells where id =\"" + id + "\""; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); Spell cis = new Spell(); while (resultSet.next()){ //int id, String name, String Slot, int armor, int mp, int attack, String imageName cis.setAll( (String) resultSet.getObject("name"), (Integer) resultSet.getObject("firedamage"), (Integer) resultSet.getObject("waterdamage"),(Integer) resultSet.getObject("winddamage"), (Integer) resultSet.getObject("earthdamage"), (Integer) resultSet.getObject("mpcost"), (String) resultSet.getObject("animationatlas"), (Integer) resultSet.getObject("healhp"), (Integer) resultSet.getObject("applystatus"),(Integer) resultSet.getObject("healstatus")); } statement.close(); resultSet.close(); connect.close(); cis.updateSpell(); return cis; } public CharacterDataPackage UpdateCharacterItemInvetory(CharacterDataPackage cdp) throws ClassNotFoundException, SQLException{ cdp.items= getItemInventory(cdp.name); return cdp; } public ItemInventory getItemInventory(String characterName) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventories?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from "+characterName+"_iteminventory"; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); ItemInventory cis = new ItemInventory(); if(!resultSet.isBeforeFirst()){ return cis; } Integer q = 0; while (resultSet.next()){ Item item = getItemInfo((Integer) resultSet.getObject("itemid")); q = (Integer) resultSet.getObject("quantity"); item.setQuantity(q); cis.add(item); } System.out.println(cis.get(0).name); statement.close(); resultSet.close(); connect.close(); return cis; } public Item getItemInfo(int id) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); String query = "select * from Items where id =\"" + id + "\""; resultSet = statement.executeQuery(query); ResultSetMetaData Meta = resultSet.getMetaData(); Item cis = new Item(); while (resultSet.next()){ //String name, Integer firedamage,Integer waterdamage,Integer winddamage,Integer earthdamage,String animationatlas, //Integer healhp, Integer applystatus, Integer healstatus, String imageName cis.setAll( (String) resultSet.getObject("name"), (Integer) resultSet.getObject("firedamage"), (Integer) resultSet.getObject("waterdamage"),(Integer) resultSet.getObject("winddamage"), (Integer) resultSet.getObject("earthdamage"), (String) resultSet.getObject("animationatlas"),(Integer) resultSet.getObject("healamount"), (Integer) resultSet.getObject("statuscaused"),(Integer) resultSet.getObject("statuscured"), (String) resultSet.getObject("imageName")); } statement.close(); resultSet.close(); connect.close(); cis.updateItem(); return cis; } public EquipmentInventory getEquipmentInventory(String characterName){ return null; //get the equipment in the chest for the character } public CharacterSpritePackage getSriteInformation(String characterName){ return null; //get sprite info from the DB. the object will beincomplete. the server app will complete it and send it to the client. } public ArrayList<HashMap<String,Object>> getRow(String query) throws SQLException, ClassNotFoundException{ Connection connect = null; Class.forName("com.mysql.jdbc.Driver");//driver connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Project8?user=" + dbuser + "&password=" + dbpass ); // login to the mysql server Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; statement = connect.createStatement(); // resultSet = statement.executeQuery(query); //check if a row is returned Boolean Returning_Rows = statement.execute(query); if(Returning_Rows){ resultSet = statement.getResultSet(); } else{ return (new ArrayList<HashMap<String,Object>>()); } ResultSetMetaData Meta = resultSet.getMetaData(); int colCount = Meta.getColumnCount(); ArrayList<String> cols = new ArrayList<String>(); for(int i = 1; i <= colCount; i++){ cols.add(Meta.getColumnName(i)); } ArrayList<HashMap<String, Object>> rows = new ArrayList<HashMap<String,Object>>(); while (resultSet.next()){ HashMap<String,Object> row = new HashMap<String,Object>(); for(String colName: cols){ Object val = resultSet.getObject(colName); row.put(colName, val); } rows.add(row); } statement.close(); resultSet.close(); connect.close(); return rows; } }
package com.jim.multipos.data.operations; import com.jim.multipos.data.db.model.products.Category; import com.jim.multipos.data.db.model.products.Product; import com.jim.multipos.data.db.model.products.Return; import java.util.Calendar; import java.util.List; import io.reactivex.Observable; import io.reactivex.Single; /** * Created by DEV on 30.08.2017. */ public interface ProductOperations { Observable<Long> addProduct(Product product); Observable<Boolean> addProduct(List<Product> productList); Observable<Long> replaceProduct(Product product); Observable<List<Product>> getAllProducts(); Single<List<Product>> getAllActiveProducts(Category category); Observable<Integer> getAllProductCount(Category category); Observable<Boolean> isProductNameExists(String productName, Long categoryId); Observable<Boolean> removeProduct(Product product); Single<Product> getProductById(Long productId); Single<Boolean> insertReturns(List<Return> returnsList); Single<Boolean> isProductSkuExists(String sku, Long subcategoryId); Single<List<Return>> getReturnList(Calendar fromDate, Calendar toDate); Single<List<Product>> getVendorProductsByVendorId(Long id); Single<Double> getLastCostForProduct(Long productId); }
package com.shoplite.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.shoplite.model.Usuario; import com.shoplite.service.UsuarioService; @RestController @RequestMapping("/user") @CrossOrigin({"*"}) public class UsuarioController { @Autowired UsuarioService userServicio; @PostMapping(value = "/saveUser") public ResponseEntity saveUser(@RequestBody Usuario user) { userServicio.crearUsuarios(user); return ResponseEntity.ok("OK"); } @GetMapping(path="/listUser",produces = "application/json") public List<Usuario> listUser(){ return userServicio.listUsers(); } @GetMapping(path="/buscar/{user},{pass}",produces = "application/json") public Usuario verificarUsuario(String user, String pass) { return userServicio.veficarUser(user, pass); } }
package jp.personal.server.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; import jp.personal.server.enums.Schema; @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataSource { public Schema value(); }
package cn.tarena.ht.mapper; import cn.tarena.ht.pojo.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; /** * Created by 12863 on 2017/7/10. */ public interface UserMapper { List<User> findUserList(); void deleteUser(String[] userIds); void updateUserState(@Param("userIds") String[] userIds,@Param("state") int state); void saveUser(User user); List<Map<String,Object>> findMangerList(String deptId); void saveUserRole(@Param("userId")String userId,@Param("roleId")String roleId); @Delete("delete from role_user_p where AUTH_USER_ID=#{userId}") void deleteUserRole(String userId); public User findUserByN_P(@Param("username")String username,@Param("password")String password); User findUserByname(String username); }
package pl.finapi.paypal.email; import java.io.PrintWriter; import java.io.StringWriter; public class EmailFailureMessage implements EmailMessage { private final byte[] csvFileAsBytes; private final RuntimeException exception; private final String originalFilename; public EmailFailureMessage(byte[] csvFileAsBytes, String originalFilename, RuntimeException exception) { this.csvFileAsBytes = csvFileAsBytes; this.originalFilename = originalFilename; this.exception = exception; } public byte[] getCsvFileAsBytes() { return csvFileAsBytes; } public RuntimeException getException() { return exception; } public String getOriginalFilename() { return originalFilename; } public String getMessage() { if (getException() == null) { return "no exception"; } else { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); getException().printStackTrace(printWriter); return stringWriter.toString(); } } @Override public String getSubject() { return "exception in webapi"; } }
package PreviousVersions; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class TEST_multipleTableFunctions { private Object[] headerLabels; private Object[][] rows; private JFrame frame; public TEST_multipleTableFunctions() { // read the input file try { // read the headerLabels BufferedReader br = new BufferedReader(new FileReader("testValues_assignmentGrades.csv")); headerLabels = br.readLine().split(","); // read the rows into an ArrayList (because its length is flexible) ArrayList<Object[]> rowsAsAdded = new ArrayList<>(); int numRows = 0; String row = br.readLine(); while (row != null){ rowsAsAdded.add(row.split(",")); row = br.readLine(); numRows++; } // now add the rows to the final 2D array of rows (now that you know how many rows there are and can declare the array length) rows = new Object[numRows][]; for (int i = 0; i < numRows; i++) { rows[i] = rowsAsAdded.get(i); } } catch (IOException e) { e.printStackTrace(); } // create JFrame frame = new JFrame("Multiple Panels as Table"); // add the navigation buttons to the frame // frame.getContentPane().add(new NavigationButtonBanner(), BorderLayout.NORTH); // main panel JPanel tablePanel = new JPanel(new GridLayout(rows.length + 1,1)); // add header JPanel headerPanel = new JPanel(new GridLayout(0, headerLabels.length)); for (int i = 0; i < headerLabels.length; i++) { JButton button = new JButton((String) headerLabels[i]); headerPanel.add(button); } tablePanel.add(headerPanel); // add the rest of the buttons for (Object[] row : rows) { JPanel rowPanel = new JPanel(new GridLayout(0, row.length)); for (int i = 0; i < row.length; i++) { JButton cellButton = new JButton((String) row[i]); rowPanel.add(cellButton); } tablePanel.add(rowPanel); } frame.getContentPane().add(tablePanel); // make the JFrame visible JScrollPane scroll = new JScrollPane(tablePanel); frame.getContentPane().add(scroll); // this line adds the table to the frame (you do not need a separate panel) frame.setSize(800, 400); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // make the JFrame appear in the middle of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2); } public static void main(String[] args) { TEST_multipleTableFunctions tmtf = new TEST_multipleTableFunctions(); } }
package edu.buffalo.cse.irf14.analysis; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapitalizationRule extends TokenFilter { private static final Pattern camelAcronymPattern = Pattern.compile("(([A-Z]+[a-z]+|[a-z]+[A-Z]+)[,.!']*[a-z]*|[A-Z]+[\\.,!]*)"); private static final Pattern firstWordPattern = Pattern.compile("(^|([.!?]\\s))(\\w+)"); private static final Pattern properNounsPattern = Pattern.compile("[A-Z][a-z]+"); private static ArrayList<String> noChangesList = new ArrayList<String>(); private boolean isMethodCalled = true; public CapitalizationRule() { super(); } public CapitalizationRule(TokenStream stream) { super(stream); } public ArrayList<String> buildNoChangeTokens (String lines){ ArrayList<String> retainedList = new ArrayList<String>(); Matcher camelAcronymMatcher = camelAcronymPattern.matcher(lines); Matcher firstWordMatcher = firstWordPattern.matcher(lines); while (camelAcronymMatcher.find()){ retainedList.add(camelAcronymMatcher.group().trim()); } /* Remove all the first words from the constructed list of words that * should be retained */ while (firstWordMatcher.find()){ String firstWord = firstWordMatcher.group().replaceAll("[.!?]", "").trim(); if (retainedList.contains(firstWord)){ retainedList.remove(firstWord); } } isMethodCalled = false; return retainedList; } private boolean checkForMerge(String element, String successorWord) { Matcher properNounMatchOne = properNounsPattern.matcher(element); Matcher properNounMatchTwo = properNounsPattern.matcher(successorWord); return (properNounMatchOne.find() && properNounMatchTwo.find()); } @Override public boolean increment() throws TokenizerException { if(!(tokenStream.next() instanceof Token) && !tokenStream.hasNext()) { return false; } /* Build the list of tokens to be preserved ONLY ONCE */ if (isMethodCalled){ noChangesList = buildNoChangeTokens (tokenStream.toString().replaceAll("[\\[\\]]", "").replace(",", "")); } Token token = tokenStream.getCurrent(); if (token != null && Util.isValidString(token.getTermText())){ String element = token.getTermText(); if (!noChangesList.contains(element)){ token.setTermText(element.toLowerCase()); } element = token.getTermText(); if (tokenStream.hasPrevious()){ String precedingWord = tokenStream.getPrevious().getTermText(); boolean mergeRequired = checkForMerge(precedingWord, element); if (mergeRequired){ tokenStream.getPrevious().merge(token); tokenStream.remove(); } } } return true; } }
package com.fhzz.psop.configuration.shiro; import javax.annotation.Resource; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fhzz.psop.entity.Permission; import com.fhzz.psop.entity.Role; import com.fhzz.psop.entity.UserInfo; import com.fhzz.psop.service.UserInfoService; public class MyShiroRealm extends AuthorizingRealm { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private UserInfoService userInfoService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { logger.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal(); for (Role role : userInfo.getRoles()) { authorizationInfo.addRole(role.getRole()); for (Permission p : role.getPermissions()) { authorizationInfo.addStringPermission(p.getPermission()); } } return authorizationInfo; } /* 主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { logger.info("MyShiroRealm.doGetAuthenticationInfo()"); // 获取用户的输入的账号. String username = (String) token.getPrincipal(); logger.info("" + token.getCredentials()); // 通过username从数据库中查找 User对象 // 实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 UserInfo userInfo = userInfoService.findByUsername(username); logger.info("----->>userInfo=" + userInfo); if (userInfo == null) { return null; } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, // 用户名 userInfo.getCustPassword(), // 密码 null, // salt=username+salt getName() // realm name ); return authenticationInfo; } }
package AdventureGame; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Interface extends JFrame { public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 20, L = 1,R = 2, U = 3, D = 4; BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_3BYTE_BGR); Rectangle rect = new Rectangle(20, 40, 15 * 50, 15 * 35); //Color c = new Color(100, 100, 100); public Interface( Player player, Map map2) { AdventureGame.p1.load(); //back = new Background(); //back.load(); AdventureGame.m.load(); StatusBar.load(); this.setBounds(100, 100, WIDTH, HEIGHT); this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent arg0) { if(AdventureGame.inven.draw == false)AdventureGame.p1.move(arg0.getKeyCode()); else AdventureGame.inven.keyprocess(arg0.getKeyCode()); keyproccess(arg0.getKeyCode()); } }); this.setTitle("test"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); this.setResizable(false); new Thread(new ThreadUpadte()).start(); } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) offersetImage.getGraphics(); g2d.setColor(Color.white); g2d.fillRect(0, 0, WIDTH, HEIGHT); g2d.setColor(Color.black); //g2d.drawRect(rect.x, rect.y, rect.width, rect.height); AdventureGame.m.draw(g2d); AdventureGame.p1.draw(g2d); StatusBar.draw(g2d); if(Inventory.draw == true) AdventureGame.inven.drawInventory(g2d); g.drawImage(offersetImage, 0, 0, null); } public static void keyproccess(int keycode) { System.out.println(keycode); switch (keycode) { case KeyEvent.VK_I: if(Inventory.draw == false) Inventory.draw = true; else Inventory.draw = false; break; } System.out.println(); } class ThreadUpadte implements Runnable { public void run() { while (true) { try { Thread.sleep(SLEEPTIME); repaint(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class StatusBar { private static BufferedImage img1; public static void load() { try { img1 = ImageIO.read(new FileInputStream(AdventureGame.reslocation+"Statusbar.bmp")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void draw(Graphics2D g2d) { g2d.setColor(Color.white); g2d.fillRect(0, 500, 800, 600); g2d.setColor(Color.black); g2d.drawImage(img1, 0, 510, null); g2d.drawString(Integer.toString(AdventureGame.p1.getDamage_p()), 50, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getDamage_m()), 130, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getArmor()), 200, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getMagic_resist()), 290, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getHungry()), 360, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getThirsty()), 440, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getGold()), 520, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getX()), 600, 530); g2d.drawString(Integer.toString(AdventureGame.p1.getY()), 630, 530); g2d.drawRect(50, 600-50, 800-100, 15); g2d.drawRect(50, 600-50+20, 800-100, 15); //HP g2d.setColor(Color.red); g2d.fillRect(51, 600-50+1, (int)((AdventureGame.p1.getCurHP()+0.00)/AdventureGame.p1.getMaxHP()*(800-100)-1), 14); g2d.setColor(Color.black); g2d.drawString(Integer.toString(AdventureGame.p1.getCurHP())+"/"+Integer.toString(AdventureGame.p1.getMaxHP()),800/2-20,565); //MP g2d.setColor(Color.blue); g2d.fillRect(51, 600-50+20+1, (int)((AdventureGame.p1.getCurMP()+0.00)/AdventureGame.p1.getMaxMP()*(800-100)-1), 14); g2d.setColor(Color.black); g2d.drawString(Integer.toString(AdventureGame.p1.getCurMP())+"/"+Integer.toString(AdventureGame.p1.getMaxMP()),800/2-20,585); } } /* class Background { BufferedImage Grass; BufferedImage Wall; public void load() { try { Grass = ImageIO.read(new FileInputStream("src/AdventureGame/Grass.bmp")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Wall = ImageIO.read(new FileInputStream("src/AdventureGame/Wall.bmp")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void draw(Graphics2D g2d,int[][] map) { for(int i = 0;i < 20; i++) for(int i2 = 0;i2 < 20; i2++) { switch(map[i][i2]) { case 0: g2d.drawImage(Wall, i*45, i2*45, null); break; case 1: g2d.drawImage(Grass, i*45, i2*45, null); break; } } } } */
package com.tencent.mm.plugin.wallet.balance.ui; import com.tencent.mm.plugin.mmsight.segment.FFmpegMetadataRetriever; import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceManagerUI.3; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n.c; import org.json.JSONArray; import org.json.JSONObject; class WalletBalanceManagerUI$3$1 implements c { final /* synthetic */ 3 paA; WalletBalanceManagerUI$3$1(3 3) { this.paA = 3; } public final void a(l lVar) { JSONArray optJSONArray = this.paA.paz.optJSONArray("balance_menu_item"); if (optJSONArray != null && optJSONArray.length() > 0) { for (int i = 0; i < optJSONArray.length(); i++) { JSONObject optJSONObject = optJSONArray.optJSONObject(i); if (optJSONObject != null) { WalletBalanceManagerUI$a walletBalanceManagerUI$a = new WalletBalanceManagerUI$a(); walletBalanceManagerUI$a.title = optJSONObject.optString(FFmpegMetadataRetriever.METADATA_KEY_TITLE); walletBalanceManagerUI$a.paB = optJSONObject.optInt("jump_type", 0); walletBalanceManagerUI$a.paC = optJSONObject.optString("jump_h5_url"); walletBalanceManagerUI$a.paD = optJSONObject.optString("tinyapp_username"); walletBalanceManagerUI$a.paE = optJSONObject.optString("tinyapp_path"); lVar.add(0, i, 0, walletBalanceManagerUI$a.title); this.paA.jLK.add(walletBalanceManagerUI$a); } } } } }
/** * S1. https://programmers.co.kr/learn/courses/30/lessons/43163 */ import java.util.*; class Solution { class Word { int depth; String word; public Word(String word, int depth) { this.word = word; this.depth = depth; } } public int solution(String begin, String target, String[] words) { Queue<Word> queue = new LinkedList<>(); boolean[] visited = new boolean[words.length]; queue.offer(new Word(begin, 0)); while(!queue.isEmpty()) { Word curr = queue.poll(); for (int i = 0; i < words.length; ++i) { if (visited[i]) continue; // 이미 큐에 넣은 상태면 pass int diff = 0; String word = words[i]; for (int j = 0; j < word.length(); ++j) { if (curr.word.charAt(j) != word.charAt(j)) ++diff; } if (diff > 1) continue; // 두 개이상의 알파벳이 바뀐 단어이면 pass if (word.equals(target)) return curr.depth + 1; queue.offer(new Word(word, curr.depth + 1)); visited[i] = true; } } return 0; } } /** * S2. LinkedList로 구현 */ import java.util.*; class Solution { class Node { String next; int edge; public Node(String next, int edge) { this.next = next; this.edge = edge; } } public int solution(String begin, String target, String[] words) { Queue<Node> q = new LinkedList<>(); boolean[] visited = new boolean[words.length]; q.offer(new Node(begin, 0)); while(!q.isEmpty()) { Node cur = q.poll(); if (cur.next.equals(target)) { // 현재 노드가 target이면, 이 노드의 edge를 반환한다. return cur.edge; } for (int i = 0; i < words.length; ++i) { // 방문한 적이 없고 1개의 알파벳만 바뀐 단어만 큐에 넣는다. if(!visited[i] && isValid(cur.next, words[i])) { visited[i] = true; q.offer(new Node(words[i], cur.edge + 1)); } } } return 0; } public boolean isValid(String cur, String word) { int count = 0; for(int i = 0; i < word.length(); ++i) { if (cur.charAt(i) != word.charAt(i)) { count ++; } } return count > 1; } }
package com.tencent.mm.api; import com.tencent.mm.ac.a.c; import com.tencent.mm.kernel.c.a; public interface f extends a { c ak(long j); }
package Tester; import static org.junit.Assert.*; import Implementations.PolynomialImp; import Interfaces.Polynomial; import org.junit.Before; import org.junit.Test; public class Test1 { private static final double EPSILON = 0.0001; private Polynomial P1; private Polynomial P2; @Before public void setUp() throws Exception { P1 = new PolynomialImp("8x^2+1"); P2 = new PolynomialImp("4x^2+2"); } @Test public void testAdd() { Polynomial P3 = P1.add(P2); Polynomial P4 = new PolynomialImp("12x^2+3"); System.out.printf("Add-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testSubtract() { Polynomial P3 = P1.subtract(P2); Polynomial P4 = new PolynomialImp("4x^2+-1"); System.out.printf("Subtract-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testMultiplyPolynomial() { Polynomial P3 = P1.multiply(P2); Polynomial P4 = new PolynomialImp("32x^4+20x^2+2"); System.out.printf("Multiply-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testDerivative() { Polynomial P3 = P1.derivative(); Polynomial P4 = new PolynomialImp("16x"); System.out.printf("Derivative-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testIndefiniteIntegral() { Polynomial P3 = P2.indefiniteIntegral(); double c1 = 4/3.0; String strP4 = c1 + "x^3+2x+1"; Polynomial P4 = new PolynomialImp(strP4); System.out.printf("Indefinite Integral-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testDefiniteIntegral() { double number1 = P1.definiteIntegral(2, 4); double number2 = 151.333333; System.out.printf("Definite Integral-> number1: %f, number2: %f\n", number1, number2); double delta = number1 - number2; assertTrue(delta < EPSILON); } @Test public void testDegree() { int number1 = P1.degree(); int number2 = 2; System.out.printf("Degree -> number1: %d, number2: %d\n", number1, number2); assertTrue(number1 == number2); } @Test public void testEvaluate() { double number1 = P1.evaluate(3); double number2 = 73.0; System.out.printf("Evaluate-> number1: %f, number2: %f\n", number1, number2); double delta = Math.abs(number1 - number2); assertTrue(delta < EPSILON); } @Test public void testMultiplyDouble() { Polynomial P3 = P1.multiply(2); Polynomial P4 = new PolynomialImp("16x^2+2"); System.out.printf("Multiply-> P3: %s, P4: %s\n", P3, P4); assertTrue(P3.equals(P4)); } @Test public void testToString() { String string1 = P1.toString(); String string2 = "8.00x^2+1.00"; System.out.printf("toString-> string1: %s, string2: %s\n", string1, string2); assertTrue(string1.equals(string2)); } }
package com.mysql.cj.protocol; import com.mysql.cj.MysqlConnection; import com.mysql.cj.Query; import com.mysql.cj.Session; public interface ResultsetRowsOwner { void closeOwner(boolean paramBoolean); MysqlConnection getConnection(); Session getSession(); Object getSyncMutex(); String getPointOfOrigin(); int getOwnerFetchSize(); Query getOwningQuery(); int getOwningStatementMaxRows(); int getOwningStatementFetchSize(); long getOwningStatementServerId(); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\ResultsetRowsOwner.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package webprotocol; import com.google.gson.annotations.SerializedName; import lombok.*; @Builder @AllArgsConstructor @Getter @Setter @ToString public class UserTask { @SerializedName("userId") private int userId; @SerializedName("id") private int id; @SerializedName("title") private String title; @SerializedName("completed") private boolean completed; }
package cn.leo.produce.decode; /** * @description: zxing view result back * @author: fanrunqi * @date: 2019/4/16 15:50 */ public interface ResultCallBack { void onResult(String result); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IServiceSupport; import com.douwe.generic.dao.DataAccessException; import java.util.List; import lappa.smsbanking.Entities.Agence; /** * * @author lappa */ public interface IServiceAgence { public Agence findByIdA(Long id) throws DataAccessException; public Agence findByNomAgence(String nomAgence) throws DataAccessException; public Agence findByCodeAgence(String codeAgence) throws DataAccessException; public void save(Agence c) throws DataAccessException; public void delete(Long id) throws DataAccessException; public void update(Agence c) throws DataAccessException; public List<Agence> findAll() throws DataAccessException; public Agence findById(Long id) throws DataAccessException; }
// Completely Reliable User Development API package com.nicjames2378.IEClocheCompat.CRUD; import blusunrize.immersiveengineering.api.tool.BelljarHandler; import com.nicjames2378.IEClocheCompat.CRUD.formats.CropFormat; import com.nicjames2378.IEClocheCompat.CRUD.formats.FertilizerFormat; import com.nicjames2378.IEClocheCompat.Main; import com.nicjames2378.IEClocheCompat.utils.ConversionUtils; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; public class IEClocheCompat { public static boolean registerCrop(ItemStack seed, ItemStack[] output, ItemStack soil, Block crop, boolean condition) { if (condition) { try { BelljarHandler.cropHandler.register(seed, output, soil, crop.getDefaultState()); Main.log.info(String.format("Registering seed '%1$s', with output '%2$s', with soil '%3$s', with crop '%4$s'", seed.getItem().getRegistryName(), ConversionUtils.ItemStackArrayToString(output), soil.getItem().getRegistryName(), crop.getRegistryName())); Main.log.info("-------------------------------"); return true; } catch (Exception e) { Main.log.error(String.format("Error registering crop for seed '%1$s'. Skipping!", seed.toString())); Main.log.error(e); return false; } } return false; } public static boolean registerCrop(CropFormat newCrop) { ItemStack seed = newCrop.getSeed(); ItemStack[] output = newCrop.getOutputs(); ItemStack soil = newCrop.getSoil(); Block crop = newCrop.getCrop(); boolean condition = newCrop.isConditionValid(); return IEClocheCompat.registerCrop(seed, output, soil, crop, condition); } public static boolean[] registerAllCrops(CropFormat[] newCrops) { boolean[] results = new boolean[newCrops.length]; int current = 0; for (CropFormat newCrop : newCrops) { results[current] = registerCrop(newCrop); } return results; } public static boolean registerFertilizer(ItemStack fertilizer, float growthMultiplier, boolean condition) { if (condition) { try { BelljarHandler.registerBasicItemFertilizer(fertilizer, growthMultiplier); Main.log.info(String.format("Registering fertilizer '%1$s', with growth multiplier of '%2$s'", fertilizer.getItem().getRegistryName(), growthMultiplier)); Main.log.info("-------------------------------"); return true; } catch (Exception e) { Main.log.error(String.format("Error registering fertilizer '%1$s'. Skipping!", fertilizer.getItem().getRegistryName())); Main.log.error(e); return false; } } return false; } public static boolean registerFertilizer(FertilizerFormat newFertilizer) { ItemStack fertilizer = newFertilizer.getFertilizer(); float growthMultiplier = newFertilizer.getGrowthMultiplier(); boolean condition = newFertilizer.isConditionValid(); return IEClocheCompat.registerFertilizer(fertilizer, growthMultiplier, condition); } public static boolean[] registerAllFertilizers(FertilizerFormat[] newFertilizers) { boolean[] results = new boolean[newFertilizers.length]; int current = 0; for (FertilizerFormat newFertilizer : newFertilizers) { results[current] = registerFertilizer(newFertilizer); } return results; } }
package net.fusionlord.mods.betterwolfcontrol.client.proxy; import net.fusionlord.mods.betterwolfcontrol.client.events.EventOnMouse; import net.fusionlord.mods.betterwolfcontrol.client.rendering.model.entity.RenderLayerWolf; import net.fusionlord.mods.betterwolfcontrol.client.rendering.model.item.ItemColorWhistle; import net.fusionlord.mods.betterwolfcontrol.client.rendering.model.tile.TileEntitySpecialRenderDogBowl; import net.fusionlord.mods.betterwolfcontrol.common.config.Reference; import net.fusionlord.mods.betterwolfcontrol.common.enums.Group; import net.fusionlord.mods.betterwolfcontrol.common.init.ModBlocks; import net.fusionlord.mods.betterwolfcontrol.common.init.ModItems; import net.fusionlord.mods.betterwolfcontrol.common.proxy.CommonProxy; import net.fusionlord.mods.betterwolfcontrol.common.tile.TileEntityDogBowl; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.RenderItem; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderWolf; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.item.Item; import net.minecraft.world.World; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * Created by FusionLord on 4/2/2018. */ @Mod.EventBusSubscriber(modid = Reference.MODID, value = {Side.CLIENT}) public class ClientProxy extends CommonProxy { @SubscribeEvent public static void registerModels(ModelRegistryEvent event) { for (Group group : Group.VALUES) { Item item = Item.getItemFromBlock(ModBlocks.DOGBOWL); ModelResourceLocation mrl = new ModelResourceLocation(item.getRegistryName(), "group=".concat(group.getName())); ModelLoader.setCustomModelResourceLocation(item, group.ordinal(), mrl); } } @Override public void preInit(FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init(FMLInitializationEvent event) { super.init(event); Minecraft.getMinecraft().getItemColors().registerItemColorHandler(new ItemColorWhistle(), ModItems.WHISTLE); MinecraftForge.EVENT_BUS.register(new EventOnMouse()); Render<EntityWolf> wolfRender = Minecraft.getMinecraft().getRenderManager().getEntityClassRenderObject(EntityWolf.class); if (wolfRender instanceof RenderWolf) ((RenderWolf) wolfRender).addLayer(new RenderLayerWolf()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityDogBowl.class, new TileEntitySpecialRenderDogBowl()); } @Override public void postInit(FMLPostInitializationEvent event) { super.postInit(event); } @Override public World getWorld(int dim) { return Minecraft.getMinecraft().world; } @Override public Side getSide() { return Side.CLIENT; } }
package com.tencent.mm.sandbox.updater; import com.tencent.mm.sdk.platformtools.x; class f$2 implements Runnable { final /* synthetic */ f sEk; final /* synthetic */ long sEl; f$2(f fVar, long j) { this.sEk = fVar; this.sEl = j; } public final void run() { x.d("MicroMsg.TrafficStatistic", "onUpstreamTraffic upstream : %s", new Object[]{Long.valueOf(this.sEl)}); f.a(this.sEk, f.a(this.sEk) + Math.max(0, this.sEl)); f.a(this.sEk, false); } }
package com.simontuffs.onejar.guice.test; import junit.framework.TestCase; import com.simontuffs.onejar.test.Invoker; import com.simontuffs.onejar.test.Invoker.Result; public class SelfTestEclipseGuice extends TestCase { protected static Object test; public void testEclipseGuice() throws Exception { Result result = Invoker.run("java -jar build/test-eclipse-guice.jar"); System.out.println(result.toString()); assertTrue("Expected pass did not occur: " + result, result.status == 0); } }
package top.wangruns.nowcoder.sword2offer; import java.util.Comparator; import java.util.PriorityQueue; /** * 题目描述 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 * */ public class P63_数据流中的中位数 { int count=0; PriorityQueue<Integer> minHeap=new PriorityQueue<Integer>(); PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(11,new Comparator<Integer>(){ public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); public void Insert(Integer num) { count++; //判定奇偶的高效写法,如果当前个数为偶数,插入最小堆(需要保证,最大推堆顶小于,小于最小堆堆顶) if((count&1)==0){ if(!maxHeap.isEmpty()&&num<maxHeap.peek()){ maxHeap.offer(num); num=maxHeap.poll(); } minHeap.offer(num);//插入最小堆 } //如果当前个数为奇数,插入最大堆(需要保证,最大推堆顶小于,小于最小堆堆顶) else{ if(!minHeap.isEmpty()&&num>minHeap.peek()){ minHeap.offer(num); num=minHeap.poll(); } maxHeap.offer(num);//插入最大堆 } } public Double GetMedian() { double res=0; //没有任何数 if(count==0) return res; //总数为奇数,那么最大堆的堆顶就是中位数 else if((count&1)==1) res= maxHeap.peek(); //如果为偶数,那么最小堆的堆顶 和 最大堆的堆顶之和/2就是中位数 else res= (minHeap.peek()+maxHeap.peek())/2.0; return res; } }
/* * 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 webshop.controller; import java.util.ArrayList; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import javax.persistence.Query; import webshop.model.Customer; import webshop.model.ICustomer; /** * * @author Nizam */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Stateless @LocalBean public class CustomerFacade { @PersistenceContext(unitName = "APGWebShopPU") private EntityManager em; public ICustomer register(String userName, String password) { Customer customer = new Customer(userName, password); em.persist(customer); return customer; } public boolean alreadyRegisterd(String userName) { Customer customer = em.find(Customer.class, userName); if (customer == null) { return false; } return true; } public ICustomer find(String userName, String password) { try { ICustomer found = em.find(Customer.class, userName); return found; } catch (Exception ex) { return null; } } public Customer findByName(String userName) { Customer found = em.find(Customer.class, userName); return found; } public void logout(String userName, String password) { } public List<Customer> getCustomers() { Query query = em.createQuery("SELECT x FROM Customer x"); List<Customer> ret = query.getResultList(); if (ret == null) { return new ArrayList<Customer>(); } else { return ret; } } public void updateCustomer(Customer acc) { em.merge(acc); } }
package Java_io; import java.io.File; public class io_test1 { /* * java.io.File类 * 1.方式与输入输出相关的类,接口等都定义在java.io包下 * 2.File是一个类,可以有构造器创建其对象。此对象对应着一个文件属性。 * 3.File类对象与平台无关. * 4.File中的方法,仅涉及到如何创建,删除,重命名等等, * 只要涉及文件内容的,File类无能为力,只能通过IO流来完成. * 5.File类的对象常作为IO流的具体类的构造器的形参。 */ /* 路径. * 绝对路径:包含盘符的完整的文件路径. * 相对路径:在当前文件目录下的文件的路径. * */ public static void main(String[] args) { File file1 = new File("d:\\io\\hellworld.txt"); File file2 = new File("hello.txt"); File file3 = new File("d:/io/io1"); } }
package com.toshevski.android.shows.activities; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.toshevski.android.shows.adapters.SearchAdapter; import com.toshevski.android.shows.databases.MyData; import com.toshevski.android.shows.pojos.Keys; import com.toshevski.android.shows.pojos.Series; import com.toshevski.android.shows.animations.ProgressBarAnimation; import com.toshevski.android.shows.R; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class Search extends AppCompatActivity { private ArrayList<Series> series; private ListView listview; private SearchAdapter adapter; private TextView nothingFoundText; private ProgressBar pb; private ProgressBarAnimation progressAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_layout); series = new ArrayList<>(); nothingFoundText = (TextView) findViewById(R.id.nothingFound); listview = (ListView) findViewById(R.id.searchList); adapter = new SearchAdapter(getApplicationContext(), series); listview.setAdapter(adapter); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Series s = series.get(position); s.setSelected(!s.isSelected()); adapter.notifyDataSetChanged(); } }); handleIntent(getIntent()); pb = (ProgressBar) findViewById(R.id.progressBar); pb.setProgressDrawable(ContextCompat.getDrawable(this, R.drawable.custom_progressbar)); } private void reDraw() { if (adapter.getCount() == 0) { listview.setVisibility(View.INVISIBLE); nothingFoundText.setVisibility(View.VISIBLE); } else { listview.setVisibility(View.VISIBLE); nothingFoundText.setVisibility(View.GONE); } } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.search_menu, menu); return true; } private void fixSeries(Series s) { s.selected = false; try { FileOutputStream fos = new FileOutputStream(new File(getFilesDir(), s.getImdb() + ".jpg")); Bitmap bm = ((BitmapDrawable) s.getImage()).getBitmap(); bm.compress(Bitmap.CompressFormat.JPEG, this.getResources().getInteger(R.integer.image_quality), fos); fos.close(); s.setStatus(Series.ImageStatus.DOWN); s.setImage(null); } catch (Exception e) { Log.i("MainActivity.fixSeries:", "Greshki"); e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = new Intent(getApplicationContext(), MySeries.class); switch (item.getItemId()) { case R.id.addSeries: for (Series s : series) if (s.isSelected()) { fixSeries(s); MyData.add(s); } MyData.isDirty = true; i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //i.putExtra("series", as); setResult(Activity.RESULT_OK, i); Log.i("Search.addSeries:", "TREBA DA SE VRATI NA POCHETNA! " + MyData.howManySeries()); startActivity(i); break; case android.R.id.home: //selected.clear(); setResult(Activity.RESULT_CANCELED, i); finish(); break; } return true; } @Override protected void onResume() { super.onResume(); } @Override protected void onNewIntent(Intent intent) { handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); this.setTitle(query); if (this.getSupportActionBar() != null) this.getSupportActionBar().setSubtitle(R.string.search_query); Log.i("L3FT.srch.handleIntent:", query); String link2 = Keys.searchLinkBeforeName + query + Keys.searchLinkAfterName; new GetData().execute(link2.replace(" ", "%20")); } } // AsyncTask class GetData extends AsyncTask<String, Void, Void> { private String line; private int howMany = 0; private int howManyPassed = 0; private Series newToAdd; protected Void doInBackground(String... params) { try { URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", Keys.contentType); connection.setRequestProperty("trakt-api-version", Keys.apiVersion); connection.setRequestProperty("trakt-api-key", Keys.apiKey); connection.setDoInput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); line = rd.readLine(); JsonToJava(line); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { } @Override protected void onPostExecute(Void aVoid) { adapter.notifyDataSetChanged(); pb.setVisibility(View.INVISIBLE); reDraw(); } @Override protected void onProgressUpdate(Void... values) { progressAnimation = new ProgressBarAnimation(pb, pb.getProgress(), (int)(100 * (double) howManyPassed / howMany)); progressAnimation.setDuration(500); pb.startAnimation(progressAnimation); series.add(newToAdd); adapter.notifyDataSetChanged(); } // Inner Methods private void JsonToJava(String line) { try { JSONArray array = new JSONArray(line); howMany = array.length(); for (int i = 0; i < array.length(); ++i) { howManyPassed = i + 1; JSONObject object = array.getJSONObject(i); JSONObject show = object.getJSONObject("show"); double rating = object.getDouble("score"); String title = show.getString("title"); int year = -1; if (show.has("year") && !show.isNull("year")) year = show.getInt("year"); if (year == -1) continue; JSONObject poster = show.getJSONObject("images").getJSONObject("poster"); String imageName = "x"; if (poster.has("thumb") && !poster.isNull("thumb")) imageName = poster.getString("thumb"); if (imageName.equals("x")) continue; JSONObject ids = show.getJSONObject("ids"); String imdb; if (!ids.isNull("imdb")) imdb = ids.getString("imdb"); else continue; if (imdb == null || imdb.length() < 3 || imdb.equals("null")) continue; String overview = ""; if (show.has("overview")) overview = show.getString("overview"); Drawable drw = null; if (imageName != null) drw = getImage(imageName); newToAdd = new Series(title, year, imdb, overview, rating, "", imageName, Series.ImageStatus.ONLINE); newToAdd.setFilesDir(getFilesDir()); if (drw != null) newToAdd.setImage(drw); else newToAdd.setStatus(Series.ImageStatus.NO); Log.i("JSON:", title); publishProgress(); } } catch (Exception e) { e.printStackTrace(); } } private Drawable getImage(String line) { try { Log.i("L3FT.search.getImage:", line); URL url = new URL(line); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); InputStream is = connection.getInputStream(); return Drawable.createFromStream(is, null); } catch (Exception e) { e.printStackTrace(); return null; } } } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class FileWriterExample { public static void main(String[] args) { FileWriter fw ; FileReader fr; Scanner scanner = new Scanner(System.in); BufferedWriter bw = null; BufferedReader br = null; int n = scanner.nextInt(); //String content = "Hi"; long[] numbers = new long[n]; for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } try{ fw = new FileWriter("C:/Users/S525074/Desktop/coursera/data.txt"); bw = new BufferedWriter(fw); //br.write(content); PrintWriter pr = new PrintWriter(bw); for (int i=0; i< numbers.length; i++){ pr.println(String.valueOf(numbers[i])); } }catch(IOException ex){ System.out.println(ex); } try { fr = new FileReader("C:/Users/S525074/Desktop/coursera/data.txt"); br = new BufferedReader(fr); while (br.read()!= -1){ for(int i=0; i<numbers.length;i++){ numbers[i] = br.read(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } }//end if scanner.close(); }//end finally } }
package com.spark.others; import java.io.Serializable; import java.util.Arrays; import java.util.List; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.api.java.function.VoidFunction; import scala.Tuple2; /** * 所谓二次排序,就是自定义key类,然后自己实现compareTo方法, * 这个key, 可以设置多个属性,先按照,第一个属性比,然后在按照第二个属性比, * * * @author ZORO * */ public class SecondSortMy { public static void main(String[] args) { SparkConf conf = new SparkConf(); conf.setMaster("local").setAppName("secondSort"); JavaSparkContext jsc = new JavaSparkContext(conf); List<Tuple2<String, Integer>> asList = Arrays.asList(new Tuple2<String, Integer>("apple", 23), new Tuple2<String, Integer>("apple", 12), new Tuple2<String, Integer>("hive", 12), new Tuple2<String, Integer>("banaan", 10), new Tuple2<String, Integer>("hive", 3)); JavaRDD<Tuple2<String, Integer>> fruiltPriceRDD = jsc.parallelize(asList); /** * (apple,12) * (apple,23) * (banaan,10) * (hive,3) * (hive,12) */ fruiltPriceRDD.mapToPair(new PairFunction<Tuple2<String, Integer>, FruiltPrice, Tuple2<String, Integer>>() { private static final long serialVersionUID = 1L; @Override public Tuple2<FruiltPrice, Tuple2<String, Integer>> call(Tuple2<String, Integer> t) throws Exception { FruiltPrice key = new FruiltPrice(t._1, t._2); return new Tuple2<SecondSortMy.FruiltPrice, Tuple2<String, Integer>>(key, t); } }).sortByKey().foreach(new VoidFunction<Tuple2<FruiltPrice, Tuple2<String, Integer>>>() { private static final long serialVersionUID = 1L; @Override public void call(Tuple2<FruiltPrice, Tuple2<String, Integer>> t) throws Exception { System.out.println(t._2); } }); jsc.stop(); } /** * 自定义二次排序类 * * @author ZORO * */ static class FruiltPrice implements Serializable, Comparable<FruiltPrice> { private static final long serialVersionUID = 1L; private String fruilt; private Integer price; public String getFruilt() { return fruilt; } public FruiltPrice() { super(); } public FruiltPrice(String fruilt, Integer price) { this.fruilt = fruilt; this.price = price; } public void setFruilt(String fruilt) { this.fruilt = fruilt; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } /** * 自己设置排序规则,先按照第一个字段比较,相同在按照第二个字段比较 */ @Override public int compareTo(FruiltPrice o) { int compareToFruilt = this.getFruilt().compareTo(o.getFruilt()); if (compareToFruilt != 0) { return compareToFruilt; } return this.getPrice().compareTo(o.getPrice()); } } }
import java.util.ArrayList; import java.util.List; public class Billing { // Create a method that asks for the user's input: public static void processOrder(String order) { float total = 0f; float milk = 0.53f; float sugar = 0.17f; float cream = 0.73f; float sprinkles = 0.29f; float xigua = 1.03f; float itemPrice = 0f; float amount = 0f; // Split the original order up into different item orders String[] items = order.split(", "); //for each item, split the string into an array for (String item : items) { String[] words = item.split(" "); // Set the number of drinks/items amount = Float.valueOf(words[0]); switch (words[2].toLowerCase()) { // Find the type of drink or item case "regular": RegularCoffee regular = new RegularCoffee(); itemPrice = regular.getCost(); break; case "decaf": DecafCoffee decaf = new DecafCoffee(); itemPrice = decaf.getCost(); break; case "xigua": itemPrice = xigua; break; } // If there are additional items to add, find them and add to running total (itemPrice) if(words.length > 2) { for (int i = 4; i < words.length; i += 2) { switch (words[i].toLowerCase()) { case "milk": itemPrice += milk; break; case "sugar": itemPrice += sugar; break; case "cream": itemPrice = itemPrice + cream; break; case "sprinkles": itemPrice = itemPrice + sprinkles; break; } } } // Calculate price for each type of item and add to total total = total + (amount * itemPrice); } // Return total price System.out.printf("Final bill is $" + "%1.2f", total); } }
package com.example.metrics; /** * Gauges: an instantaneous measurement of a discrete value. * <p> * Counters: a value that can be incremented and decremented. Can be used in queues to monitorize * the remaining number of pending jobs. * <p> * Meters: measure the rate of events over time. You can specify the rate unit, the scope of events * or event type. * <p> * Histograms: measure the statistical distribution of values in a stream of data. * <p> * Timers: measure the amount of time it takes to execute a piece of code and the distribution of * its duration. * <p> * Healthy checks: as his name suggests, it centralize our service’s healthy checks of external * systems. * <p> * Gauges: 用于瞬时值的测量,比如采集某集合内的元素个数 * <p> * Counters: 计数器 * <p> * Meters:单位时间内事件发生的速率,比如TPS * <p> * Histograms:Histogram统计数据流量的分布情况。比如最小值,最大值,中间值,还有中位数,75百分位, 90百分位, 95百分位, 98百分位, 99百分位, 和 * 99.9百分位的值(percentiles)。 * <p> * Timers:其实是 Histogram 和 Meter 的结合, histogram 某部分代码/调用的耗时, meter统计TPS。 * <p> * Healthy checks: */ public class Main { public static void main(String[] args) { } }
package cs3500.animator.view; import cs3500.animator.model.featurestate.FeatureState; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; /** * This class represents a JPanel that will be used in the VisualView class of an animation. This * class represents one frame in an animation to be displayed to the JFrame class it is part of. */ public class AnimationPanel extends JPanel { List<FeatureState> currentFrame; /** * This constructor builds an AnimationPanel based on its height and width. * * @param width the width * @param height the height */ public AnimationPanel(int width, int height) { super(); this.currentFrame = new ArrayList<>(); this.setPreferredSize(new Dimension(width, height)); this.setBackground(Color.WHITE); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; DrawingStrategy drawingStrategy; for (FeatureState shape : currentFrame) { drawingStrategy = shape.getDrawingStrategy(); drawingStrategy .draw(g2d, (int) shape.getXDimension(), (int) shape.getYDimension(), shape.getLocation(), shape.getColor()); } } /** * This method sets the List of FeatureState to the next frame. * * @param next the next list of FeatureState to be displayed */ public void setListOfFeatureStates(List<FeatureState> next) { this.currentFrame = next; } }
package com.shopping.models; public class addr { private int cid; private String city; private int area; public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getArea() { return area; } public void setArea(int area) { this.area = area; } @Override public String toString() { return "addr [cid=" + cid + ", city=" + city + ", area=" + area + "]"; } }
package model.Shark; import javafx.scene.image.Image; import model.Board; import model.Enums.PieceType; import model.Enums.StatusType; import model.Status; import model.Tile; import model.interfaces.Piece; import java.io.Serializable; import java.util.Set; public abstract class SharkDecorator implements Piece, Serializable { protected Piece decoratedShark; public SharkDecorator(Piece decoratedShark) { this.decoratedShark = decoratedShark; } @Override public Set<Tile> getValidMoves(Tile currentCoord, int movement, Board board) { return decoratedShark.getValidMoves(currentCoord, movement, board); } @Override public Set<Tile> getValidAttacks(Tile currentCoord, Board board) { return decoratedShark.getValidAttacks(currentCoord, board); } @Override public Set<Tile> calcValidSpecials(Tile currentCoord, Board board) { return decoratedShark.calcValidSpecials(currentCoord, board); } @Override public void move(Tile tile, Board board) { getTile().removePiece(); tile.setPiece(this); } @Override public void attack(Tile tile) { decoratedShark.attack(tile); } @Override public void special(Tile tile, Board board) { decoratedShark.special(tile, board); } @Override public void takeDamage() { decoratedShark.takeDamage(); } @Override public void die() { decoratedShark.die(); } @Override public void setStatus(StatusType type, int duration) { decoratedShark.setStatus(type, duration); } @Override public void removeStatus(StatusType status) { decoratedShark.removeStatus(status); } @Override public Status getStatus(StatusType type) { return decoratedShark.getStatus(type); } @Override public PieceType getPieceType() { return decoratedShark.getPieceType(); } @Override public Image getSprite() { return decoratedShark.getSprite(); } @Override public Tile getTile() { return decoratedShark.getTile(); } @Override public int getHealth() { return decoratedShark.getHealth(); } @Override public void setTile(Tile tile) { decoratedShark.setTile(tile); } @Override public void setSprite(Image sprite) { decoratedShark.setSprite(sprite); } @Override public int getBaseMovement() { return decoratedShark.getBaseMovement(); } @Override public void setBaseMovement(int baseMovement) { decoratedShark.setBaseMovement(baseMovement); } @Override public void setHealth(int health) { decoratedShark.setHealth(health); } @Override public Set<Tile> getValidSpecials() { return decoratedShark.getValidSpecials(); } @Override public void setValidSpecials(Set<Tile> validSpecials) { decoratedShark.setValidSpecials(validSpecials); } }
package com.example.demo.controller; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.example.demo.form.PersonForm; import com.example.demo.model.Person; /** @controller: bản chất là đăng ký nhận Event từ client (vd: http event, STOMP event với websocket) @RequestMapping(): là đăng ký nhận Event từ Http request */ @Controller public class HttpResponseHeaderController { @RequestMapping(value = "/responseHeader", method = RequestMethod.GET) // @ResponseBody void: ko trả ve giá trị => dùng HttpServletResponse để trả về giá trị public @ResponseBody String generateReport( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = ((HttpServletRequest)request).getRequestURI().toString(); System.out.println("***** uri: " + uri); //====================================================================== // add Cookies to response Header //====================================================================== Cookie myCookie = new Cookie("testCookies", "ABCDEFFFFFF"); myCookie.setHttpOnly(true); //javaScript can not get this cookies from source code myCookie.setSecure(false); //true: browser must send with https instead of http myCookie.setMaxAge(24*60*60); //second: 24h* 60m *60s myCookie.setPath("/"); //uri: all subdirectory of this path is availabe to send this cookies // myCookie.setDomain(".dichly.com"); // sub domain can not use this cookies response.addCookie(myCookie); //====================================================================== // add fields to header //====================================================================== // Set refresh, autoload time as 5 seconds // response.setIntHeader("Refresh",5);// “Refresh” attribute trong http response header. response.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // 1 week in future response.setHeader("Cache-Control","max-age=3600"); response.setStatus(200);// status Code in Header response return "please, check response Header and Chrome Dev mode"; } }
package se.jaitco.queueticketapi.service; import org.junit.Assert; import org.junit.Test; import se.jaitco.queueticketapi.model.User; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; public class UserServiceTest { private final UserService classUnderTest = new UserService(); @Test public void testGetUser() { Optional<User> user = classUnderTest.getUser("Aschan"); Assert.assertThat(user.isPresent(), is(true)); } }
package boj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BOJ_1759_암호만들기 { private static int R; private static int N; private static char[] arr; private static char[] result; private static String operator ="aeiou"; private static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); R = Integer.parseInt(st.nextToken()); N = Integer.parseInt(st.nextToken()); arr = new char[N]; result = new char[R]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) { arr[i] = st.nextToken().charAt(0); } Arrays.sort(arr); nCr(0,0); System.out.println(sb); } public static void nCr(int r, int k) { if(r == R) { if(check()) { for (int i = 0; i < result.length; i++) { sb.append(result[i]); } sb.append("\n"); } return; } for (int i = k; i < arr.length; i++) { result[r] = arr[i]; nCr(r+1,i+1); } } public static boolean check() { int m=0; int c=0; for (int i = 0; i < result.length; i++) { if(operator.indexOf(result[i]) >=0) { m++; }else { c++; } } if(m>=1 && c>=2) return true; else return false; } }
class Solution { public int solution(int[] money) { int answer = 0; int size = money.length; if (size == 3) { for (int i=0; i<3; i++) { answer = Math.max(answer, money[i]); } return answer; } int[] dpIncludeFirst = new int[size]; int[] dpExcludeFirst = new int[size]; dpIncludeFirst[0] = money[0]; dpIncludeFirst[1] = Math.max(money[0], money[1]); dpExcludeFirst[0] = 0; dpExcludeFirst[1] = money[1]; for (int i=2; i<size; i++) { dpExcludeFirst[i] = Math.max(dpExcludeFirst[i-1], dpExcludeFirst[i-2] + money[i]); answer = Math.max(answer, dpExcludeFirst[i]); if (i == size-1){ break; } dpIncludeFirst[i] = Math.max(dpIncludeFirst[i-1], dpIncludeFirst[i-2] + money[i]); answer = Math.max(answer, dpIncludeFirst[i]); } return answer; } }
package concurrent_test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Description: * * @author Baltan * @date 2019/1/9 19:36 */ public class AwaitTerminationTest { public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(5); service.execute(() -> { System.out.println("线程1启动"); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } }); service.execute(() -> { System.out.println("线程2启动"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } }); TimeUnit.SECONDS.sleep(1); service.shutdown(); System.out.println("线程池关闭"); while (!service.awaitTermination(10, TimeUnit.MILLISECONDS)) { System.out.println("线程还在执行"); } System.out.println("主线程结束"); } }
package jumpingalien.part2.tests; import static jumpingalien.tests.util.TestUtils.spriteArrayForSize; import static org.junit.Assert.*; import jumpingalien.model.LivingCreatures; import jumpingalien.model.Shark; import jumpingalien.model.World; import jumpingalien.util.Sprite; import jumpingalien.util.Util; import org.junit.Before; import org.junit.Test; public class SharkTest { private Sprite[] defaultSprites; private World defaultWorld; private Shark shark; @Before public void setUp() { this.defaultWorld = new World(10,10,10,10,10,9,9); this.defaultSprites = spriteArrayForSize(2,2); this.shark = new Shark(0, 0, 0, 0, defaultWorld,defaultSprites,100); } @Test public void extendedConstructor$LegalCase() { Shark shark = new Shark(5, 10, 1, 20,defaultWorld,defaultSprites,100); assertTrue(shark.getXPosition() == 5); assertTrue(shark.getYPosition() == 10); assertTrue(shark.getHorizontalVelocity() == 1); assertTrue(shark.getVerticalVelocity() ==20); assertTrue(shark.getHorizontalAcceleration()==1.5); assertTrue(shark.getVerticalAcceleration() == 0); assertTrue(shark.getWorld() == defaultWorld); assertTrue(shark.getHP() == 100); assertArrayEquals(defaultSprites, shark.getSpriteArray()); } @Test public void extendedConstructor$OutOfBoundXPosition() { //Positions too big (out of bounds of gameworld) Shark shark = new Shark(300,0,0,0,defaultWorld,defaultSprites,100); assertTrue(shark.getHP() == 0); assertTrue(shark.getWorld() == null); assertTrue(shark.isDead()); } @Test public void extendedConstructor$OutOfBoundYPosition() { //Positions too big (out of bounds of gameworld) Shark shark = new Shark(0,6805,0,0,defaultWorld,defaultSprites,100); assertTrue(shark.getHP() == 0); assertTrue(shark.getWorld() == null); assertTrue(shark.isDead()); } @Test public void testCorrectInitialisedWithPositionAndSprites() { Shark shark = new Shark(0,0,defaultSprites); assertTrue(shark.getWorld() ==null); assertTrue(shark.getHP() == 100); assertTrue(shark.getHorizontalVelocity() == 0); assertTrue(shark.getVerticalVelocity() == 0); } @Test public void testCorrectInitialisedWithOnlySprites() { Shark shark = new Shark(defaultSprites); assertTrue(shark.getXPosition()==0); assertTrue(shark.getYPosition()==0); } @Test public void testTerminteWhenTerminatedWithinTheBounds(){ assertTrue(shark.isAlive()); shark.addHP(-100); //Terminates when HP goes below 0 HP assertTrue(shark.getHP() == 0); assertTrue(shark.isDying()); for (int i=0; i<5; i += 1){ shark.advanceTime(0.199); } assertTrue(shark.isDead()); assertTrue(shark.getWorld() == null); } @Test(expected=IllegalStateException.class) public void testTerminteWhenAliveAndWithinTheBounds() throws Exception{ assertTrue(shark.isAlive()); shark.terminate(); assertTrue(shark.isAlive()); } @Test public void testTerminteWhenOutsideTheBounds(){ shark.setPosition(0, 666); //when going out of bound the slime is immediately removed. assertTrue(shark.isDead()); assertTrue(shark.getWorld() == null); } //TODO //@Test(expected = IllegalXPositionException.class) //public void testSetXposition$IllegalCase() throws Exception{ // shark alien = new shark(spriteArrayForSize(2, 2)); // alien.setXPosition(-5); // assertTrue(alien.getXPosition() == -5); //} @Test public void testSetXposition$LegalCase() throws Exception{ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setXPosition(5); assertTrue(shark.getXPosition() == 5); } //@Test(expected = IllegalXPositionException.class) //public void testSetXposition$IllegalCase() throws Exception{ // shark alien = new shark(spriteArrayForSize(2, 2)); // alien.setXPosition(-5); // assertTrue(alien.getXPosition() == -5); //} @Test public void testSetYposition$LegalCase() throws Exception{ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setYPosition(5); assertTrue(shark.getYPosition() == 5); } @Test public void testSetHorizontalVelocity() { Shark creature = new Shark(0,0,spriteArrayForSize(2, 2)); double velocity; creature.setHorizontalVelocity(2); velocity = creature.getHorizontalVelocity(); assertEquals(2.0,velocity,Util.DEFAULT_EPSILON); creature.setHorizontalVelocity(5); velocity = creature.getHorizontalVelocity(); assertEquals(4,velocity,Util.DEFAULT_EPSILON); creature.setHorizontalVelocity(-5); velocity = creature.getHorizontalVelocity(); assertEquals(0.0,velocity,Util.DEFAULT_EPSILON); } @Test public void testSetVerticalVelocity() { Shark creature = new Shark(0,0,spriteArrayForSize(2, 2)); double velocity; creature.setVerticalVelocity(10); velocity = creature.getVerticalVelocity(); //The maximum speed is limited by 8 [m/s] assertEquals(10,velocity,Util.DEFAULT_EPSILON); creature.setVerticalVelocity(5); velocity = creature.getVerticalVelocity(); assertEquals(5,velocity,Util.DEFAULT_EPSILON); } @Test public void hasAsWorld_True(){ assertTrue(shark.hasAsWorld(defaultWorld)); } @Test public void hasAsWorld_False(){ shark.setWorld(null); assertFalse(shark.hasAsWorld(defaultWorld)); } @Test public void canHaveAsWorld_True(){ assertTrue(shark.canHaveAsWorld(defaultWorld)); } @Test public void canHaveAsWorld_False(){ assertFalse(shark.canHaveAsWorld(null)); } @Test public void isValidSpriteArray_True() { assertTrue(LivingCreatures.isValidSpriteArray(spriteArrayForSize(2, 2, 2),shark)); } @Test public void isValidSpriteArray_False() { assertFalse(LivingCreatures.isValidSpriteArray(spriteArrayForSize(2, 2, 0),shark)); assertFalse(LivingCreatures.isValidSpriteArray(spriteArrayForSize(2, 2, 13),shark)); assertFalse(LivingCreatures.isValidSpriteArray(spriteArrayForSize(2, 2, 8),shark)); } @Test public void getCurrentSprite$Right(){ shark.setDirection(1); assertTrue(shark.getCurrentSprite() == shark.getSpriteArray()[1]); } @Test public void getCurrentSprite$Left(){ shark.setDirection(-1); assertTrue(shark.getCurrentSprite() == shark.getSpriteArray()[0]); } @Test public void setHP_NormalCase(){ shark.setHP(shark.getMinHP()); assertTrue(shark.getHP() == shark.getMinHP()); shark.setHP(shark.getMaxHP()/2); assertTrue(shark.getHP() == shark.getMaxHP()/2); shark.setHP(shark.getMaxHP()); assertTrue(shark.getHP() == shark.getMaxHP()); } @Test public void setHP_SpecialCase(){ shark.setHP(shark.getMinHP() - 5); assertTrue(shark.getHP() == shark.getMinHP()); shark.setHP(shark.getMaxHP()+5); assertTrue(shark.getHP() == shark.getMaxHP()); } @Test public void changeHorizontalPosition(){ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setHorizontalVelocity(4); shark.setHorizontalAcceleration(2); shark.setDirection(1); shark.changeHorizontalPosition(0.1,0); assertEquals(shark.getXPosition(),40,Util.DEFAULT_EPSILON); } @Test public void changeVerticalPosition(){ Shark shark = new Shark(100,100,spriteArrayForSize(2, 2)); shark.startJump(5,2); shark.changeVerticalPosition(0.1); assertEquals(shark.getXPosition(),100,Util.DEFAULT_EPSILON); Shark shark1 = new Shark(0,0,spriteArrayForSize(2, 2)); shark1.setVerticalVelocity(-5); shark1.setVerticalAcceleration(-2); shark1.setDirection(1); shark1.changeVerticalPosition(0.1); assertEquals(shark.getXPosition(),100,Util.DEFAULT_EPSILON); } @Test public void startJump_whileNotMovingVertical(){ shark.startJump(7,-2); assertEquals(shark.getVerticalVelocity(),7,Util.DEFAULT_EPSILON); assertEquals(shark.getVerticalAcceleration(),-2,Util.DEFAULT_EPSILON); assertTrue(shark.getMovingVertical()); } @Test public void startJump_WhileMovingVertical(){ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setVerticalVelocity(-5); shark.setVerticalAcceleration(-2); shark.setMovingVertical(true); shark.startJump(5,9); assertEquals(shark.getVerticalVelocity(),-5,Util.DEFAULT_EPSILON); assertEquals(shark.getVerticalAcceleration(),-2,Util.DEFAULT_EPSILON); assertTrue(shark.getMovingVertical()); } @Test public void endJump_ableToEndJump(){ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setVerticalVelocity(5); shark.setVerticalAcceleration(-2); shark.endJump(); assertEquals(shark.getVerticalVelocity(),0,Util.DEFAULT_EPSILON); assertEquals(shark.getVerticalAcceleration(),-2,Util.DEFAULT_EPSILON); } @Test public void endJump_unableToEnd(){ Shark shark = new Shark(0,0,spriteArrayForSize(2, 2)); shark.setVerticalVelocity(-5); shark.setVerticalAcceleration(-2); shark.endJump(); assertEquals(shark.getVerticalVelocity(),-5,Util.DEFAULT_EPSILON); assertEquals(shark.getVerticalAcceleration(),-2,Util.DEFAULT_EPSILON); } }
package com.mockito.v4_v5_stubbing_expect; public class StubbingService { public String runRealMethod() { System.out.println("============== You call runRealMethod"); return "runRealMethod"; } public String runStubbingMethod() { System.out.println("============== You call runStubbingMethod"); return "runStubbingMethod"; } }
package com.example.owner.cs125finalproject; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; 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.ImageButton; import android.widget.TextView; public class GameEndWin extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_end_win); Button main_menu = findViewById(R.id.main_menu_button); /************************************************* * Title: Android .ogg file stops playing after a few seconds * Author: Vadim Zin4uk * Date: October 8, 2014 * Code version: N/A * Availability: https://stackoverflow.com/questions/24011610/android-ogg-file-stops-playing-after-a-few-seconds **************************************************/ MediaPlayer winningSound = MediaPlayer.create(this, R.raw.winningsound); winningSound.start(); main_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("Click:","Main Menu"); Intent i = new Intent(GameEndWin.this, HomePage.class); startActivity(i); } }); ImageButton restart = findViewById(R.id.restart_button); restart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("Click:","Restart of game after game ended"); Intent i = new Intent(GameEndWin.this, Levels_Menu.class); startActivity(i); } }); Intent intent = getIntent(); String scoreReceivedFromLevel = ((Integer) intent.getIntExtra("score", 20)).toString(); TextView totalScore = findViewById(R.id.total_score); totalScore.setText(scoreReceivedFromLevel); } /************************************************* * Title: Disable back button in android * Author: Gopinath * Date: January 24, 2011 * Edit Date: December 13, 2017 * Code version: N/A * Availability: https://stackoverflow.com/questions/4779954/disable-back-button-in-android **************************************************/ public void onBackPressed() { Intent i = new Intent(GameEndWin.this, Levels_Menu.class); startActivity(i); } }
/** * */ package ca.soen6441.tf.critterstd.model.strategy; import java.io.Serializable; /** * ShootingStrategy specifies shooting Strategy. * * @author Hardik */ public enum ShootingStrategy implements Serializable { SHOOT_CLOSEST, SHOOT_EXITING, SHOOT_WEAKEST, SHOOT_STRONGEST; }
package org.eurokids.db; import java.sql.SQLException; import java.sql.*; public class DbUtils { String connectionUrl="jdbc:mysql://localhost:3306/onlinejava"; public static PreparedStatement getPreparedStatement(String sql)throws ClassNotFoundException,SQLException{ PreparedStatement ps=null; Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/eurokids"; String user="root"; String password=null; Connection con =DriverManager.getConnection(url,user,password); ps=con.prepareStatement(sql); return ps; } //public static void main(String[] args)throws ClassNotFoundException,SQLException{ //getPreparedStatement("select * from admin"); // //System.out.println("hello"); //} }
package com.classes; // LibGDX imports import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; // Custom class import import com.sprites.MovementSprite; // Constants imports import static com.config.Constants.FIRETRUCK_HEIGHT; import static com.config.Constants.FIRETRUCK_WIDTH; // Java util import import java.util.ArrayList; /** * The truck implementation. A sprite capable of moving and colliding with other sprites. * * @author Archie * @since 16/12/2019 */ public abstract class Truck extends MovementSprite { // Private values to be used in this class only protected ArrayList<Texture> textureSlices; protected float[] truckProperties; /** * Overloaded constructor containing all possible parameters. * Creates a truck capable of moving and colliding with the tiledMap and other sprites. * It also requires an ID so that it can be focused with the camera. Drawn with the given * texture at the given position. * * @param textureSlices The array of textures used to draw the truck with. * @param properties The properties of the truck inherited from Constants. * @param collisionLayer The layer of the map the truck collides with. * @param xPos The x-coordinate for the truck. * @param yPos The y-coordinate for the truck. */ public Truck (ArrayList<Texture> textureSlices, float[] properties, TiledMapTileLayer collisionLayer, float xPos, float yPos) { super(textureSlices.get(textureSlices.size() - 1), collisionLayer); this.textureSlices = textureSlices; this.setPosition(xPos, yPos); this.truckProperties = properties; this.create(); } /** * Simplfied constructor for the truck, that doesn't require a position. * Creates a truck capable of moving and colliding with the tiledMap and other sprites. * It also requires an ID so that it can be focused with the camera. Drawn with the given * texture at (0,0). * * @param textureSlices The array of textures used to draw the truck with. * @param properties The properties of the truck inherited from Constants. * @param collisionLayer The layer of the map the truck collides with. */ public Truck(ArrayList<Texture> textureSlices, float[] properties, TiledMapTileLayer collisionLayer) { super(textureSlices.get(textureSlices.size() - 1), collisionLayer); this.textureSlices = textureSlices; this.create(); } /** * Sets the health of the truck and its size provided in CONSTANTS. * Also initialises any properties needed by the truck. */ private void create() { this.setSize(FIRETRUCK_WIDTH, FIRETRUCK_HEIGHT); this.getHealthBar().setMaxResource((int) this.truckProperties[0]); this.setAccelerationRate(this.truckProperties[1]); this.setDecelerationRate(this.truckProperties[1] * 0.6f); this.setMaxSpeed(this.truckProperties[2]); this.setRestitution(this.truckProperties[3]); // Start the truck facing left this.rotate(-90); } /** * Update the position and direction of the truck every frame. * TODO: change direction vector2 to Constants.Direction * * @param batch The batch to draw onto. * @param camera Used to get the centre of the screen. */ public void update(Batch batch) { super.update(batch); drawVoxelImage(batch); } /** * Draws the voxel representation of the truck. Incrementally builds the truck * from layers of images with each image slightly higher than the last */ protected void drawVoxelImage(Batch batch) { // Length of array containing image slices int slicesLength = this.textureSlices.size() - 1; float x = getX(), y = getY(), angle = this.getRotation(); float width = this.getWidth(), height = this.getHeight(); for (int i = 0; i < slicesLength; i++) { Texture texture = animateLights(i); batch.draw(new TextureRegion(texture), x, (y - slicesLength / 3) + i, width / 2, height / 2, width, height, 1, 1, angle, true); } } /** * Alternates between showing the red and blue light on the truck. * Returns the texture at the given index offset to the correct index. * * @param index The index of the next texture to draw the sprite with. * @return The next texture to draw the sprite with. */ private Texture animateLights(int index) { if (index == 14) { // The index of the texture containing the first light colour Texture texture = this.getInternalTime() / 5 > 15 ? this.textureSlices.get(index + 1) : this.textureSlices.get(index); return texture; } else if (index > 14) { // Offset remaining in order to not repeat a texture return this.textureSlices.get(index + 1); } return this.textureSlices.get(index); } /** * Gets whether the truck is damaged. * * @return Whether the truck is damaged. */ public boolean isDamaged() { return this.getHealthBar().getCurrentAmount() < this.truckProperties[0]; } /** * Overloaded method for drawing debug information. Draws the hitbox as well * as the hose range indicator. * * @param renderer The renderer used to draw the hitbox and range indicator with. */ @Override public void drawDebug(ShapeRenderer renderer) { super.drawDebug(renderer); } /** * Dispose of all textures used by this class and its parents. */ @Override public void dispose() { super.dispose(); for (Texture texture : this.textureSlices) { texture.dispose(); } } }
package com.lsz.dto; import lombok.Data; @Data public class OpenDoDTO { private String id; private String path; private String type; private String projectName; public OpenDoDTO(){ } public OpenDoDTO(String id, String path, String type, String projectName) { this.id = id; this.path = path; this.type = type; this.projectName = projectName; } }
package tez.levent.feyyaz.kedi.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import tez.levent.feyyaz.kedi.services.GetData; public class AlarmStartService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent ıntent) { Intent i = new Intent(context,GetData.class); context.startService(i); Log.d("AlarmStartService","Çalıştı!"); } }
package com.gman.config; import com.gman.service.EnglishGreetingService; import com.gman.service.GreetingService; import com.gman.service.RussianGreetingService; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; /** * Created by Anton Mikhaylov on 16.11.17. */ @Configuration public class GreetingServiceConfig { @Bean @ConditionalOnProperty(name = "language.greeting", havingValue = "english", matchIfMissing = true) @Primary public GreetingService englishGreetingService() { return new EnglishGreetingService(); } @Bean @ConditionalOnProperty(name = "language.greeting", havingValue = "russian") public GreetingService russianGreetingService() { return new RussianGreetingService(); } }
package lab_6_problem1; import java.util.Scanner; public class TestCompany { public static void main(String[] args) { Company testCompany1=new Company(); testCompany1.newCustomer(); testCompany1.newCustomer(); testCompany1.endCustomer(); testCompany1.sendBroadcast(); Scanner keyboard=new Scanner(System.in); Company testCompany2=new Company(keyboard.nextLine()); testCompany2.newCustomer(); testCompany2.newCustomer(); testCompany2.endCustomer(); testCompany2.sendBroadcast(); keyboard.close(); } }
package com.tencent.mm.boot.svg.a.a; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public final class bk extends c { private final int height = 24; private final int width = 24; protected final int b(int i, Object... objArr) { switch (i) { case 0: return 24; case 1: return 24; case 2: Canvas canvas = (Canvas) objArr[0]; Looper looper = (Looper) objArr[1]; c.f(looper); c.e(looper); Paint i2 = c.i(looper); i2.setFlags(385); i2.setStyle(Style.FILL); Paint i3 = c.i(looper); i3.setFlags(385); i3.setStyle(Style.STROKE); i2.setColor(-16777216); i3.setStrokeWidth(1.0f); i3.setStrokeCap(Cap.BUTT); i3.setStrokeJoin(Join.MITER); i3.setStrokeMiter(4.0f); i3.setPathEffect(null); c.a(i3, looper).setStrokeWidth(1.0f); canvas.saveLayerAlpha(null, 51, 4); i2 = c.a(i2, looper); i2.setColor(-16777216); canvas.save(); Paint a = c.a(i2, looper); Path j = c.j(looper); j.moveTo(21.721962f, 9.453671f); j.lineTo(15.541582f, 8.317529f); j.cubicTo(15.434511f, 8.296709f, 15.339336f, 8.2312765f, 15.288775f, 8.133128f); j.lineTo(12.30863f, 2.6725035f); j.cubicTo(12.246172f, 2.5565097f, 12.121256f, 2.5f, 11.999313f, 2.5f); j.cubicTo(11.874397f, 2.5f, 11.752456f, 2.559484f, 11.689998f, 2.6725035f); j.lineTo(8.709852f, 8.133128f); j.cubicTo(8.656317f, 8.228302f, 8.5641165f, 8.296709f, 8.457046f, 8.317529f); j.lineTo(2.2766654f, 9.453671f); j.cubicTo(2.011962f, 9.501259f, 1.907865f, 9.825446f, 2.0952394f, 10.018769f); j.lineTo(6.5892506f, 14.643644f); j.cubicTo(6.6695538f, 14.726922f, 6.705244f, 14.839941f, 6.687399f, 14.952961f); j.lineTo(5.661301f, 21.136314f); j.cubicTo(5.6196623f, 21.401018f, 5.893288f, 21.60624f, 6.1371727f, 21.490244f); j.lineTo(11.844656f, 18.780752f); j.cubicTo(11.895217f, 18.756958f, 11.948752f, 18.745062f, 12.002288f, 18.745062f); j.cubicTo(12.055823f, 18.745062f, 12.109359f, 18.756958f, 12.159921f, 18.780752f); j.lineTo(17.867403f, 21.490244f); j.cubicTo(18.111288f, 21.60624f, 18.381939f, 21.401018f, 18.343275f, 21.136314f); j.lineTo(17.569984f, 16.478724f); j.cubicTo(18.542545f, 15.78871f, 19.015444f, 15.196845f, 19.071953f, 15.107619f); j.cubicTo(19.137386f, 15.006496f, 19.095747f, 14.920244f, 19.095747f, 14.920244f); j.cubicTo(19.095747f, 14.920244f, 19.095747f, 14.920244f, 19.095747f, 14.920244f); j.cubicTo(17.528345f, 15.571593f, 13.721374f, 16.666098f, 9.042962f, 16.505491f); j.cubicTo(8.477865f, 16.487646f, 7.915742f, 16.422215f, 7.600477f, 16.365704f); j.cubicTo(7.261419f, 16.303246f, 7.2078834f, 15.940394f, 7.416077f, 15.767891f); j.cubicTo(8.727697f, 14.667438f, 13.093818f, 11.544532f, 13.162225f, 11.490996f); j.cubicTo(13.242528f, 11.428538f, 13.245502f, 11.336338f, 13.174122f, 11.276854f); j.cubicTo(13.072999f, 11.190602f, 10.684719f, 10.348905f, 7.032406f, 10.908053f); j.cubicTo(6.782573f, 10.946718f, 6.6368375f, 10.604686f, 6.8807216f, 10.476795f); j.cubicTo(7.9097934f, 9.932517f, 10.256434f, 9.260348f, 12.647689f, 9.278193f); j.cubicTo(14.316213f, 9.293065f, 15.758698f, 9.792729f, 16.169138f, 10.093123f); j.cubicTo(16.38328f, 10.250756f, 16.335691f, 10.444078f, 16.160215f, 10.592789f); j.cubicTo(15.262008f, 11.354183f, 12.710147f, 13.120855f, 11.820862f, 13.804921f); j.cubicTo(11.716765f, 13.885224f, 11.755429f, 14.01014f, 11.868449f, 14.051779f); j.cubicTo(13.397186f, 14.637696f, 15.687318f, 14.819122f, 17.302307f, 14.833993f); j.lineTo(21.915285f, 10.015795f); j.cubicTo(22.087788f, 9.825446f, 21.983692f, 9.501259f, 21.721962f, 9.453671f); j.close(); WeChatSVGRenderC2Java.setFillType(j, 1); canvas.drawPath(j, a); canvas.restore(); canvas.restore(); c.h(looper); break; } return 0; } }
package tema8; import java.time.LocalDate; import java.time.Period; import java.util.ArrayList; import java.util.Collections; import java.util.Optional; public class HistoricoEmprestimos { private ArrayList<Emprestimo> historicoEmprestimos; private Biblioteca biblioteca; private Clientela clientela; public HistoricoEmprestimos(Biblioteca biblioteca, Clientela clientela) { historicoEmprestimos = new ArrayList<Emprestimo>(); this.biblioteca = biblioteca; this.clientela = clientela; } public ArrayList<Emprestimo> retornaHistoricoEmprestimos() { return historicoEmprestimos; } public void zeraHistoricoEmprestimos() { historicoEmprestimos.clear(); } public void atualizaCont() { int proximoId=0; for (Emprestimo emprestimo : historicoEmprestimos) { if (emprestimo.getId() > proximoId) { proximoId = emprestimo.getId(); } } Emprestimo.setCont(proximoId); } public void addEmprestimo(Emprestimo emprestimo) { historicoEmprestimos.add(emprestimo); } public void apagarEmprestimo(Emprestimo emprestimo) { historicoEmprestimos.remove(emprestimo); } public int getSize() { return historicoEmprestimos.size(); } public void atualizaHistoricoEUsuario(Usuario usuarioTestado) { for (Emprestimo emprestimo : historicoEmprestimos) { if (emprestimo.getUsuario() == usuarioTestado) { int intervaloDias; if (emprestimo.getDataDevolucao() != null ) { if (emprestimo.getDataDevolucao().isAfter(emprestimo.getDataADevolver())) { intervaloDias = Period.between(emprestimo.getDataADevolver(), emprestimo.getDataDevolucao()).getDays(); usuarioTestado.setFgEmDia(false); } else { intervaloDias = 0; } }else if (emprestimo.getDataDevolucao() == null && LocalDate.now().isAfter(emprestimo.getDataADevolver())) { intervaloDias = Period.between(emprestimo.getDataADevolver(), LocalDate.now()).getDays(); usuarioTestado.setFgEmDia(false); } else { intervaloDias = 0; } emprestimo.setQtDiasAtraso(intervaloDias); } } } public void atualizaHistoricoEUsuario() { for (Emprestimo emprestimo : historicoEmprestimos) { int intervaloDias; if (emprestimo.getDataDevolucao() != null ) { if (emprestimo.getDataDevolucao().isAfter(emprestimo.getDataADevolver())) { intervaloDias = Period.between(emprestimo.getDataADevolver(), emprestimo.getDataDevolucao()).getDays(); emprestimo.getUsuario().setFgEmDia(false); } else { intervaloDias = 0; } }else if (emprestimo.getDataDevolucao() == null && LocalDate.now().isAfter(emprestimo.getDataADevolver())) { intervaloDias = Period.between(emprestimo.getDataADevolver(), LocalDate.now()).getDays(); emprestimo.getUsuario().setFgEmDia(false); } else { intervaloDias = 0; } emprestimo.setQtDiasAtraso(intervaloDias); } } public Optional<Emprestimo> emprestar(Livro livro, Usuario usuario) { atualizaHistoricoEUsuario(usuario); if(usuario.isFgEmDia() && !livro.isFgEmprestado() && !usuario.estaNoLimiteDeLivros()) { Emprestimo emprestimo = new Emprestimo(); emprestimo.emprestou(livro, usuario); biblioteca.emprestarLivro(livro); historicoEmprestimos.add(emprestimo); return Optional.of(emprestimo); } return Optional.empty(); } public Optional<Emprestimo> buscaEmprestimoPorUsuarioELivro(Livro livro, Usuario usuario) { ArrayList<Emprestimo> historicoRecente = historicoEmprestimos; Collections.reverse(historicoRecente); for (Emprestimo emprestimoMaisRecente : historicoRecente) { if (livro.equals(emprestimoMaisRecente.getLivro()) && usuario.equals(emprestimoMaisRecente.getUsuario())) { return Optional.of(emprestimoMaisRecente); } } return Optional.empty(); } public void renovar (Emprestimo emprestimoARenovar) { Usuario usuarioRenovando = emprestimoARenovar.getUsuario(); atualizaHistoricoEUsuario(usuarioRenovando); if (!usuarioRenovando.isFgEmDia()) { throw new IllegalArgumentException("Você não está em dia com a biblioteca. Esta ação não será possível."); } else { emprestimoARenovar.renovacao(); } } public void devolver(Emprestimo emprestimoDevolvendo) { if (emprestimoDevolvendo.getDataDevolucao() == null) { emprestimoDevolvendo.devolveu(); } else { throw new IllegalArgumentException("O livro " + emprestimoDevolvendo.getLivro().getTitulo() + " já foi devolvido pelo usuário " + emprestimoDevolvendo.getUsuario().getNome() + "."); } } public void devolverVariosLivros(Usuario usuarioDevolvendo, ArrayList<Livro> livrosADevolver) { for (Livro livroEmprestado : livrosADevolver) { Optional<Emprestimo> emprestimoDevolvendo = buscaEmprestimoPorUsuarioELivro(livroEmprestado, usuarioDevolvendo); if (emprestimoDevolvendo.isPresent()) { devolver(emprestimoDevolvendo.get()); } } } public ArrayList<Emprestimo> relatorioLivrosEmprestados() { atualizaHistoricoEUsuario(); ArrayList<Emprestimo> livrosEmprestados = new ArrayList<Emprestimo>(); for (Emprestimo emprestimo : historicoEmprestimos) { if (emprestimo.getDataDevolucao() == null) { livrosEmprestados.add(emprestimo); } } return livrosEmprestados; } public ArrayList<Emprestimo> relatorioEmprestimosAtrasados() { ArrayList<Emprestimo> historicoEmprestimosAtrasados = new ArrayList<Emprestimo>(); atualizaHistoricoEUsuario(); for (Emprestimo emprestimo : historicoEmprestimos) { if (!emprestimo.isFgQuitado() && emprestimo.getQtDiasAtraso() != 0) { historicoEmprestimosAtrasados.add(emprestimo); } } return historicoEmprestimosAtrasados; } }
package DAL; import java.sql.*; public class MySQLAccess { private Connection connection = null; private Statement statement = null; private PreparedStatement preparedStatement = null; private ResultSet resultSet = null; private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost:3306/librarysystem"; private static final String USER = "root"; private static final String PASS = "Tutuan96"; /** * to connect to db * @throws Exception if cannot connect */ public void connectDB() throws Exception { try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, USER, PASS); } catch (Exception e) { System.out.println("Error connect db"); } } /** * get data from db * @param query query applied to db * @return ResultSet, null if doesn't find */ public ResultSet getData(String query) { try { statement = connection.createStatement(); resultSet = statement.executeQuery(query); } catch (Exception e) { System.out.println("Error query"); } return this.resultSet; } /** * update data to db * @param query query applied to db * @return number of row effected */ public int updateData(String query) { int result = 0; try { statement = connection.createStatement(); result = statement.executeUpdate(query); } catch (Exception e){ System.out.println("Error query"); return 0; } return result; } public PreparedStatement getPreparedStatement(String query){ try{ preparedStatement = connection.prepareStatement(query); } catch (Exception e) { System.out.println("Error query"); } return this.preparedStatement; } /** * close connection to db */ public void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (Exception e) { System.out.println("Error"); } } }
package com.tt.miniapp.service.hostevent; import com.tt.miniapp.service.PureServiceInterface; import org.json.JSONObject; public interface HostEventMiniAppServiceInterface extends PureServiceInterface { void addHostEventListener(String paramString1, String paramString2, HostEventListener paramHostEventListener); void onReceiveMiniAppHostEvent(String paramString1, String paramString2, JSONObject paramJSONObject); void removeHostEventListener(String paramString1, String paramString2, HostEventListener paramHostEventListener); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\service\hostevent\HostEventMiniAppServiceInterface.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.flutterwave.raveandroid.data.events; import com.flutterwave.raveandroid.rave_logger.Event; import static com.flutterwave.raveandroid.rave_logger.Event.EVENT_TITLE_REQUERY; public class RequeryCancelledEvent { Event event; public RequeryCancelledEvent() { event = new Event(EVENT_TITLE_REQUERY, "Requery Cancelled"); } public Event getEvent() { return event; } }
package animatronics.client.gui; import java.util.Arrays; import net.minecraft.client.Minecraft; import net.minecraft.inventory.Container; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.StatCollector; import animatronics.api.energy.ITEHasEntropy; import animatronics.client.gui.element.ElementEntropyStorage; import animatronics.client.gui.element.ElementTextField; import animatronics.common.tile.TileEntityHeatCollapser; public class GuiEntropyFurnace extends GuiBase{ public GuiEntropyFurnace(Container container, TileEntity tile) { super(container, tile); elementList.add(new ElementEntropyStorage(7, 6, (ITEHasEntropy)tile)); } }
package me.man_cub.cpvppotions; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; public class CPVPPotions extends JavaPlugin { public void onEnable() { Bukkit.getServer().getPluginManager().registerEvents(new CPVPPotionsListener(), this); Bukkit.getLogger().info("[CPVPPotions] has been enabled."); } public void onDisable() { Bukkit.getLogger().info("[CPVPPotions] has been disabled."); } }
import java.util.Arrays; public class Outline { public static void main(String[] args) { String[] stringArray = { "the", "quick", "brown", "fox", "jumped", "over", "ever", "heat", "bees", "box" }; sortByLength(stringArray); sortByLengthReversed(stringArray); sortByFirstChar(stringArray); sortByContainsLetter(stringArray, 'e'); System.out.println(Arrays.asList(stringArray)); } public static void sortByLength(String[] stringArray) { Arrays.sort(stringArray, (String a, String b) -> a.length() - b.length()); } public static void sortByLengthReversed(String[] stringArray) { Arrays.sort(stringArray, (String a, String b) -> b.length() - a.length()); } public static void sortByFirstChar(String[] stringArray) { Arrays.sort(stringArray, (String a, String b) -> a.charAt(0) - b.charAt(0)); } public static void sortByContainsLetter(String[] stringArray, char c) { Arrays.sort(stringArray, (String a, String b) -> b.indexOf(c) - a.indexOf(c)); } }
class Solution { public String reverseWords(String s) { StringBuilder sol = new StringBuilder(); String[] split = s.split("\\s"); for(int i = 0; i < split.length; i++){ String current = split[i]; for(int j = current.length() - 1; j >= 0; j--){ sol.append(current.charAt(j)); } if(i != split.length - 1){ sol.append(" "); } } return sol.toString(); } }
package com.rbysoft.myovertimebd; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.rbysoft.myovertimebd.DbHelper.DbHelper; import com.rbysoft.myovertimebd.Layout.FounderPage; import androidx.appcompat.app.AlertDialog; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class MyMainActivity extends AppCompatActivity { DbHelper dbHelper; public static BottomNavigationView navView; public static Context mycontext; public Menu mymenu; String lang="en"; Boolean isPossible=false; private InterstitialAd mInterstitialAd; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: getSupportFragmentManager().beginTransaction() .replace(R.id.Fragment_Container,new Fragment_home()) .addToBackStack("MAINSTACK") .commit(); return true; case R.id.navigation_dashboard: if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } else { Log.d("TAG", "The interstitial wasn't loaded yet."); } getSupportFragmentManager().beginTransaction() .replace(R.id.Fragment_Container,new Fragment_Detailslist()) .addToBackStack("MAINSTACK") .commit(); return true; case R.id.navigation_calculation: getSupportFragmentManager().beginTransaction() .replace(R.id.Fragment_Container,new Fragment_calculator()) .addToBackStack("MAINSTACK") .commit(); return true; case R.id.navigation_profile: getSupportFragmentManager().beginTransaction() .replace(R.id.Fragment_Container,new Fragment_profile()) .addToBackStack("MAINSTACK") .commit(); return true; case R.id.navigation_notifications: getSupportFragmentManager().beginTransaction() .replace(R.id.Fragment_Container,new Fragment_notification()) .addToBackStack("MAINSTACK") .commit(); return true; } return false; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_main); lang=Saving.getAString(this,"Language"); if (lang==null){ Saving.saveAString(this,"Language","En"); } navView = findViewById(R.id.nav_view); navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); this.setTitle("My Overtime BD"); lang=Saving.getAString(this,"Language"); if (lang.equals("bn")&& isPossible){ UpdateResources(); } MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-5998919965178917/3766204015"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); dbHelper = new DbHelper(this); navView.setSelectedItemId(R.id.navigation_home); } private void UpdateResources() { mymenu.getItem(0).setTitle(getResources().getString(R.string.clearrecordb)); mymenu.getItem(1).setTitle(getResources().getString(R.string.sharethisappb)); mymenu.getItem(2).setTitle(getResources().getString(R.string.rateusb)); mymenu.getItem(3).setTitle(getResources().getString(R.string.contactusb)); mymenu.getItem(4).setTitle(getResources().getString(R.string.aboutfounderb)); mymenu.getItem(5).setTitle(getResources().getString(R.string.exitb)); } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.e("MYMAIN","MENU CREATED"); isPossible=true; getMenuInflater().inflate(R.menu.dev_menu, menu); mymenu=menu; if (lang.equals("bn")){ UpdateResources(); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.reset: resetButton(); break; case R.id.share: try { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My OverTime Bd"); String shareMessage; shareMessage = "\nTracking,Counting and Calculating Overtime data\n\n" + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n"; shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage); startActivity(Intent.createChooser(shareIntent, "Choose one")); } catch(Exception e) { //e.toString(); } break; case R.id.rate: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ BuildConfig.APPLICATION_ID))); break; case R.id.exit: finish(); System.exit(0); case R.id.founderpage: startActivity(new Intent(MyMainActivity.this, FounderPage.class)); break; case R.id.contact: Uri uri = Uri.parse("fb-messenger://user/320673321942965"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(intent); } catch (ActivityNotFoundException e){ startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.facebook.orca"))); } break; } return true; } @Override public void onBackPressed() { AlertDialog.Builder alerDialogBuilder = new AlertDialog.Builder(this); if(lang.equals("bn")){ alerDialogBuilder.setTitle(getResources().getString(R.string.exitb)).setIcon(R.drawable.ic_warning); alerDialogBuilder.setMessage(getResources().getString(R.string.doyouwanttoexitb)); }else{ alerDialogBuilder.setTitle(getResources().getString(R.string.exit)).setIcon(R.drawable.ic_warning); alerDialogBuilder.setMessage(getResources().getString(R.string.doyouwanttoexit)); } alerDialogBuilder.setCancelable(true); alerDialogBuilder.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); alerDialogBuilder.setNegativeButton(getResources().getString(R.string.No), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alerDialogBuilder.create(); alertDialog.show(); } public void resetButton() { AlertDialog.Builder alerDialogBuilder = new AlertDialog.Builder(this); alerDialogBuilder.setTitle(getResources().getString(R.string.warning)); alerDialogBuilder.setIcon(R.drawable.ic_warning); alerDialogBuilder.setMessage(getResources().getString(R.string.deletealldata)); alerDialogBuilder.setCancelable(true); alerDialogBuilder.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dbHelper.ResetTable(); Toast.makeText(MyMainActivity.this, getResources().getString(R.string.resetalldata), Toast.LENGTH_SHORT).show(); } }); alerDialogBuilder.setNegativeButton(getResources().getString(R.string.No), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alerDialogBuilder.create(); alertDialog.show(); } }
package net.sssanma.mc.protect; import org.bukkit.block.Sign; public class LockSignFromBlock extends LockSign { Sign sign; public LockSignFromBlock(Sign sign) throws LockerException { super(sign.getLines()); this.sign = sign; } public Sign getSign() { return sign; } }
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class C206_CaseStudyTest { private Student s1; private Student s2; @Before public void setUp() throws Exception { s1 = new Student("001", "Nigel", "primary 5", "W67A", "Magdelene", "Jack", "Jack@gmail.com"); s2 = new Student("003", "Mary", "primary 6", "W67F", "Joyce", "Richard", "Richard@gmail.com"); } @After public void tearDown() throws Exception { } @Test public void addStudentTest() { //Test that studentlist is not null assertNotNull("Test that studentlist is not null",StudentDB.studentlist); //Test that the size of studentlist is 0 before adding any student assertEquals("Test that the size of studentlist is 0 before adding any student",0,StudentDB.studentlist.size()); //Test that the size of the student arraylist is 1 after adding 1 student StudentDB.addStudent(s1); assertEquals("Test that the size of the student arraylist is 1 after adding 1 student",1,StudentDB.studentlist.size()); //Test that the size of studentlist is zero after removing student StudentDB.addStudent(s1); assertEquals("Test that the size of studentlist is 1 after removing 1 student",2,StudentDB.studentlist.size()); } }
package bowling; import java.util.LinkedList; /** * * @author Emmanouil Vergopoulos, Ozan Agtas, Jasmin Reis Klapper, Berfin Korkmaz * */ public abstract class Game implements IGame { private boolean gameStarted; private boolean gameFinished; private String name; private int currentRound; private int maxRounds; private int pinsLeft; private int maxPins; private int maxPlayerCount; private int throwNr; private Player currentPlayer; private LinkedList<Player> listOfPlayers; public Game(int maxPlayers) { this.maxPlayerCount = maxPlayers; this.gameStarted = false; this.gameFinished = false; this.currentRound = 1; this.throwNr = 1; this.maxRounds = 0; this.listOfPlayers = new LinkedList<Player>(); System.out.println(this.gameStarted); // this.listOfPlayers.ensureCapacity(2 * maxPlayers); } @Override public Player addPlayer(String name) { Player p = new Player(listOfPlayers.size(), name); listOfPlayers.add(p); System.out.println(p.toString()); return p; } @Override public Player getActivePlayer() { return this.currentPlayer; } public void setActivePlayer(Player p) { this.currentPlayer = p; } @Override public int getActivePlayerCount() { return this.listOfPlayers.size(); } @Override public int getMaxPlayerCount() { return this.maxPlayerCount; } @Override public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public int getPinsLeft() { return this.pinsLeft; } public void setPinsLeft(int nr) { this.pinsLeft = nr; } @Override public int getPinCount() { return this.maxPins; } public void setPinCount(int pins) { this.maxPins = pins; } @Override public Player getPlayer(int id) { for (Player p : listOfPlayers) { if (p.getID() == id) return p; } return null; } public LinkedList<Player> getListOfPlayers() { return this.listOfPlayers; } @Override public int getRound() { return this.currentRound; } public void setRound(int newRound) { this.currentRound = newRound; } @Override public int getRoundCount() { return this.maxRounds; } public void setMaxRound(int rounds) { this.maxRounds = rounds; } @Override public int getThrow() { return throwNr; } public void setThrow(int throwNr) { this.throwNr = throwNr; } @Override public boolean hasFinished() { return gameFinished; } public void setHasFinished(boolean f) { gameFinished = f; } @Override public boolean hasStarted() { return gameStarted; } @Override public boolean startGame() { if (hasStarted()) System.err.println("Spiel ist bereits gestartet!"); if (listOfPlayers.size() < 2) System.err.println("Anzahl der Spieler ist zur klein!"); if (!gameStarted && listOfPlayers.size() >= 2 && getName() != null && getRoundCount() > 0 && this.getPinCount() > 0) { this.setActivePlayer(this.getListOfPlayers().getFirst()); gameStarted = true; } this.resetPins(); return hasStarted(); } /** * */ public void resetPins() { this.pinsLeft = this.maxPins; } @Override public boolean throwBall(int count) { if (!hasStarted() || hasFinished()) { System.err.println("Spiel hat noch nicht gestartet oder ist bereits beendet!"); return false; } if (count > getPinsLeft() || count < 0) { System.err.println("Anzahl der umgeworfenen Pins ist kleiner 0 oder negativ"); return false; } return true; } }
package homework1; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import java.io.File; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; /** * Group 32 * File for the Homework n.1 of "Big Data Computing" Course" * The following file: * 1-reads an input file of non negative doubles into a RDD * 2-computes and prints the maximum value in 2 ways * 3-creates a RDD of normalized values * 4-computes and prints the mean value using count and collect methods * * @author Giovanni Candeo 1206150 * @author Nicolo Levorato 1156744 * */ public class G32HM1 { private static Double findMax(Double x, Double y) { if(x>=y){ return x; }else{ return y; } } public static class valueComparator implements Serializable, Comparator<Double> { public int compare(Double a, Double b){ if(a < b) return -1; else if(a>b) return 1; else return 0; } } public static void main(String[] args) throws FileNotFoundException{ if(args.length == 0){ throw new IllegalArgumentException("Expecting the fie name on the command line"); } ArrayList<Double> lNumbers = new ArrayList<>(); //read a list of numbers from the file passed as argument Scanner s = new Scanner(new File(args[0])); while(s.hasNext()){ lNumbers.add(Double.parseDouble(s.next())); } s.close(); //setup spark local //setMaster("local") can be added if not set on vm options SparkConf configuration = new SparkConf(true).setAppName("homework1.G32HM1"); JavaSparkContext sparkContext = new JavaSparkContext(configuration); //parallel collection JavaRDD<Double> dNumbers = sparkContext.parallelize(lNumbers); //finds and prints the maximum number using reduce method double maxNumberReduce = dNumbers.reduce(G32HM1::findMax); System.out.println("Reduce method: the max number is "+maxNumberReduce); //finds and prints the maximum number using max method double maxNumberMax = dNumbers.max(new valueComparator()); System.out.println("Max method: the max number is "+maxNumberMax); //find the min value used for normalization double minNumberMin = dNumbers.min(new valueComparator()); //creates a RDD of normalized numbers JavaRDD<Double> dNormalized = dNumbers.map(x -> (x-minNumberMin)/(maxNumberMax-minNumberMin)); /* The following code compute and print mean value of the RDD dNormalized */ //count how many elements contains long count = dNormalized.count(); // I could use this but instead lets use the collect method // double sum = dNormalized.reduce((x,y) -> x+y); //sum the value of all elements double sum = 0; List<Double> lNormalized = dNormalized.collect(); for(Double listElement: lNormalized){ sum += listElement; } //compute the mean value double mean = sum/count; System.out.println("The mean value is: "+mean); } }
package com.kil; import javafx.geometry.Point2D; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Getter public class CityNode { private Point2D point; @Setter private Point2D finPoint; private String cityName; private double Umax1; // private double Umax2; // private double Umax3; // private double Umax4; private double frequency; private double nominalPower_Re; private double nominalPower_Im; public CityNode(String cityName, double x_coord, double y_coord, double nominalPower_Re, double nominalPower_Im, double Umax1, double frequency) { this.point = new Point2D(x_coord,y_coord); finPoint = point; //always this.cityName = cityName; //window this.nominalPower_Re = nominalPower_Re; this.nominalPower_Im = nominalPower_Im; this.frequency = frequency; this.Umax1 = Umax1; // this.Umax2 = Umax2; // this.Umax3 = Umax3; // this.Umax4 = Umax4; } public List getInfo(){ List<String> list = new ArrayList<>(); if(!Logic.worldCoord) list.add(point.getX() + " : " + point.getY()); else list.add(Logic.coordConvert.newCoordsByIndex(Logic.nodeList.indexOf(this))); list.add("S nom " + nominalPower_Re + " + " + nominalPower_Im + "i"); list.add("f " + frequency); list.add("V fact: " + Umax1); // list.add("V fact 2: " + Umax1); // list.add("V fact 3: " + Umax1); // list.add("V fact 4: " + Umax1); return list; } }
package hashTable; import java.util.*; public class Programmars_4 { public static void main(String[] args){ String[] genres = {"classic", "pop", "classic", "classic", "pop", "zazz", "zazz"}; int[] plays = {500, 600, 150, 800, 2500, 2000, 6000}; HashMap<String, int[]> map = new HashMap<>(); HashMap<String, Integer> total = new HashMap<>(); for(int i=0; i < genres.length; i++){ String key = genres[i]; if(!map.containsKey(key)){ int[] init = {i, -1}; map.put(key, init); } else { int play = plays[i]; int input_index = i; int[] val = map.get(key); for(int j=0; j < val.length; j++){ int current_index = val[j]; if(current_index == -1){ val[j] = input_index; break; } if(play > plays[val[j]]){ play = plays[current_index]; int temp = val[j]; val[j] = input_index; input_index = temp; } } } total.put(key, total.getOrDefault(key, 0) + plays[i]); } // Total 정렬 List<Map.Entry<String, Integer>> entries = new ArrayList<>(total.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } }); for(HashMap.Entry<String, Integer> entry : entries){ System.out.println(entry.getKey() + " : " + entry.getValue()); } ArrayList<Integer> arrayList = new ArrayList<>(); for(HashMap.Entry<String, Integer> entry : entries){ int arr[] = map.get(entry.getKey()); for(int val : arr){ if(val != -1){ arrayList.add(val); } } } int[] answer = new int[arrayList.size()]; for(int i=0; i < arrayList.size(); i++){ answer[i] = arrayList.get(i); System.out.print(answer[i] + ", "); } } }
package Disciplina; public class CadastroDisciplina { }
package za.ac.cput.Repository; import java.util.List; public interface IRepository<T, ID> { public T create(T t); public T read(ID id); public T update(T t); public boolean delete(ID id); }
package atm.simulation; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class ATMPanel extends JPanel { private JButton btShowLog; public static final int DISPLAYABLE_LINES = 9; public static final String BLANK_DISPLAY_LINE = " t "; public ATMPanel(final GUI gui, SimCardReader cardReader, SimOperator operatorPanel, SimDisplay display, SimKeyboardDigital keyboardDigital, SimulationPrinter printer) { setLayout(new BorderLayout()); JPanel panelTop = new JPanel(); panelTop.setLayout(new FlowLayout()); ButtonChoose bt = new ButtonChoose(); bt.setPreferredSize(new Dimension(80, 240)); panelTop.add(bt, FlowLayout.LEFT); SimDisplay panelDisplay = new SimDisplay(); panelTop.add(panelDisplay, FlowLayout.CENTER); ButtonChoose bt1 = new ButtonChoose(); bt1.setPreferredSize(new Dimension(80, 250)); panelTop.add(bt1, FlowLayout.RIGHT); add(panelTop, BorderLayout.PAGE_START); JPanel panelCenter = new JPanel(); panelCenter.setPreferredSize(new Dimension(200, 150)); SimKeyboardDigital keyBoard = new SimKeyboardDigital(); panelCenter.add(keyBoard); SimCardReader simCardReader = new SimCardReader(); panelCenter.add(simCardReader); add(panelCenter); JPanel panelBottom = new JPanel(); panelBottom.setBackground(new Color(128, 128, 255)); btShowLog = new JButton("Show Log"); btShowLog.setPreferredSize(new Dimension(100, 30)); btShowLog.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gui.showCard("LOG"); } }); panelBottom.add(btShowLog); operatorPanel.setPreferredSize(new Dimension(510, 30)); panelBottom.add(operatorPanel); add(panelBottom, BorderLayout.PAGE_END); } }
package com.sietecerouno.atlantetransportador.utils; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.sietecerouno.atlantetransportador.R; import com.sietecerouno.atlantetransportador.manager.Manager; import com.sietecerouno.atlantetransportador.sections.DocumentWhitPhotoActivity; import com.squareup.picasso.Picasso; /** * A simple {@link Fragment} subclass. */ public class ContainerImageFragment extends Fragment { private String title; private int page; public ContainerImageFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); page = getArguments().getInt("someInt", 0); title = getArguments().getString("someTitle"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_container_image, container, false); ImageView img = (ImageView) view.findViewById(R.id.img); Picasso.with(getActivity()) .load(title) .into(img); return view; } // newInstance constructor for creating fragment with arguments public static ContainerImageFragment newInstance(int page, String title) { ContainerImageFragment fragmentFirst = new ContainerImageFragment(); Bundle args = new Bundle(); args.putInt("someInt", page); args.putString("someTitle", title); fragmentFirst.setArguments(args); return fragmentFirst; } }
/* * Copyright © 2016, 2018 IBM Corp. All rights reserved. * * 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.ibm.cloudant.kafka.common; public class MessageKey { public static final String CONFIGURATION_EXCEPTION = "ConfigurationException"; public static final String READ_CLOUDANT_STREAM_ERROR = "ReadCloudantStreamError"; public static final String CLOUDANT_DATABASE_ERROR = "CloudantDatabaseError"; public static final String STREAM_CLOSED_ERROR = "ClosedStreamError"; public static final String STREAM_TERMINATE_ERROR = "TerminateStreamError"; public static final String CLOUDANT_CONNECTION_URL_DOC = "CloudantConnectUrlDoc"; public static final String CLOUDANT_CONNECTION_USR_DOC = "CloudantConnectUsrDoc"; public static final String CLOUDANT_CONNECTION_PWD_DOC ="CloudantConnectPwdDoc"; public static final String CLOUDANT_LAST_SEQ_NUM_DOC = "CloudantLastSeqNumDoc"; public static final String CLOUDANT_CONNECTION_URL_DISP = "CloudantConnectUrlDisp"; public static final String CLOUDANT_CONNECTION_USR_DISP = "CloudantConnectUsrDisp"; public static final String CLOUDANT_CONNECTION_PWD_DISP = "CloudantConnectPwdDisp"; public static final String CLOUDANT_LAST_SEQ_NUM_DISP = "CloudantLastSeqNumDisp"; public static final String CLOUDANT_LIMITATION = "CloudantLimitation"; public static final String KAFKA_TOPIC_LIST_DOC = "KafkaTopicListDoc"; public static final String KAFKA_TOPIC_LIST_DISP = "KafkaTopicListDisp"; public static final String CLOUDANT_OMIT_DDOC_DISP = "CloudantOmitDDocDisp"; public static final String CLOUDANT_OMIT_DDOC_DOC = "CloudantOmitDDocDoc"; public static final String CLOUDANT_STRUCT_SCHEMA_DISP = "CloudantSchemaDisp"; public static final String CLOUDANT_STRUCT_SCHEMA_DOC = "CloudantSchemaDoc"; public static final String CLOUDANT_STRUCT_SCHEMA_FLATTEN_DISP = "CloudantSchemaFlattenDisp"; public static final String CLOUDANT_STRUCT_SCHEMA_FLATTEN_DOC = "CloudantSchemaFlattenDoc"; public static final String CLOUDANT_STRUCT_SCHEMA_JSON_ELEMENT = "CloudantSchemaUnknownJsonElement"; public static final String CLOUDANT_STRUCT_SCHEMA_JSON_PRIMITIVE = "CloudantSchemaUnknownJsonPrimitive"; public static final String CLOUDANT_STRUCT_SCHEMA_JSON_MIXED_ARRAY = "CloudantSchemaMixedArrays"; public static final String GUID_SCHEMA = "GuidSchema"; }
package demo.li.opal.uidemo.nestedRecycler.holder; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import demo.li.opal.uidemo.R; public class FeedsFootVH extends RecyclerView.ViewHolder { public TextView tips; public ImageView loading; public FeedsFootVH(View itemView) { super(itemView); tips = (TextView) itemView.findViewById(R.id.tips); loading = (ImageView) itemView.findViewById(R.id.loading); } }
/* * Copyright (c) 2018 Baidu, Inc. All Rights Reserved. * * 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.yy.lite.brpc.namming.s2s; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baidu.brpc.client.instance.ServiceInstance; import com.baidu.brpc.naming.*; import com.google.common.collect.Sets; import com.yy.common.hostinfo.bean.ServerInfo; import com.yy.common.hostinfo.bean.ServiceInstanceTag; import com.yy.common.hostinfo.utils.ServerUtil; import com.yy.ent.client.s2s.constants.S2SEnvBuilder; import com.yy.ent.clients.daemon.DaemonConfig; import com.yy.ent.clients.s2s.S2SCallback; import com.yy.ent.clients.s2s.S2SClient; import com.yy.ent.clients.s2s.S2SMeta; import com.yy.ent.clients.s2s.SubFilter; import com.yy.ent.clients.s2s.codec.S2SEntData; import com.yy.ent.clients.s2s.util.IpUtils; import com.yy.lite.brpc.namming.s2s.annotation.S2SNamming; import com.yy.lite.brpc.namming.s2s.base.ProtocolType; import com.yy.lite.brpc.namming.s2s.base.S2sDaemonClient; import com.yy.lite.brpc.namming.s2s.base.S2sService; import com.yy.lite.brpc.namming.s2s.base.S2sSignalHandler; import io.netty.util.Timer; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class S2sNamingService implements NamingService { private final static Logger logger = LoggerFactory.getLogger(S2sNamingService.class); private static final String SPLIT = ":"; private static String DEFAULT_REGISTER; private Map<String, Map<String, Map<String, String>>> servCacheMap = new ConcurrentHashMap<>(); private final ConcurrentMap<ServiceInstance, Map<String, List<ServiceInstance>>> notified = new ConcurrentHashMap<ServiceInstance, Map<String, List<ServiceInstance>>>(); protected BrpcURL url; private int retryInterval; private Timer timer; private S2sDaemonClient daemonClient; private String s2sName = ""; private String accessKey = ""; private String protocol = "yyp"; private boolean toRegister = true; private boolean hasRegister = false; private Set<String> subscribedSet = new HashSet<>(); private volatile Set<ServiceInstance> serviceInstancesCache = new HashSet<>(); public S2sNamingService(BrpcURL url) { this.retryInterval = url.getIntParameter(Constants.INTERVAL, Constants.DEFAULT_INTERVAL); this.s2sName = url.getStringParameter("accessAccount", ""); this.accessKey = url.getStringParameter("accessKey", ""); this.protocol = url.getStringParameter("protocol", ProtocolType.YYP.getCode()); this.toRegister = url.getStringParameter("toRegister","true").equals("true"); logger.info("init:" + JSONObject.toJSONString(url)); if (StringUtils.isBlank(s2sName)) { throw new IllegalStateException("s2s accessName is not blank"); } if (StringUtils.isBlank(accessKey)) { throw new IllegalStateException("s2s accessKey is not blank"); } DaemonConfig config = new DaemonConfig(); config.setAccessAccount(s2sName); config.setAccessKey(accessKey); config.setReadyTime(1000); config.setEnableIntranet("true"); try { daemonClient = S2sService.init(config); //最后一个s2s注册中心作为客户端注册中心, 在多s2s注册中心时有用 DEFAULT_REGISTER = s2sName; } catch (Exception e) { logger.error("init s2s client error", e); throw new IllegalStateException(e); } } @Override public List<ServiceInstance> lookup(SubscribeInfo subscribeInfo) { return new ArrayList<ServiceInstance>(); } @Override public void subscribe(SubscribeInfo subscribeInfo, final NotifyListener listener) { logger.info("subscribe:" + JSONObject.toJSONString(subscribeInfo)); //只需要一个s2s注册中心,进行订阅服务 if (!s2sName.equals(DEFAULT_REGISTER)) { logger.info(s2sName + " is not default register,do nothing."); return; } String servName = subscribeInfo.getServiceId(); S2SNamming s2SNamming = getAnnationByClass(subscribeInfo.getInterfaceName(), S2SNamming.class); if(s2SNamming!=null && StringUtils.isNotBlank(s2SNamming.name())){ servName = s2SNamming.name(); } final String serverNameFinal = servName; String servProtocol = protocol; ProtocolType protocolType = ProtocolType.create(protocol); if (protocolType == null) { throw new RuntimeException("protocol is unsupported. serverName:" + servName + ",protocol:" + servProtocol); } if (subscribedSet.contains(servName)) { logger.info(servName + " s2s name has bean already subscribed."); return; } //客户端 S2SEnvBuilder builder = new S2SEnvBuilder(); builder.setMetaServer(daemonClient.getConfig().getMetaServer()); S2SClient client = new S2SClient(new S2SCallback() { @Override public void onAdd(S2SMeta meta) {//do nothing } @Override public void onBind() {//never happen } @Override public void onRefresh(S2SMeta[] metas) { // 刷新 List<ServiceInstance> currentServiceList = getURLListFromS2s(metas, "listener", protocolType); Set<ServiceInstance> currentServiceSet = Sets.newHashSet(currentServiceList); Set<ServiceInstance> addList = Sets.difference(currentServiceSet,serviceInstancesCache); Set<ServiceInstance> deleteList = Sets.difference(serviceInstancesCache,currentServiceSet); logger.info("{}:s2slist:currentServiceList:{}",serverNameFinal,currentServiceList); logger.info("{}:s2slist:serviceInstancesCache:{}",serverNameFinal,serviceInstancesCache); logger.info("{}:s2slist:addList:{}",serverNameFinal,addList); logger.info("{}:s2slist:deleteList:{}",serverNameFinal,deleteList); listener.notify(addList, deleteList); serviceInstancesCache = currentServiceSet; logger.info("{}:s2slist:after_serviceInstancesCache:{}",serverNameFinal,serviceInstancesCache); } @Override public void onRemove(S2SMeta meta) { //do nothing } }, builder); client.initialize(daemonClient.getConfig().getAccessAccount(), daemonClient.getConfig().getAccessKey()); List<SubFilter> subFilters = new ArrayList<>(); SubFilter subFilter = new SubFilter(); subFilter.setInterestedName(servName); subFilters.add(subFilter); client.subscribe(subFilters); synchronized (this) { subscribedSet.add(servName); } List<S2SMeta> list = client.getServicesByName(servName); if (list == null || list.isEmpty()) { try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); list = client.getServicesByName(servName); if (list != null && !list.isEmpty()) { break; } } } catch (InterruptedException e) { logger.error("client.getServicesByName error", e); } } if (CollectionUtils.isNotEmpty(list)) { S2SMeta[] result = new S2SMeta[list.size()]; list.toArray(result); // 刷新 List<ServiceInstance> addList = getURLListFromS2s(result, "direct", protocolType); List<ServiceInstance> deleteList = new ArrayList<>(); listener.notify(addList, deleteList); // serviceInstancesCache = addList ; } else { logger.info("get service from s2s is empty"); } } @Override public void unsubscribe(SubscribeInfo subscribeInfo) { logger.info("unsubscribe:" + JSONObject.toJSONString(subscribeInfo)); } @Override public void register(RegisterInfo registerInfo) { if(!this.toRegister){ logger.info("s2sName={} not to register ",this.s2sName); return ; } logger.info("register:" + JSONObject.toJSONString(url)); ProtocolType protocolType = ProtocolType.create(protocol); if (protocolType == null) { throw new RuntimeException("protocol is unsupported. protocol:" + protocol); } if (daemonClient == null) { throw new RuntimeException("s2s client is null.s2sName:" + s2sName); } Map<Integer, Integer> protocolMap = new HashMap<>(); int port = registerInfo.getPort(); protocolMap.put(protocolType.getVal(), port); if (!hasRegister) { ServerInfo serverInfo = ServerUtil.getServerInfoByHostInfo(); Map<String, Object> extMap = new HashMap<>(8); extMap.put("areaId", serverInfo.getAreaId()); extMap.put("regionId", serverInfo.getRegionId()); extMap.put("roomId", serverInfo.getRoomId()); daemonClient.registerToDaemon(protocolType, port, daemonClient.getConfig().getGroupId(), protocolMap, extMap); //注册新号,用于优雅停机 new S2sSignalHandler(daemonClient).registerSignal(); hasRegister = true; logger.info(String.format("interface[%s],protocal[%s],port[%s],s2sName[%s] do s2s register.", accessKey, protocol, port, s2sName)); } else { logger.info(String.format("interface[%s],protocal[%s],port[%s],s2sName[%s] had been register.", accessKey, protocol, port, s2sName)); } } @Override public void unregister(RegisterInfo registerInfo) { logger.info("unregister:" + JSONObject.toJSONString(url)); } private List<ServiceInstance> getURLListFromS2s(S2SMeta[] metas, String tag, ProtocolType protocolType) { List<ServiceInstance> result = new ArrayList<ServiceInstance>(); for (S2SMeta meta : metas) { logger.info("====================fresh start " + tag + "========================"); String servName = meta.getName(); if (servName != null && !"".equals(servName.trim())) { S2SEntData s2sEntData = S2SEntData.readFromByteArray(meta.getData()); Integer port = null; if (s2sEntData.getProtocol() != null && !s2sEntData.getProtocol().isEmpty()) { //兼容anka等一个s2sName 多种协议 port = s2sEntData.getProtocol().get(protocolType.getVal()); } //新框架使用tcp_port port = port == null ? s2sEntData.getTcp_port() : port; if (port == null || port == 0) { logger.info(servName + " not found available port."); } if (s2sEntData.getIpList() == null || s2sEntData.getIpList().isEmpty()) { continue; } Object setid = null; Map<String, Map<String, String>> ipMap = servCacheMap.computeIfAbsent(servName, k -> new ConcurrentHashMap<>()); for (Integer ipType : s2sEntData.getIpList().keySet()) { Long ip = s2sEntData.getIpList().get(ipType); String ipStr = IpUtils.longToIp(ip); if ("127.0.0.1".equals(ipStr)) { continue; } if (0 == meta.getMetaStatus()) { //新加入服务器 Map<String, String> infoMap = new HashMap<>(); ServiceInstanceTag tagInfo = new ServiceInstanceTag(); tagInfo.setIspId(ipType); tagInfo.setGroupId(meta.getGroupId()); int roomId = 0; int areaId = 0; int regionId = 0; if (s2sEntData.getParamMap() != null && s2sEntData.getParamMap().containsKey("roomId")) { roomId = (int) s2sEntData.getParamMap().get("roomId"); } if (s2sEntData.getParamMap() != null && s2sEntData.getParamMap().containsKey("areaId")) { areaId = (int) s2sEntData.getParamMap().get("areaId"); } if (s2sEntData.getParamMap() != null && s2sEntData.getParamMap().containsKey("regionId")) { regionId = (int) s2sEntData.getParamMap().get("regionId"); } tagInfo.setRoomId(roomId); tagInfo.setAreaId(areaId); tagInfo.setRegionId(regionId); infoMap.put("tagInfo", JSON.toJSONString(tagInfo)); ipMap.put(ipStr + SPLIT + port, infoMap); logger.info(String.format("subscribe service[add], name %s, port %s, ip %s, group %s, setid %s, time %s", servName, port, ipStr, meta.getGroupId(), setid, meta.getTimestamp())); } else if (1 == meta.getMetaStatus()) { //要移除的服务器 ipMap.remove(ipStr + SPLIT + port); logger.info(String.format("subscribe service[remove], name %s, port %s, ip %s, group %s, setid %s, time %s", servName, port, ipStr, meta.getGroupId(), setid, meta.getTimestamp())); } else { logger.info("unknow status[" + servName + "],status:" + meta.getMetaStatus() + "========================"); } } for (String key : ipMap.keySet()) { Map<String, String> value = ipMap.get(key); if (value == null) { continue; } String[] ipInfo = key.split(SPLIT); ServiceInstance serviceInstance = new ServiceInstance(); serviceInstance.setIp(ipInfo[0]); serviceInstance.setPort(NumberUtils.toInt(ipInfo[1])); serviceInstance.setTag(value.get("tagInfo")); logger.info(servName + ",serviceInstance:" + serviceInstance); result.add(serviceInstance); } } } logger.info("====================fresh end " + tag + "========================"); return result; } private <A extends Annotation> A getAnnationByClass(String clazz, Class<A> annation){ if(StringUtils.isBlank(clazz) || annation==null){ return null; } try{ return Thread.currentThread().getContextClassLoader().loadClass(clazz).getAnnotation(annation); }catch (Exception e){ return null; } } }
package com.google.android.exoplayer2.a; import com.google.android.exoplayer2.a.e.a; import com.google.android.exoplayer2.b.d; class e$a$5 implements Runnable { final /* synthetic */ a afE; final /* synthetic */ d afM; e$a$5(a aVar, d dVar) { this.afE = aVar; this.afM = dVar; } public final void run() { this.afM.jC(); this.afE.afC.d(this.afM); } }
package com.root.mssm.ui.sellonmssm.home; import androidx.lifecycle.ViewModel; public class SellerHomeViewModel extends ViewModel { // TODO: Implement the ViewModel }
package sampleRestControllers; import com.catasys.dfappl.dfapplmasterstatusservice.exception.MasterStatusNotFoundException; import com.catasys.dfappl.dfapplmasterstatusservice.model.entity.MemberStatus; import com.catasys.dfappl.dfapplmasterstatusservice.model.entity.OnTrakMember; import com.catasys.dfappl.dfapplmasterstatusservice.model.entity.PatientsFHIR; import com.catasys.dfappl.dfapplmasterstatusservice.model.entity.structure.GenericResponse; import com.catasys.dfappl.dfapplmasterstatusservice.model.entity.structure.PatchOperation; import com.catasys.dfappl.dfapplmasterstatusservice.repository.OnTrakMemberRepository; import com.catasys.dfappl.dfapplmasterstatusservice.repository.PatientsFHIRRepository; import com.catasys.dfappl.dfapplmasterstatusservice.service.interfaces.MasterStatusService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.List; import static com.catasys.dfappl.dfapplmasterstatusservice.model.consts.ServiceConst.PATIENTMONGOID; import static com.catasys.dfappl.dfapplmasterstatusservice.model.consts.ServiceConst.EREHABID; @RestController @Valid @RequestMapping("/v1/masterstatus") public class Rest_100_MasterStatusController { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private PatientsFHIRRepository patientsFHIRRepository; @Autowired private OnTrakMemberRepository onTrakMemberRepository; @Autowired private MasterStatusService masterStatusService; @ApiOperation(value = "Get All Member Status", response = List.class) @RequestMapping(method = RequestMethod.GET) public List<OnTrakMember> getAllOnTrakMembers( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName ) { log.debug("getAllOnTrakMembers() start"); Long secondsStart = System.currentTimeMillis() / 1000; List<OnTrakMember> onTrakMembers = onTrakMemberRepository.findAll(); if (onTrakMembers != null) { Long secondsEnd = System.currentTimeMillis() / 1000; log.debug("getAllOnTrakMembers() end took [" + (secondsEnd - secondsStart) + "] secs for [" + onTrakMembers.size() + "]"); return onTrakMembers; } else { throw new MasterStatusNotFoundException("No ontrakMembers found"); } } @ApiOperation(value = "Get onTrakMember by eRehabId or patientMongoId", response = MemberStatus.class) @RequestMapping(value = ("/{id}"), method = RequestMethod.GET) public OnTrakMember getOnTrakMember( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName, @ApiParam(value = "MemId") @PathVariable(value = "id") String id, @ApiParam(value = "MemId Type") @RequestParam(value = "idType", required = false) String idType ) { log.debug("getOnTrakMember() start"); Long secondsStart = System.currentTimeMillis() / 1000; OnTrakMember onTrakMember = null; PatientsFHIR patientsFHIR; if ((id != null && idType == null) || idType != null && idType.equalsIgnoreCase(EREHABID)) { patientsFHIR = patientsFHIRRepository.findFirstByIdentifierValue(id); if (patientsFHIR != null) { onTrakMember = onTrakMemberRepository.findFirstByMemberReference(patientsFHIR.get_id().toString()); } else { log.error("Patient with eRehabId [ {}] not found", id); throw new MasterStatusNotFoundException("Patient with eRehabId [" + id + "] not found"); } } else if (idType != null && idType.equalsIgnoreCase(PATIENTMONGOID)) { onTrakMember = onTrakMemberRepository.findFirstByMemberReference(id); } if (onTrakMember != null) { Long secondsEnd = System.currentTimeMillis() / 1000; log.debug("getOnTrakMember() end took [{}] secs", secondsEnd - secondsStart); return onTrakMember; } else { log.error("Patient with eRehabId or patientMongoId [ {}] not found", id); throw new MasterStatusNotFoundException("onTrakMember for eRehabId or patientMongoId [" + id + "] is not found"); } } @ApiOperation(value = "Create OnTrakMember Master Status", response = MemberStatus.class) @RequestMapping(value = "/{eRehabId}", method = RequestMethod.POST) public OnTrakMember createOnTrakMember( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName, @ApiParam(value = "Patient's dRehabId") @PathVariable("eRehabId") @NotNull String eRehabId, @ApiParam(value = "Member Status Body") @RequestBody @NotNull MemberStatus memberStatus ) { log.info("createOnTrakMember() called"); OnTrakMember onTrakMember = masterStatusService.createOnTrakMember(eRehabId, memberStatus); log.debug("onTrakMember = " + onTrakMember); log.info("createOnTrakMember() completed"); return onTrakMember; } @ApiOperation(value = "PATCH Update OnTrak Member info", response = List.class, produces = "application/json") @RequestMapping(method = RequestMethod.PATCH) public List<GenericResponse> updateOnTrakMemberPatch( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName, @ApiParam(value = "Patient's id") @RequestParam("id") @NotNull String id, @ApiParam(value = "Patch Request Body") @RequestBody @NotNull PatchOperation patchRequest ) { log.debug("updateOnTrakMemberPatch() called"); List<GenericResponse> responseList = masterStatusService.updateOnTrakMemberPatch(patchRequest); log.debug("responseList = " + responseList); log.debug("updateOnTrakMemberPatch() completed"); return responseList; } @ApiOperation(value = "Update OnTrak Member Master Status", response = MemberStatus.class) @RequestMapping(value = "/{eRehabId}", method = RequestMethod.PUT) public OnTrakMember updateOnTrakMember( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName, @ApiParam(value = "Patient's dRehabId") @PathVariable("eRehabId") @NotNull String eRehabId, @ApiParam(value = "Member Status Body") @RequestBody @NotNull MemberStatus memberStatus ) { log.debug("updateMemberStatus() start"); OnTrakMember onTrakMember = masterStatusService.updateOnTrakMember(eRehabId, memberStatus); return onTrakMember; } @ApiOperation(value = "Delete Member Status", response = ResponseEntity.class) @RequestMapping(value = "/{eRehabId}", method = RequestMethod.DELETE) public ResponseEntity<?> deleteOnTrakMember( @ApiParam(value = "User Name") @RequestParam(value = "userName", required = true) String userName, @ApiParam(value = "Patient's dRehabId") @PathVariable("eRehabId") @NotNull String eRehabId ) { log.debug("deleteOnTrakMember() start"); Long secondsStart = System.currentTimeMillis() / 1000; OnTrakMember onTrakMember; PatientsFHIR patientsFHIR = patientsFHIRRepository.findFirstByIdentifierValue(eRehabId); if (patientsFHIR != null) { onTrakMember = onTrakMemberRepository.findFirstByMemberReference(patientsFHIR.get_id().toString()); if (onTrakMember != null) { onTrakMemberRepository.delete(onTrakMember); Long secondsEnd = System.currentTimeMillis() / 1000; log.debug("deleteOnTrakMember() end took [" + (secondsEnd - secondsStart) + "] secs"); return ResponseEntity.ok().build(); } else { log.error("OnTrakMember Master Status for eRehabId [" + eRehabId + "] is not found"); throw new MasterStatusNotFoundException("OnTrakMember Master Status for eRehabId [" + eRehabId + "] is not found"); } } else { log.error("Patient with eRehabId [" + eRehabId + "] not found"); throw new MasterStatusNotFoundException("Patient with eRehabId [" + eRehabId + "] not found"); } } }
package cn.canlnac.onlinecourse.domain.repository; import java.util.Map; import cn.canlnac.onlinecourse.domain.Answer; import cn.canlnac.onlinecourse.domain.Catalog; import cn.canlnac.onlinecourse.domain.DocumentList; import cn.canlnac.onlinecourse.domain.LearnRecord; import cn.canlnac.onlinecourse.domain.QuestionList; import rx.Observable; /** * 目录接口. */ public interface CatalogRepository { /** 获取目录 */ Observable<Catalog> getCatalog(int catalogId); /** 修改目录 */ Observable<Void> updateCatalog(int catalogId, Map<String,Object> catalog); /** 删除目录 */ Observable<Void> deleteCatalog(int catalogId); /** 创建小测 */ Observable<Integer> createQuestion(int catalogId, Map<String,Object> question); /** 更新小测 */ Observable<Void> updateQuestion(int catalogId, Map<String,Object> question); /** 删除小测 */ Observable<Void> deleteQuestion(int catalogId); /** 获取小测 */ Observable<QuestionList> getQuestion(int catalogId); /** 获取学习记录 */ Observable<LearnRecord> getLearnRecord(int catalogId); /** 创建学习记录 */ Observable<Integer> createLearnRecord(int catalogId, Map<String,Object> learnRecord); /** 更新学习记录 */ Observable<Void> updateLearnRecord(int catalogId, Map<String,Object> learnRecord); /** 创建文档 */ Observable<Integer> createDocumentInCatalog(int catalogId, Map<String,Object> document); /** 文档列表 */ Observable<DocumentList> getDocumentsInCatalog(int catalogId, Integer start, Integer count, String sort); /** 获取章节下的回答 */ Observable<Answer> getAnswer(int catalogId); /** 创建回答 */ Observable<Integer> createAnser(int catalogId, Map<String,Object> answer); }
package com.ani.lambda.chaining; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ChainingConsumer { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>( List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 34, 34, 3, 23, 34, 45, 67, 784, 43, 234)); Consumer<Integer> printNumber = i -> System.out.print(i + " "); Consumer<Integer> printDoubleOfNumber = i -> System.out.println(i * 2); // For Consumer andThen provides chaining. // It means you can chain as many consumer as you want e.g. // c1.andThen(c2).andThen(c3).andThen(c4)... and so on. list.forEach(printNumber.andThen(printDoubleOfNumber)); } }