text
stringlengths 10
2.72M
|
|---|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Executor {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Assignement : Sort the Array
Arrays sort = new Arrays();
int arr[]= {20,15,13,9,5,1};
int resarr[] = sort.bubbleSort(arr);
System.out.println("Find Min and Max of an Array ");
for (int counter =0; counter< resarr.length; counter++)
{
System.out.print( resarr[counter] + " " );
}
// Find min and Max of an Array
int minmaxarr[]= {20,15,13,9,5,1};
int arrres[] ;
int arrRes[]= sort.FindMinMax(minmaxarr);
System.out.println(" ");
System.out.println("Find Min and Max of an Array ");
System.out.println("The min number from the Array is : " + arrRes[0]);
System.out.println(" The Max number from the Array is : " + arrRes[1]);
//Program to Print a Binary Triangle
System.out.println("Create the Binary Tree");
BinaryTriangle binT = new BinaryTriangle();
binT.CreateBinaryTriangle( 6);
// Write a programin C# Sharp to separate odd and even integers in separate arrays
int evenodd[]= {20,15,13,9,5,1};
sort.EvenOddArray(arr);
//3.Find the Frequency of the Word “the” in a given Sentence
StringFunctions sf = new StringFunctions();
sf.FindWordFrequency();
sf.FindCharWordLineCount();
}
}
|
/*
* Copyright (c) 2011-2020 HERE Global B.V. and its affiliate(s).
* All rights reserved.
* The use of this software is conditional upon having a separate agreement
* with a HERE company for the use or utilization of this software. In the
* absence of such agreement, the use of the software is not allowed.
*/
package com.here.hellomap;
//import android.support.v7.app.AppCompatActivity;
//import android.os.Bundle;
//import android.view.Menu;
//import android.view.MenuItem;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.here.android.mpa.common.CopyrightLogoPosition;
import com.here.android.mpa.common.GeoCoordinate;
import com.here.android.mpa.common.Image;
import com.here.android.mpa.common.OnEngineInitListener;
import com.here.android.mpa.mapping.AndroidXMapFragment;
import com.here.android.mpa.mapping.Map;
import com.here.android.mpa.mapping.MapMarker;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BasicMapActivity extends FragmentActivity implements LayersAdapter.ItemListener {
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private Map map = null;
private AndroidXMapFragment mapFragment = null;
private LocationManager locationManager;
private Dialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
checkPermissions();
//Dağlar dağlar
//Hi Uğur naber2
}
private AndroidXMapFragment getMapFragment() {
return (AndroidXMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}
@SuppressWarnings("deprecation")
private void initialize(final Location lct) {
setContentView(R.layout.activity_main);
// Search for the map fragment to finish setup by calling init().
mapFragment = getMapFragment();
// Set up disk cache path for the map service for this application
boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(
getApplicationContext().getExternalFilesDir(null) + File.separator + ".here-maps");
if (!success) {
Toast.makeText(getApplicationContext(), "Unable to set isolated disk cache path.", Toast.LENGTH_LONG);
} else {
mapFragment.init(new OnEngineInitListener() {
@Override
public void onEngineInitializationCompleted(
final OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setCenter(new GeoCoordinate(lct.getLatitude(), lct.getLongitude(), 0.0),
Map.Animation.NONE);
try {
Image image = new Image();
image.setImageResource(R.drawable.ic_car);
MapMarker customMarker = new MapMarker(new GeoCoordinate(lct.getLatitude(), lct.getLongitude(), 0.0), image);
map.addMapObject(customMarker);
} catch (IOException e) {
e.printStackTrace();
}
// Set the zoom level to the average between min and max
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
Button btnZoomPositive = findViewById(R.id.btn_zoomPositive);
Button btnZoomNegative = findViewById(R.id.btn_zoomNegative);
mapFragment.setCopyrightLogoPosition(CopyrightLogoPosition.BOTTOM_LEFT);
btnZoomPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.setZoomLevel(map.getZoomLevel() * 1.06);
}
});
btnZoomNegative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.setZoomLevel(map.getZoomLevel() / 1.06);
}
});
Button btnMylocation = findViewById(R.id.btn_mylocation);
btnMylocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 1.7);
map.setCenter(new GeoCoordinate(lct.getLatitude(), lct.getLongitude(), 0.0), Map.Animation.NONE);
}
});
Button btnLayers = findViewById(R.id.btn_layer);
btnLayers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<String> schemes = map.getMapSchemes();
showDialog(schemes);
}
});
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(BasicMapActivity.this).setMessage(
"Error : " + error.name() + "\n\n" + error.getDetails())
.setTitle(R.string.engine_init_error)
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
finishAffinity();
}
}).create().show();
}
});
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void showDialog(List<String> layerList) {
dialog = new Dialog(BasicMapActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog_layers);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
RecyclerView rvLayers = dialog.findViewById(R.id.rv_layers);
ArrayList<Layer> newData = new ArrayList<>();
for (int i = 0; i < layerList.size(); i++) {
newData.add(new Layer(i, layerList.get(i)));
/* if(i==4){
newData.add(new Layer(i, "Uydu Görüntüsü"));
}*/
}
LayersAdapter adapter = new LayersAdapter(newData, getApplicationContext());
rvLayers.setAdapter(adapter);
adapter.setItemListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvLayers.setLayoutManager(linearLayoutManager);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location lct = getLastKnownLocation();
// all permissions were granted
initialize(lct);
break;
}
}
private Location getLastKnownLocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Location location = new Location("gps");
return location;
}
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
@Override
public void onItemClicked(Layer mainList, int position) {
List<String> schemes = map.getMapSchemes();
map.setMapScheme(schemes.get(mainList.getLayerID()));
dialog.dismiss();
}
}
|
package com.tencent.wecall.talkroom.model;
import com.tencent.pb.common.a.a;
import com.tencent.pb.talkroom.sdk.c;
class f$5 implements c {
final /* synthetic */ f vyi;
f$5(f fVar) {
this.vyi = fVar;
}
public final void V(byte[] bArr, int i) {
try {
if (f.l(this.vyi)) {
if (f.m(this.vyi)) {
for (int i2 = 0; i2 < bArr.length; i2++) {
bArr[i2] = (byte) 0;
}
}
if (f.l(this.vyi)) {
b c = f.c(this.vyi);
short s = (short) i;
if (a.vbD) {
c.vwZ.SendAudio(bArr, s, 0);
}
if (this.vyi.vxW) {
this.vyi.vxW = false;
com.tencent.pb.common.c.c.x("TalkRoomService", new Object[]{"onRecPcmDataCallBack len: ", Integer.valueOf(i)});
}
}
}
} catch (Exception e) {
com.tencent.pb.common.c.c.x("TalkRoomService", new Object[]{"initMediaComponent record", e});
}
}
}
|
public class AddMusicControl {
private DataManager dm;
public AddMusicControl(DataManager d) {
this.dm = d;
}
public void handleAddMusic(String title, String artist, String link) {
dm.addMusic(title, artist, link);
}
}
|
package net.sssanma.mc.web;
import org.json.simple.JSONObject;
public abstract class WebSocketAPIHandler {
public abstract void write(JSONObject jsonObject);
public abstract APIMethod getMethodType();
public enum APIMethod {
MESSAGE, JOIN, QUIT,
}
}
|
/*
* MIT License
*
* Copyright (c) 2020 Hasan Demirtaş
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package io.github.portlek.mapentry;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
/**
* an immutable {@link Map.Entry} implementation.
* <p>
* there is no thread-safety guarantee.
*
* @param <K> key type.
* @param <V> value type.
*/
public final class MapEntry<K, V> implements Map.Entry<K, V> {
/**
* the key.
*/
@NotNull
private final K key;
/**
* the value.
*/
@NotNull
private final V value;
/**
* ctor.
*
* @param key the key.
* @param value the value.
*/
private MapEntry(@NotNull final K key, @NotNull final V value) {
this.key = key;
this.value = value;
}
@NotNull
public static <K, V> Map.Entry<K, V> from(@NotNull final K key, @NotNull final V value) {
return new MapEntry<>(key, value);
}
@Override
public K getKey() {
return this.key;
}
@Override
public V getValue() {
return this.value;
}
@Override
public V setValue(@NotNull final V yvalue) {
throw new UnsupportedOperationException(this.getClass().getSimpleName() + " is an immutable class, you can't edit it!");
}
@Override
public int hashCode() {
return this.key.hashCode() ^ this.value.hashCode();
}
@Override
public boolean equals(final Object obj) {
return obj instanceof Map.Entry
&& ((Map.Entry<?, ?>) obj).getKey().equals(this.key)
&& ((Map.Entry<?, ?>) obj).getValue().equals(this.value);
}
@Override
public String toString() {
return this.key + "=" + this.value;
}
}
|
package com.techelevator;
import com.techelevator.SalaryWorker;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
public class SalaryWorkerTest {
@Test
public void weekly_pay_is_pay_divided_by_52() {
SalaryWorker test = new SalaryWorker("Jacob","Peralta",52000);
test.calculateWeeklyPay(40);
double pay = test.annualSalary/52;
//assertEquals with doubles is deprecated, is this good??
Assert.assertEquals((int)pay, (int)test.getAnnualSalary()/52);
}
}
|
import java.util.Scanner;
public class FBIAgentProgram {
/**
* @param args
*/
public static void main(String[] args) {
String[] names = {"Bowman","Walker","Christian","Edwards","Cummings","Halpern","Scott","Rhineheart","Haley","Brooks"};
String[] address = {"Canaan","Newark","Hardwick","Montgomery","Trenton","Liverpool","Sheridan","Houston","Westfield","Syosset"};
String[] state = {"CT","NJ","VT","AL","NJ","NY","WY","TX","NJ","NY"};
String[] sex = {"M","F","M","M","M","F","M","F","F","M"};
int[] age = {48, 39, 46, 71, 31, 38, 51, 62, 22, 32};
int[] salary = {18000, 27000, 59000, 78000, 25000, 45000, 19000, 91000, 33000, 40000};
int[] savings = {4200, 3600, 1900, 500, 7800, 12000, 400, 53200, 4700, 3900};
String[] Car = {"Saturn","Olds","Chev","Chev","Ford","Chev","Ford","Cad","Honda","Ford"};
int[] years = {1999, 2000, 2001, 2003, 2004, 2002, 2006, 2005, 2002, 2004};
int counter = 0;
int request;
Scanner keyboard = new Scanner(System.in);
System.out.println("Here are the cases ALL OF THEM");
System.out.println("_________________________" + "\n");
//request = keyboard.nextInt();
while (counter != 10)
{
if (Car[counter] == "Ford" && salary[counter] >= 20000 && age[counter] >=30)
{
System.out.println(names[counter] +" "+ address[counter]);
}
counter++;
}
System.out.println("End of Mr. Holmes case \n");
counter = 0;
while (counter != 10)
{
if (Car[counter] == "Ford" && savings[counter] <= 2000)
{
System.out.println(names[counter]);
}
if (Car[counter] == "Chev" && savings[counter] <= 2000)
{
System.out.println(names[counter]);
}
if (Car[counter] == "Honda" && savings[counter] <= 2000)
{
System.out.println(names[counter]);
}
counter++;
}
System.out.println("End of Colouseau's Case \n");
counter = 0;
while(counter != 10)
{
if (sex[counter] == "F")
{
System.out.println(names[counter] +" "+ Car[counter] +" "+ years[counter]);
}
counter++;
}
System.out.println("End of Simon's Case \n");
counter = 0;
while(counter != 10)
{
if (sex[counter] == "M" && age[counter] <= 35 && state[counter] == "NJ" && Car[counter] == "Ford")
{
System.out.println(names[counter]);
}
counter++;
}
System.out.println("End of the Pink Panther's Case");
System.out.println("Out");
}
}
|
package com.bridgelabz.user.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bridgelabz.user.service.UserDao;
/**
* Servlet Filter implementation class LoginFilter
*/
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
String uemail= req.getParameter("uemail");
String upwd= req.getParameter("upwd");
HttpSession s2=req.getSession();
RequestDispatcher rd=null;
if(uemail == null || upwd == null)
{
res.sendRedirect("login.jsp");
}
else
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
|
package ru.innopolis.mputilov.expression;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
/**
* Created by mputilov on 04.09.16.
*/
public class PrettyPrinter {
public void print(Expression expression) {
Document doc = expression.toXml();
try {
Transformer transformer = null;
transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
|
package com.kingdee.lightapp.domain.pubacc;
/**
* @since model为4时是应用消息模板的响应按钮 2015-7-15
* @author wang_kun
*/
public class PubaccMsgButton {
private String title; //消息标题
private String text; //消息摘要
/* event需要传入已下信息(URLENCODE utf-8编码):
String eventViewId 该id跟button上的id一致
String subAppDesc 按钮对应事件的访问url地址
String url
JSONObject reqData 参数
String reqType 请求url方式 get/post
String contentType 传参类型
boolean autoReply 是否需要自动回复
String appId 轻应用Id
*/
private String event;
private String url;
private int id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
package com.zzidc.web.lambda;
import org.junit.Test;
/**
* @ClassName LambdaTest
* @Author chenxue
* @Description TODO
* @Date 2019/4/1 15:01
**/
public class LambdaTest {
public void test(){
Converter<String,Integer> converter = new Converter<String, Integer>() {
@Override
public Integer conver(String from) {
return Integer.valueOf(from);
}
};
System.out.println(converter);
Converter<String,Integer> converter1 = (param)-> Integer.valueOf(param);
}
}
|
package com.example.stockspring.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.stockspring.dao.StockPriceDao;
import com.example.stockspring.model.StockPrice;
@Service
public class StockPriceServiceImpl implements StockPriceService {
@Autowired
StockPriceDao stockPriceDao;
public void insertStockPrice(StockPrice stockPrice) {
stockPriceDao.save(stockPrice);
}
public List<StockPrice> getStockPriceList() throws SQLException {
// TODO Auto-generated method stub
return stockPriceDao.findAll();
}
}
|
package com.pangpang6.books.guava.primitives;
import org.junit.Test;
import com.google.common.primitives.Doubles;
/**
* Created by jiangjiguang on 2017/12/16.
*/
public class DoublesTest {
@Test
public void compareTest(){
int r = Doubles.compare(2.0, 3.3);
System.out.println(r);
}
@Test
public void containsTest(){
double[] dd = new double[4];
dd[0] = 2.00;
boolean b = Doubles.contains(dd, 2.0);
System.out.println(b);
}
@Test
public void tryParseTest(){
Double d = Doubles.tryParse("3");
System.out.println(d);
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.activity.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import org.overlord.rtgov.activity.model.ActivityType;
import org.overlord.rtgov.activity.model.ActivityUnit;
import org.overlord.rtgov.activity.server.QuerySpec;
/**
* This class provides utility functions for the activity
* model.
*
*/
public final class ActivityUtil {
protected static final ObjectMapper MAPPER=new ObjectMapper();
private static final TypeReference<java.util.List<ActivityUnit>> ACTIVITY_UNIT_LIST=
new TypeReference<java.util.List<ActivityUnit>>() { };
private static final TypeReference<java.util.List<ActivityType>> ACTIVITY_TYPE_LIST=
new TypeReference<java.util.List<ActivityType>>() { };
private static ObjectWriter ATLIST_WRITER=null;
static {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
ATLIST_WRITER = MAPPER.writerWithType(ACTIVITY_TYPE_LIST);
}
/**
* Private constructor.
*/
private ActivityUtil() {
}
/**
* This method serializes an Activity event into a JSON representation.
*
* @param act The activity
* @return The JSON serialized representation
* @throws Exception Failed to serialize
*/
public static byte[] serializeActivityUnit(ActivityUnit act) throws Exception {
byte[] ret=null;
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
MAPPER.writeValue(baos, act);
ret = baos.toByteArray();
baos.close();
return (ret);
}
/**
* This method serializes a Query Spec into a JSON representation.
*
* @param qs The query spec
* @return The JSON serialized representation
* @throws Exception Failed to serialize
*/
public static byte[] serializeQuerySpec(QuerySpec qs) throws Exception {
byte[] ret=null;
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
MAPPER.writeValue(baos, qs);
ret = baos.toByteArray();
baos.close();
return (ret);
}
/**
* This method serializes an object into a JSON string representation.
*
* @param obj The object
* @return The JSON serialized string representation
* @throws Exception Failed to serialize
*/
public static String objectToJSONString(Object obj) throws Exception {
String ret=null;
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
MAPPER.writeValue(baos, obj);
ret = new String(baos.toByteArray());
baos.close();
return (ret);
}
/**
* This method serializes an ActivityUnit list into a JSON representation.
*
* @param activities The activity unit list
* @return The JSON serialized representation
* @throws Exception Failed to serialize
*/
public static byte[] serializeActivityUnitList(java.util.List<ActivityUnit> activities) throws Exception {
byte[] ret=null;
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
MAPPER.writeValue(baos, activities);
ret = baos.toByteArray();
baos.close();
return (ret);
}
/**
* This method serializes an ActivityType event list into a JSON representation.
*
* @param activities The activity type list
* @return The JSON serialized representation
* @throws Exception Failed to serialize
*/
public static byte[] serializeActivityTypeList(java.util.List<ActivityType> activities) throws Exception {
byte[] ret=null;
java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
ATLIST_WRITER.writeValue(baos, activities);
ret = baos.toByteArray();
baos.close();
return (ret);
}
/**
* This method deserializes an Activity event from a JSON representation.
*
* @param act The JSON representation of the activity
* @return The Activity event
* @throws Exception Failed to deserialize
*/
public static ActivityUnit deserializeActivityUnit(byte[] act) throws Exception {
ActivityUnit ret=null;
java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(act);
ret = MAPPER.readValue(bais, ActivityUnit.class);
bais.close();
return (ret);
}
/**
* This method deserializes a Query Spec from a JSON representation.
*
* @param qs The JSON representation of the query spec
* @return The query spec
* @throws Exception Failed to deserialize
*/
public static QuerySpec deserializeQuerySpec(byte[] qs) throws Exception {
QuerySpec ret=null;
java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(qs);
ret = MAPPER.readValue(bais, QuerySpec.class);
bais.close();
return (ret);
}
/**
* This method deserializes an Activity Unit list from a JSON representation.
*
* @param act The JSON representation of the activity
* @return The ActivityUnit event list
* @throws Exception Failed to deserialize
*/
public static java.util.List<ActivityUnit> deserializeActivityUnitList(byte[] act) throws Exception {
java.util.List<ActivityUnit> ret=null;
java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(act);
ret = MAPPER.readValue(bais, ACTIVITY_UNIT_LIST);
bais.close();
return (ret);
}
/**
* This method deserializes an ActivityType event list from a JSON representation.
*
* @param act The JSON representation of the activity
* @return The ActivityType event list
* @throws Exception Failed to deserialize
*/
public static java.util.List<ActivityType> deserializeActivityTypeList(byte[] act) throws Exception {
java.util.List<ActivityType> ret=null;
java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(act);
ret = MAPPER.readValue(bais, ACTIVITY_TYPE_LIST);
bais.close();
return (ret);
}
}
|
package room;
import java.util.Random;
import item.Book;
import item.Photocopier;
/**
* the library
* @author Dravet
*
*/
public class Library extends Room {
//boolean to know if the library is open
private boolean open = false;
//boolean to know if the cheat is in the photocopier
private boolean cheat = false;
private Photocopier photocopier = new Photocopier();
//constructor
public Library(String description) {
super(description);
}
/**
* method to add book in the library
* @param book a book
*/
public void addBook(Book book){
this.getListofitem().add(book);
}
/**
* initiate the library with 3 book
*
*/
public void initiate(){
this.addBook(new Book("Dora"));
this.addBook(new Book("Harry-Potter"));
this.addBook(new Book("POO"));
}
/**
* the command for the library
* @param commandWord the string's command
*/
public void command(String commandWord){
if(commandWord.equals("seephotocopier") ) {
cheat();
}
}
/**
* the method to cheat : if cheat is true, the photocopier have some cheat , else there is nothing
*/
private void cheat() {
if(this.cheat==true){
this.addBook(photocopier.getCheat());
System.out.println("you see the Exam Answer\n");
System.out.println(""+this.descriptionofitem());
}else{
System.out.println("there is nothing here");
}
}
/**
* update the room each time the player enter in the library for the cheat in the photocopier
*/
public void update(){
int random = new Random().nextInt(5);
if(random == 0){
this.setOpen(true);
this.cheat = photocopier.update();
}else{
this.setOpen(false);
}
}
//getter and setter
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class kh extends a {
public int rml;
public LinkedList<Integer> rmm = new LinkedList();
protected final int a(int i, Object... objArr) {
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.rml);
aVar.c(2, this.rmm);
return 0;
} else if (i == 1) {
return (f.a.a.a.fQ(1, this.rml) + 0) + f.a.a.a.b(2, this.rmm);
} else {
if (i == 2) {
byte[] bArr = (byte[]) objArr[0];
this.rmm.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
kh khVar = (kh) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
khVar.rml = aVar3.vHC.rY();
return 0;
case 2:
khVar.rmm = new f.a.a.a.a(aVar3.cJR().lR, unknownTagHandler).cJO();
return 0;
default:
return -1;
}
}
}
}
}
|
package fi.alekstu.ps5watch;
public class ListedConsole {
private final String name;
private final String url;
public ListedConsole(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return "ConsoleLink{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
'}';
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.table;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hudi.common.config.SerializableConfiguration;
import org.apache.hudi.common.fs.FSUtils;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.util.ValidationUtils;
import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.exception.HoodieIOException;
import org.apache.hudi.io.IOType;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.JavaSparkContext;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Operates on marker files for a given write action (commit, delta commit, compaction).
*/
public class MarkerFiles implements Serializable {
private static final Logger LOG = LogManager.getLogger(MarkerFiles.class);
private final String instantTime;
private final transient FileSystem fs;
private final transient Path markerDirPath;
private final String basePath;
public MarkerFiles(FileSystem fs, String basePath, String markerFolderPath, String instantTime) {
this.instantTime = instantTime;
this.fs = fs;
this.markerDirPath = new Path(markerFolderPath);
this.basePath = basePath;
}
public MarkerFiles(HoodieTable<?> table, String instantTime) {
this(table.getMetaClient().getFs(),
table.getMetaClient().getBasePath(),
table.getMetaClient().getMarkerFolderPath(instantTime),
instantTime);
}
public void quietDeleteMarkerDir(JavaSparkContext jsc, int parallelism) {
try {
deleteMarkerDir(jsc, parallelism);
} catch (HoodieIOException ioe) {
LOG.warn("Error deleting marker directory for instant " + instantTime, ioe);
}
}
/**
* Delete Marker directory corresponding to an instant.
*
* @param jsc Java Spark Context.
* @param parallelism Spark parallelism for deletion.
*/
public boolean deleteMarkerDir(JavaSparkContext jsc, int parallelism) {
try {
if (fs.exists(markerDirPath)) {
FileStatus[] fileStatuses = fs.listStatus(markerDirPath);
List<String> markerDirSubPaths = Arrays.stream(fileStatuses)
.map(fileStatus -> fileStatus.getPath().toString())
.collect(Collectors.toList());
if (markerDirSubPaths.size() > 0) {
SerializableConfiguration conf = new SerializableConfiguration(fs.getConf());
parallelism = Math.min(markerDirSubPaths.size(), parallelism);
jsc.parallelize(markerDirSubPaths, parallelism).foreach(subPathStr -> {
Path subPath = new Path(subPathStr);
FileSystem fileSystem = subPath.getFileSystem(conf.get());
fileSystem.delete(subPath, true);
});
}
boolean result = fs.delete(markerDirPath, true);
LOG.info("Removing marker directory at " + markerDirPath);
return result;
}
} catch (IOException ioe) {
throw new HoodieIOException(ioe.getMessage(), ioe);
}
return false;
}
public boolean doesMarkerDirExist() throws IOException {
return fs.exists(markerDirPath);
}
public Set<String> createdAndMergedDataPaths(JavaSparkContext jsc, int parallelism) throws IOException {
Set<String> dataFiles = new HashSet<>();
FileStatus[] topLevelStatuses = fs.listStatus(markerDirPath);
List<String> subDirectories = new ArrayList<>();
for (FileStatus topLevelStatus: topLevelStatuses) {
if (topLevelStatus.isFile()) {
String pathStr = topLevelStatus.getPath().toString();
if (pathStr.contains(HoodieTableMetaClient.MARKER_EXTN) && !pathStr.endsWith(IOType.APPEND.name())) {
dataFiles.add(translateMarkerToDataPath(pathStr));
}
} else {
subDirectories.add(topLevelStatus.getPath().toString());
}
}
if (subDirectories.size() > 0) {
parallelism = Math.min(subDirectories.size(), parallelism);
SerializableConfiguration serializedConf = new SerializableConfiguration(fs.getConf());
dataFiles.addAll(jsc.parallelize(subDirectories, parallelism).flatMap(directory -> {
Path path = new Path(directory);
FileSystem fileSystem = path.getFileSystem(serializedConf.get());
RemoteIterator<LocatedFileStatus> itr = fileSystem.listFiles(path, true);
List<String> result = new ArrayList<>();
while (itr.hasNext()) {
FileStatus status = itr.next();
String pathStr = status.getPath().toString();
if (pathStr.contains(HoodieTableMetaClient.MARKER_EXTN) && !pathStr.endsWith(IOType.APPEND.name())) {
result.add(translateMarkerToDataPath(pathStr));
}
}
return result.iterator();
}).collect());
}
return dataFiles;
}
private String translateMarkerToDataPath(String markerPath) {
String rPath = stripMarkerFolderPrefix(markerPath);
return MarkerFiles.stripMarkerSuffix(rPath);
}
public static String stripMarkerSuffix(String path) {
return path.substring(0, path.indexOf(HoodieTableMetaClient.MARKER_EXTN));
}
public List<String> allMarkerFilePaths() throws IOException {
List<String> markerFiles = new ArrayList<>();
FSUtils.processFiles(fs, markerDirPath.toString(), fileStatus -> {
markerFiles.add(stripMarkerFolderPrefix(fileStatus.getPath().toString()));
return true;
}, false);
return markerFiles;
}
private String stripMarkerFolderPrefix(String fullMarkerPath) {
ValidationUtils.checkArgument(fullMarkerPath.contains(HoodieTableMetaClient.MARKER_EXTN));
String markerRootPath = Path.getPathWithoutSchemeAndAuthority(
new Path(String.format("%s/%s/%s", basePath, HoodieTableMetaClient.TEMPFOLDER_NAME, instantTime))).toString();
int begin = fullMarkerPath.indexOf(markerRootPath);
ValidationUtils.checkArgument(begin >= 0,
"Not in marker dir. Marker Path=" + fullMarkerPath + ", Expected Marker Root=" + markerRootPath);
return fullMarkerPath.substring(begin + markerRootPath.length() + 1);
}
/**
* The marker path will be <base-path>/.hoodie/.temp/<instant_ts>/2019/04/25/filename.marker.writeIOType.
*/
public Path create(String partitionPath, String dataFileName, IOType type) {
Path path = FSUtils.getPartitionPath(markerDirPath, partitionPath);
try {
fs.mkdirs(path); // create a new partition as needed.
} catch (IOException e) {
throw new HoodieIOException("Failed to make dir " + path, e);
}
String markerFileName = String.format("%s%s.%s", dataFileName, HoodieTableMetaClient.MARKER_EXTN, type.name());
Path markerPath = new Path(path, markerFileName);
try {
LOG.info("Creating Marker Path=" + markerPath);
fs.create(markerPath, false).close();
} catch (IOException e) {
throw new HoodieException("Failed to create marker file " + markerPath, e);
}
return markerPath;
}
}
|
package com.ceiba.parkingceiba.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ceiba.parkingceiba.model.entity.Parqueadero;
import com.ceiba.parkingceiba.repository.ParqueaderoDao;
@Service
public class ParqueaderoServiceImp implements IParqueaderoService{
@Autowired
public ParqueaderoDao parqueaderoDao;
@Override
@Transactional
public Parqueadero registrarParqueoVehiculo(Parqueadero parqueadero) {
return parqueaderoDao.save(parqueadero);
}
@Override
public Parqueadero getParqueaderoParaAsignar(String placa) {
return parqueaderoDao.buscarVehiculoEnParqueaderoPorPlaca(placa);
}
@Override
public List<Parqueadero> encontrarTodosLosParqueaderos() {
return parqueaderoDao.findByEstado(true);
}
@Override
@Transactional
public Parqueadero asignarParqueaderoPorId(Parqueadero parqueadero, Date fechaSalida, int cobro) {
parqueadero.setFechaSalida(fechaSalida);
parqueadero.setCobro(cobro);
parqueadero.setEstado(false);
registrarParqueoVehiculo(parqueadero);
return parqueadero;
}
}
|
package com.diozero.sampleapps;
/*
* #%L
* Organisation: diozero
* Project: diozero - Sample applications
* Filename: SSD1331Test.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ThreadLocalRandom;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
import org.tinylog.Logger;
import com.diozero.api.DigitalOutputDevice;
import com.diozero.devices.oled.ColourSsdOled;
import com.diozero.devices.oled.SSD1331;
import com.diozero.devices.oled.SsdOled;
import com.diozero.sampleapps.gol.GameOfLife;
import com.diozero.util.Diozero;
/**
* <ul>
* <li>Built-in:<br>
* {@code java -cp tinylog-api-$TINYLOG_VERSION.jar:tinylog-impl-$TINYLOG_VERSION.jar:diozero-core-$DIOZERO_VERSION.jar com.diozero.sampleapps.SSD1331Test}</li>
* <li>pigpioj:<br>
* {@code sudo java -cp tinylog-api-$TINYLOG_VERSION.jar:tinylog-impl-$TINYLOG_VERSION.jar:diozero-core-$DIOZERO_VERSION.jar:diozero-provider-pigpio-$DIOZERO_VERSION.jar:pigpioj-java-2.4.jar com.diozero.sampleapps.SSD1331Test}</li>
* </ul>
*/
public class SSD1331Test {
public static void main(String[] args) {
/*-
try (LED led = new LED(16)) {
led.on();
Thread.sleep(500);
led.off();
Thread.sleep(500);
} catch (InterruptedException e) {
}
*/
// int dc_gpio = 185;
int dc_gpio = 21;
// int reset_gpio = 224;
int reset_gpio = 20;
if (args.length > 1) {
dc_gpio = Integer.parseInt(args[0]);
reset_gpio = Integer.parseInt(args[1]);
}
// int spi_controller = 2;
int spi_controller = 0;
int chip_select = 1;
if (args.length > 2) {
spi_controller = Integer.parseInt(args[2]);
chip_select = Integer.parseInt(args[3]);
}
try (DigitalOutputDevice dc_pin = new DigitalOutputDevice(dc_gpio);
DigitalOutputDevice reset_pin = new DigitalOutputDevice(reset_gpio);
ColourSsdOled oled = new SSD1331(spi_controller, chip_select, dc_pin, reset_pin)) {
gameOfLife(oled, 10_000);
displayImages(oled);
sierpinskiTriangle(oled, 250);
drawText(oled);
testJava2D(oled);
animateText(oled,
"SSD1331 Organic LED Display demo scroller. Java implementation by diozero (diozero.com).");
} catch (RuntimeException e) {
Logger.error(e, "Error: {}", e);
} finally {
// Required if there are non-daemon threads that will prevent the
// built-in clean-up routines from running
Diozero.shutdown();
}
}
public static void animateText(SsdOled oled, String text) {
int width = oled.getWidth();
int height = oled.getHeight();
BufferedImage image = new BufferedImage(width, height, oled.getNativeImageType());
Graphics2D g2d = image.createGraphics();
final ThreadLocalRandom random = ThreadLocalRandom.current();
Color[] colours = { Color.WHITE, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY,
Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.YELLOW };
g2d.setBackground(Color.BLACK);
Font f = g2d.getFont();
Logger.info("Font name={}, family={}, size={}, style={}", f.getFontName(), f.getFamily(),
Integer.valueOf(f.getSize()), Integer.valueOf(f.getStyle()));
FontMetrics fm = g2d.getFontMetrics();
int maxwidth = fm.stringWidth(text);
int amplitude = height / 4;
int offset = height / 2 - 4;
int velocity = -2;
int startpos = width;
int pos = startpos;
int x;
for (int i = 0; i < 200; i++) {
g2d.clearRect(0, 0, width, height);
x = pos;
for (char c : text.toCharArray()) {
if (x > width) {
break;
}
if (x < -10) {
x += fm.charWidth(c);
continue;
}
// Calculate offset from sine wave.
int y = (int) (offset + Math.floor(amplitude * Math.sin(x / ((float) width) * 2.0 * Math.PI)));
// Draw text.
g2d.setColor(colours[random.nextInt(colours.length)]);
g2d.drawString(String.valueOf(c), x, y);
// Increment x position based on chacacter width.
x += fm.charWidth(c);
}
// Draw the image buffer.
oled.display(image);
// Move position for next frame.
pos += velocity;
// Start over if text has scrolled completely off left side of screen.
if (pos < -maxwidth) {
pos = startpos;
}
// Pause briefly before drawing next frame.
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
public static void gameOfLife(ColourSsdOled oled, long duration) {
Logger.info("Game of Life");
oled.clear();
GameOfLife gol = new GameOfLife(oled.getWidth(), oled.getHeight());
gol.randomise();
long start = System.currentTimeMillis();
long current_duration;
int iterations = 0;
do {
render(oled, gol);
gol.iterate();
current_duration = System.currentTimeMillis() - start;
iterations++;
} while (current_duration < duration);
double fps = iterations / (duration / 1000.0);
Logger.info("FPS: {0.##}", Double.valueOf(fps));
}
private static void render(ColourSsdOled oled, GameOfLife gol) {
for (int i = 0; i < gol.getWidth(); i++) {
for (int j = 0; j < gol.getHeight(); j++) {
if (gol.isAlive(i, j)) {
oled.setPixel(i, j, ColourSsdOled.MAX_RED, ColourSsdOled.MAX_GREEN, ColourSsdOled.MAX_BLUE, false);
} else {
oled.setPixel(i, j, (byte) 0, (byte) 0, (byte) 0, false);
}
}
}
oled.display();
}
public static void displayImages(SsdOled oled) {
Logger.info("Images");
// https://github.com/rm-hull/luma.examples
String[] images = { "/images/balloon.png", "/images/pi_logo.png", "/images/pixelart1.png",
"/images/pixelart2.png", "/images/pixelart3.jpg", "/images/pixelart4.jpg", "/images/pixelart5.jpg",
"/images/starwars.png", "not found" };
for (String image : images) {
try (InputStream is = SSD1331Test.class.getResourceAsStream(image)) {
if (is != null) {
BufferedImage br = ImageIO.read(is);
if (br.getWidth() != oled.getWidth() || br.getHeight() != oled.getHeight()) {
br = Scalr.resize(br, Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_EXACT, oled.getWidth(),
oled.getHeight(), Scalr.OP_ANTIALIAS);
}
oled.display(br);
}
} catch (IOException e) {
Logger.error(e, "Error: {}", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
public static void sierpinskiTriangle(ColourSsdOled oled, int iterations) {
Logger.info("Sierpinski triangle");
int width = oled.getWidth();
int height = oled.getHeight();
final ThreadLocalRandom random = ThreadLocalRandom.current();
oled.clear();
final Point[] corners = { new Point(width / 2, 0), new Point(0, height - 1), new Point(width - 1, height - 1) };
Point point = new Point(corners[random.nextInt(corners.length)]);
for (int i = 0; i < iterations; i++) {
final Point target_corner = corners[random.nextInt(corners.length)];
point.x += (target_corner.x - point.x) / 2;
point.y += (target_corner.y - point.y) / 2;
oled.setPixel(point.x, point.y, ColourSsdOled.MAX_RED, (byte) 0, (byte) 0, true);
/*-
try {
Thread.sleep(5);
} catch (InterruptedException e) {
}
*/
}
}
private static final class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
}
}
public static void drawText(SsdOled oled) {
Logger.info("Coloured text");
int width = oled.getWidth();
int height = oled.getHeight();
BufferedImage image = new BufferedImage(width, height, oled.getNativeImageType());
Graphics2D g2d = image.createGraphics();
g2d.setBackground(Color.BLACK);
g2d.clearRect(0, 0, width, height);
g2d.setColor(Color.RED);
g2d.drawString("Red", 10, 10);
g2d.setColor(Color.GREEN);
g2d.drawString("Green", 10, 20);
g2d.setColor(Color.BLUE);
g2d.drawString("Blue", 10, 30);
oled.display(image);
g2d.dispose();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
public static void testJava2D(ColourSsdOled oled) {
Logger.info("Displaying custom image");
int width = oled.getWidth();
int height = oled.getHeight();
BufferedImage image = new BufferedImage(width, height, oled.getNativeImageType());
Graphics2D g2d = image.createGraphics();
g2d.setBackground(Color.BLACK);
g2d.clearRect(0, 0, width, height);
g2d.setColor(Color.WHITE);
g2d.drawLine(0, 0, width, height);
g2d.drawLine(width, 0, 0, height);
g2d.drawLine(width / 2, 0, width / 2, height);
g2d.drawLine(0, height / 2, width, height / 2);
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, width / 4, height / 4);
g2d.setColor(Color.ORANGE);
g2d.draw3DRect(width / 4, height / 4, width / 2, height / 2, true);
g2d.setColor(Color.BLUE);
g2d.drawOval(width / 2, height / 2, width / 3, height / 3);
g2d.setColor(Color.GREEN);
g2d.fillRect(width / 4, 0, width / 4, height / 4);
g2d.setColor(Color.YELLOW);
g2d.fillOval(0, height / 4, width / 4, height / 4);
oled.display(image);
g2d.dispose();
Logger.debug("Sleeping for 2 seconds");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Logger.debug("Inverting");
oled.invertDisplay(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Logger.debug("Restoring to normal");
oled.invertDisplay(false);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
for (int i = 0; i < 255; i++) {
oled.setContrast((byte) i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
}
|
package com.designpattern.dao;
import java.util.ArrayList;
import java.util.List;
import com.designpattern.dao.model.Transaction;
import com.designpattern.dao.model.TransactionBo;
public class TransactionDaoImpl implements TransactionDao {
List<Transaction>transactions;
public TransactionDaoImpl() {
// TODO Auto-generated constructor stub
transactions=new ArrayList<>();
transactions.add(new Transaction("2345644","345687655555"));
transactions.add(new Transaction("1123456","378654390055"));
}
@Override
public List<Transaction> getAllTransactions() {
// TODO Auto-generated method stub
return transactions;
}
@Override
public Transaction getTransactionByTinNo(int tin) {
// TODO Auto-generated method stub
return transactions.get(tin);
}
@Override
public void saveTransaction(Transaction transaction) {
transactions.add(transaction);
}
@Override
public void DeleteTransaction(TransactionBo transaction) {
// TODO Auto-generated method stub
transactions.remove(transaction);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.insat.gl5.crm_pfa.web.controller.product;
import com.insat.gl5.crm_pfa.model.Category;
import com.insat.gl5.crm_pfa.model.TVA;
import com.insat.gl5.crm_pfa.service.ProductService;
import com.insat.gl5.crm_pfa.web.controller.ConversationController;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.jboss.seam.international.status.Messages;
/**
*
* @author Mounir Messelmeni <messelmeni.mounir@gmail.com>
*/
@Named
@ConversationScoped
public class TvaController extends ConversationController {
@Inject
private TVA tva;
private TVA selectedTva;
@Inject
private ProductService productService;
@Inject
private Messages messages;
public String create() {
try {
productService.createTva(getTva());
messages.info("TVA ajoutée.");
setTva(new TVA());
return "newTva.hide();";
} catch (Exception ex) {
messages.error("Erreur lors de l'ajout de la TVA.");
}
return null;
}
public String edit() {
try {
productService.editTva(getSelectedTva());
messages.info("TVA modifiée.");
endConversation();
return "editCategory.hide();";
} catch (Exception ex) {
messages.error("Erreur lors de la modification de la TVA.");
}
return null;
}
public void delete() {
try {
productService.deleteTva(getSelectedTva());
messages.info("TVA supprimée.");
endConversation();
} catch (Exception ex) {
messages.error("Erreur lors de suppression de la TVA.");
}
}
/**
* @return the tva
*/
public TVA getTva() {
return tva;
}
/**
* @param tva the tva to set
*/
public void setTva(TVA tva) {
this.tva = tva;
}
/**
* @return the selectedTva
*/
public TVA getSelectedTva() {
return selectedTva;
}
/**
* @param selectedTva the selectedTva to set
*/
public void setSelectedTva(TVA selectedTva) {
this.selectedTva = selectedTva;
}
}
|
package error.example.domain.exception;
public class AnotherDomainException extends DomainException {
public AnotherDomainException(String message) {
super(message);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.insat.gl5.crm_pfa.model;
import javax.persistence.Entity;
/**
*
* @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com --
*/
@Entity
public class Fidelity extends BaseEntity{
private int score;
public Fidelity() {
}
public Fidelity(int score) {
this.score = score;
}
public void incrementScore(int value){
score+=value;
}
public void decrementScore(int value){
score-=value;
}
/**
* @return the score
*/
public int getScore() {
return score;
}
}
|
package controller;
import view.ServerCollectionView;
import view.ServerMainView;
/**
* @version Adreli_4_Gui_Server
* @author Jan-Hendrik Hausner
* @author John Budnik
* @author Luca Weinmann
*/
public class StartServer {
/**
* @param args
*/
public static void main(String[]args) {
new ControllServer(new ServerCollectionView(new ServerMainView()));
}
}
|
package q4.user;
import java.util.ArrayList;
import java.util.Date;
import q4.adress.Address;
public class User {
String isim ="Melih";
String soyisim="Esmek";
String password="123";
String email="mbesmek@gmail.com";
int yas=22;
Date sonGirisTarihi= new Date();
ArrayList<Address> adress = new ArrayList<Address>();
public User(String isim,String soyisim,String password,String email,int yas,Date sonGirisTarihi,ArrayList<Address> adress) {
this.isim=isim;
this.soyisim=soyisim;
this.password=password;
this.email=email;
this.yas=yas;
this.sonGirisTarihi=sonGirisTarihi;
this.adress=adress;
}
public User() {
// TODO Auto-generated constructor stub
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIsim() {
return isim;
}
public void setIsim(String isim) {
this.isim = isim;
}
public String getSoyisim() {
return soyisim;
}
public void setSoyisim(String soyisim) {
this.soyisim = soyisim;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getYas() {
return yas;
}
public void setYas(int yas) {
this.yas = yas;
}
public Date getSonGirisTarihi() {
return sonGirisTarihi;
}
public void setSonGirisTarihi(Date sonGirisTarihi) {
this.sonGirisTarihi = sonGirisTarihi;
}
public ArrayList<Address> getAdress() {
return adress;
}
public void setAdress(ArrayList<Address> adress) {
this.adress = adress;
}
}
|
package com.example.widgetex;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "main";
private ImageButton imagebutton1, imagebutton2, imagebutton3, imagebutton4, imagebutton5, imagebutton6, imagebutton7, imagebutton8;
private ImageView imageViewPic;
private TextView textViewresult;
private Context context;
private String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
// 設定 imagebutton物件
imagebutton1 = (ImageButton) findViewById(R.id.imageButton1);
imagebutton2 = (ImageButton) findViewById(R.id.imageButton2);
imagebutton3 = (ImageButton) findViewById(R.id.imageButton3);
imagebutton4 = (ImageButton) findViewById(R.id.imageButton4);
imagebutton5 = (ImageButton) findViewById(R.id.imageButton5);
imagebutton6 = (ImageButton) findViewById(R.id.imageButton6);
imagebutton7 = (ImageButton) findViewById(R.id.imageButton7);
imagebutton8 = (ImageButton) findViewById(R.id.imageButton8);
// 監聽 imagebutton
imagebutton1.setOnClickListener(new MyClick());
imagebutton2.setOnClickListener(new MyClick());
imagebutton3.setOnClickListener(new MyClick());
imagebutton4.setOnClickListener(new MyClick());
imagebutton5.setOnClickListener(new MyClick());
imagebutton6.setOnClickListener(new MyClick());
imagebutton7.setOnClickListener(new MyClick());
imagebutton8.setOnClickListener(new MyClick());
}
private class MyClick implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayActivity.class);
switch (v.getId()){
case R.id.imageButton1:
name = getResources().getString(R.string.imageButton1);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_1_b);
intent.putExtra("text", R.string.imageButton1_info);
break;
case R.id.imageButton2:
name = getResources().getString(R.string.imageButton2);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_2_b);
intent.putExtra("text", R.string.imageButton2_info);
break;
case R.id.imageButton3:
name = getResources().getString(R.string.imageButton3);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_3_b);
intent.putExtra("text", R.string.imageButton3_info);
break;
case R.id.imageButton4:
name = getResources().getString(R.string.imageButton4);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_4_b);
intent.putExtra("text", R.string.imageButton4_info);
break;
case R.id.imageButton5:
name = getResources().getString(R.string.imageButton5);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_5_b);
intent.putExtra("text", R.string.imageButton5_info);
break;
case R.id.imageButton6:
name = getResources().getString(R.string.imageButton6);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_6_b);
intent.putExtra("text", R.string.imageButton6_info);
break;
case R.id.imageButton7:
name = getResources().getString(R.string.imageButton7);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_7_b);
intent.putExtra("text", R.string.imageButton7_info);
break;
case R.id.imageButton8:
name = getResources().getString(R.string.imageButton8);
Log.d(TAG, "name = " + name);
intent.putExtra("title", name);
intent.putExtra("image", R.drawable.pic_8_b);
intent.putExtra("text", R.string.imageButton8_info);
break;
}
startActivity(intent);
}
}
}
|
package br.com.conspesca.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Local implements Serializable {
private static final long serialVersionUID = -215723937531032509L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id_local")
private Integer idLocal;
private String nome;
private String descricao;
@OneToMany(mappedBy = "local")
private List<Pescaria> pescaria;
public Local() {
}
public Local(Integer idLocal, String nome, String descricao) {
super();
this.idLocal = idLocal;
this.nome = nome;
this.descricao = descricao;
}
public Integer getIdLocal() {
return this.idLocal;
}
public void setIdLocal(Integer idLocal) {
this.idLocal = idLocal;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescricao() {
return this.descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public List<Pescaria> getPescaria() {
return this.pescaria;
}
public void setPescaria(List<Pescaria> pescaria) {
this.pescaria = pescaria;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((idLocal == null) ? 0 : idLocal.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Local other = (Local) obj;
if (idLocal == null) {
if (other.idLocal != null)
return false;
} else if (!idLocal.equals(other.idLocal))
return false;
return true;
}
}
|
package sys_bs.dao;
import java.util.List;
import sys_bs.entity.*;
/**
* 登录持久化接口
* @author Administrator
*
*/
public interface ILoginDao {
/**
* 登录
* @param code
* @param password
* @return
*/
public int login(String code,String password);
/**
* 查询
* @param account
* @return
*/
public List<Account> listAccount(Account account);
/**
* 增加
* @param account
* @return
*/
public int addAccount(Account account);
/**
* 删除
* @param account
* @return
*/
public int deleteAccount(Account account);
/**
* 修改
* @param account
* @return
*/
public int updateAccount(Account account);
}
|
package com.pine.template.mvp.contract;
import com.pine.template.mvp.adapter.MvpShopListNoPaginationAdapter;
import com.pine.tool.architecture.mvp.contract.IContract;
/**
* Created by tanghongfeng on 2018/9/14
*/
public interface IMvpShopNoPaginationListContract {
interface Ui extends IContract.Ui {
}
interface Presenter extends IContract.Presenter {
void loadShopNoPaginationListData();
MvpShopListNoPaginationAdapter getListAdapter();
}
}
|
package ru.yandex.qatools.allure.data;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import ru.yandex.qatools.allure.data.utils.TextUtils;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertFalse;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 09.12.13
*/
@RunWith(Parameterized.class)
public class TextUtilsGenerateUidTest {
private String data;
public TextUtilsGenerateUidTest(String data) {
this.data = data;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[]{"some-string"},
new Object[]{"next-string-is-empty"},
new Object[]{""},
new Object[]{"123asdasd123ASDadkllmlk(*&(*&*#(&*($@#$$@#"},
new Object[]{"-="}
);
}
@Test
public void generateUid() throws Exception {
String result = TextUtils.generateUid(data);
assertFalse("Uid should be not empty", result.isEmpty());
}
}
|
package com.tencent.mm.plugin.remittance.ui;
import com.tencent.mm.kernel.g;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.d.c;
import com.tencent.mm.wallet_core.d.d;
class RemittanceBusiUI$b implements Runnable {
public d mBH;
final /* synthetic */ RemittanceBusiUI mBt;
RemittanceBusiUI$b(RemittanceBusiUI remittanceBusiUI) {
this.mBt = remittanceBusiUI;
}
public final void run() {
c D = RemittanceBusiUI.D(this.mBt);
d dVar = this.mBH;
x.i("MicroMsg.IDelayQueryOrder", "doScene rtType %s", new Object[]{Integer.valueOf(D.rtType)});
g.Ek();
g.Eh().dpP.a(D.rtType, D);
D.a(dVar);
}
}
|
/**
*
*/
package alg.sort;
import java.util.Arrays;
/**
* 基本比较排序
* <p>
* <a href="http://www.cnblogs.com/eniac12/p/5329396.html">排序算法总结</a>
*
* @title CompareSort
*/
public class CompareSort {
public static void main(String[] args) {
int[] a = { 4, 1, -1, 6, 9, 2, 1, 0, 3, 5, 5, 18, 20, -19 };
CompareSort cs = new CompareSort();
cs.shellSort(a);
System.out.println(Arrays.toString(a));
}
/**
* 冒泡排序,复杂度固定为n^2,稳定
*/
public void bubbleSort(int[] a) {
if (a == null || a.length <= 1)
return;
int n = a.length;
for (int i = 1; i < n; ++i) { // round
for (int j = 0; j < n - i; ++j) {
if (a[j] > a[j + 1])
swap(a, j, j + 1);
}
}
}
/**
* 冒泡排序另一个版本:鸡尾酒排序
*/
public void cocktailSort(int a[]) {
int n = a.length;
int left = 0; // 初始化边界
int right = n - 1;
while (left < right) {
for (int i = left; i < right; i++) { // 前半轮,将最大元素放到后面
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
}
}
right--;
for (int i = right; i > left; i--) { // 后半轮,将最小元素放到前面
if (a[i - 1] > a[i]) {
swap(a, i - 1, i);
}
}
left++;
}
}
/**
* 选择排序,选择最值的过程开销是固定的,不存在最好的最坏情况,在任何情况下复杂度都是n^2 不稳定,发生在最小元素交换时
*/
public void selectSort(int[] a) {
if (a == null || a.length <= 1)
return;
int n = a.length;
for (int i = 0; i < n - 1; ++i) {
int min = i;
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[min]) {
min = j;
}
}
if (min != i)
swap(a, min, i);
}
}
/**
* 插入排序,最优(n)和最坏情况(n^2)分别发生在数据已有序和逆序情况下,稳定
*/
public void insertSort(int[] a) {
if (a == null || a.length <= 1)
return;
int n = a.length;
for (int i = 1; i < n; ++i) {
int tmp = a[i];
int j = i - 1;
for (; j >= 0 && a[j] > tmp; --j) {
a[j + 1] = a[j];
}
a[j + 1] = tmp;
}
}
/**
* 希尔排序,插入排序的改进,重点在于间隔h的选取
*/
public void shellSort(int[] a) {
if (a == null || a.length <= 1)
return;
for (int h = getH(a); h >= 1; h /= 2) {
for (int s = 0; s < h; ++s) {
innerInsertSort(a, s, h);
}
}
}
/**
* 希尔排序内部的插入排序
*/
private void innerInsertSort(int[] a, int start, int h) {
int n = a.length;
for (int i = start + h; i < n; i += h) {
int tmp = a[i]; // to be insert
int j = i - h; // prev element
for (; j >= start && a[j] > tmp; j -= h) {
a[j + h] = a[j];
}
a[j + h] = tmp;
}
}
private int getH(int[] a) {
return 4;
}
private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
|
package com.box.androidsdk.content.requests;
import com.box.androidsdk.content.models.BoxFolder;
import com.box.androidsdk.content.models.BoxItem;
import com.box.androidsdk.content.models.BoxSession;
import com.box.androidsdk.content.models.BoxSharedLink;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract class that represents an item update request.
*
* @param <E> type of BoxItem that is being updated.
* @param <R> type of BoxRequest that is being created.
*/
public abstract class BoxRequestItemUpdate<E extends BoxItem, R extends BoxRequest<E,R>> extends BoxRequestItem<E, R> {
/**
* Creates an update item request with the default parameters.
*
* @param clazz class of the item to return in the response.
* @param id id of the item being updated.
* @param requestUrl URL for the update item endpoint.
* @param session authenticated session that will be used to make the request with.
*/
public BoxRequestItemUpdate(Class<E> clazz, String id, String requestUrl, BoxSession session) {
super(clazz, id, requestUrl, session);
mRequestMethod = Methods.PUT;
}
protected BoxRequestItemUpdate(BoxRequestItemUpdate r) {
super(r);
}
/**
* Converts the BoxRequestItemUpdate into a BoxRequestUpdateSharedItem. Using the request you can update shared link of the item.
* @return BoxRequestUpdateSharedItem from the BoxRequestItemUpdate.
*/
public abstract BoxRequestUpdateSharedItem updateSharedLink();
/**
* Returns the new name currently set for the item.
*
* @return name for the item, or null if not set.
*/
public String getName() {
return mBodyMap.containsKey(BoxItem.FIELD_NAME) ?
(String) mBodyMap.get(BoxItem.FIELD_NAME) :
null;
}
/**
* Sets the new name for the item.
*
* @param name new name for the item.
* @return request with the updated name.
*/
public R setName(String name) {
mBodyMap.put(BoxItem.FIELD_NAME, name);
return (R) this;
}
/**
* Returns the new description currently set for the item.
*
* @return description for the item, or null if not set.
*/
public String getDescription() {
return mBodyMap.containsKey(BoxItem.FIELD_DESCRIPTION) ?
(String) mBodyMap.get(BoxItem.FIELD_DESCRIPTION) :
null;
}
/**
* Sets the new description for the item.
*
* @param description description for the item.
* @return request with the updated description.
*/
public R setDescription(String description) {
mBodyMap.put(BoxItem.FIELD_DESCRIPTION, description);
return (R) this;
}
/**
* Returns the new parent id currently set for the item.
*
* @return id of the parent folder for the item, or null if not set.
*/
public String getParentId() {
return mBodyMap.containsKey(BoxItem.FIELD_PARENT) ?
((BoxFolder) mBodyMap.get(BoxItem.FIELD_PARENT)).getId() :
null;
}
/**
* Sets the new parent id for the item.
*
* @param parentId id of the new parent folder for the item.
* @return request with the updated parent id.
*/
public R setParentId(String parentId) {
BoxFolder parentFolder = BoxFolder.createFromId(parentId);
mBodyMap.put(BoxItem.FIELD_PARENT, parentFolder);
return (R) this;
}
/**
* Returns the shared link currently set for the item.
*
* @return shared link for the item, or null if not set.
*/
public BoxSharedLink getSharedLink() {
return mBodyMap.containsKey(BoxItem.FIELD_SHARED_LINK) ?
((BoxSharedLink) mBodyMap.get(BoxItem.FIELD_SHARED_LINK)) :
null;
}
/**
* Sets the new shared link for the item.
*
* @param sharedLink new shared link for the item.
* @return request with the updated shared link.
*/
public R setSharedLink(BoxSharedLink sharedLink) {
mBodyMap.put(BoxItem.FIELD_SHARED_LINK, sharedLink);
return (R) this;
}
/**
* Sets the if-match header for the request.
* The item will only be updated if the specified etag matches the most current etag for the item.
*
* @param etag etag to set in the if-match header.
* @return request with the updated if-match header.
*/
@Override
public R setIfMatchEtag(String etag) {
return super.setIfMatchEtag(etag);
}
/**
* Returns the etag currently set in the if-match header.
*
* @return etag set in the if-match header, or null if none set.
*/
@Override
public String getIfMatchEtag() {
return super.getIfMatchEtag();
}
/**
* Returns the tags currently set for the item.
*
* @return tags for the item, or null if not set.
*/
public List<String> getTags() {
return mBodyMap.containsKey(BoxItem.FIELD_TAGS) ?
(List<String>) mBodyMap.get(BoxItem.FIELD_TAGS) :
null;
}
/**
* Sets the new tags for the item.
*
* @param tags new tags for the item.
* @return request with the updated tags.
*/
public R setTags(List<String> tags) {
JsonArray jsonArray = new JsonArray();
for (String s : tags) {
jsonArray.add(s);
}
mBodyMap.put(BoxItem.FIELD_TAGS, jsonArray);
return (R) this;
}
@Override
protected void parseHashMapEntry(JsonObject jsonBody, Map.Entry<String,Object> entry) {
if (entry.getKey().equals(BoxItem.FIELD_PARENT)) {
jsonBody.add(entry.getKey(), parseJsonObject(entry.getValue()));
return;
} else if (entry.getKey().equals(BoxItem.FIELD_SHARED_LINK)) {
if (entry.getValue() == null) {
// Adding a null shared link signifies that the link should be disabled
jsonBody.add(entry.getKey(), (String) null);
} else {
jsonBody.add(entry.getKey(), parseJsonObject(entry.getValue()));
}
return;
}
super.parseHashMapEntry(jsonBody, entry);
}
}
|
package com.neo.test.seq;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Sequence {
private static final Log log = LogFactory.getLog(Sequence.class);
private int blockSize;
private long startValue;
private static final String GET_SQL = "select id from sequence_value where name = ?";
private static final String NEW_SQL = "insert into sequence_value (id,name) values (?,?)";
private static final String UPDATE_SQL = "update sequence_value set id = ? where name = ? and id = ?";
private Map<String, Step> stepMap;
private DataSource dataSource;
public Sequence() {
this.blockSize = 5;
this.startValue = 0L;
this.stepMap = new HashMap();
}
private boolean getNextBlock(String sequenceName, Step step) {
Long value = getPersistenceValue(sequenceName);
if (value == null) {
try {
value = newPersistenceValue(sequenceName);
} catch (Exception e) {
log.error("newPersistenceValue error!");
value = getPersistenceValue(sequenceName);
}
}
boolean b = saveValue(value.longValue(), sequenceName) == 1;
if (b) {
step.setCurrentValue(value.longValue());
step.setEndValue(value.longValue() + this.blockSize);
}
return b;
}
public synchronized long get(String sequenceName) {
Step step = (Step) this.stepMap.get(sequenceName);
if (step == null) {
step = new Step(this.startValue, this.startValue + this.blockSize);
this.stepMap.put(sequenceName, step);
} else if (step.currentValue < step.endValue) {
return step.incrementAndGet();
}
for (int i = 0; i < this.blockSize; i++) {
if (getNextBlock(sequenceName, step)) {
return step.incrementAndGet();
}
}
throw new RuntimeException("No more value.");
}
private int saveValue(long value, String sequenceName) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = this.dataSource.getConnection();
statement = connection.prepareStatement("update sequence_value set id = ? where name = ? and id = ?");
statement.setLong(1, value + this.blockSize);
statement.setString(2, sequenceName);
statement.setLong(3, value);
return statement.executeUpdate();
} catch (Exception e) {
log.error("newPersistenceValue error!", e);
throw new RuntimeException("newPersistenceValue error!", e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
log.error("close statement error!", e);
}
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
log.error("close connection error!", e);
}
}
}
private Long getPersistenceValue(String sequenceName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = this.dataSource.getConnection();
statement = connection.prepareStatement("select id from sequence_value where name = ?");
statement.setString(1, sequenceName);
resultSet = statement.executeQuery();
if (resultSet.next())
return Long.valueOf(resultSet.getLong("id"));
} catch (Exception e) {
log.error("getPersistenceValue error!", e);
throw new RuntimeException("getPersistenceValue error!", e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error("close resultset error!", e);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
log.error("close statement error!", e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error("close connection error!", e);
}
}
}
return null;
}
private Long newPersistenceValue(String sequenceName) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = this.dataSource.getConnection();
statement = connection.prepareStatement("insert into sequence_value (id,name) values (?,?)");
statement.setLong(1, this.startValue);
statement.setString(2, sequenceName);
statement.executeUpdate();
} catch (Exception e) {
log.error("newPersistenceValue error!", e);
throw new RuntimeException("newPersistenceValue error!", e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
log.error("close statement error!", e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error("close connection error!", e);
}
}
}
return Long.valueOf(this.startValue);
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
public void setStartValue(long startValue) {
this.startValue = startValue;
}
static class Step {
private long currentValue;
private long endValue;
Step(long currentValue, long endValue) {
this.currentValue = currentValue;
this.endValue = endValue;
}
public void setCurrentValue(long currentValue) {
this.currentValue = currentValue;
}
public void setEndValue(long endValue) {
this.endValue = endValue;
}
public long incrementAndGet() {
return ++this.currentValue;
}
}
}
|
import java.io.*;
/**
* Created by Ankit on 1/17/2017.
*/
public class FileIO {
public static String readFile(File inputPath) {
String output = "";
try(BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputPath)))) {
output = input.readLine();
} catch( IOException e) {
e.printStackTrace();
}
return output;
}
public static void appendFile(File outputPath, String toWrite) {
try(BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath)))) {
output.append(toWrite);
} catch( IOException e) {
e.printStackTrace();
}
}
public static void writeFile(File outputPath, String toWrite) {
try(BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath)))) {
output.write(toWrite);
} catch( IOException e) {
e.printStackTrace();
}
}
public static String consoleRead() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
|
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Publisher;
@Repository
public interface PublisherRepository extends CrudRepository<Publisher,Long>{
}
|
package com.cristovantamayo.ubsvoce.services;
import java.text.DecimalFormat;
import org.hamcrest.core.IsSame;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.cristovantamayo.ubsvoce.entities.Geocode;
import com.cristovantamayo.ubsvoce.entities.Score;
import com.cristovantamayo.ubsvoce.entities.Unidade;
import com.cristovantamayo.ubsvoce.entities.enums.ScoreType;
import com.google.maps.model.GeocodingResult;
@ExtendWith(SpringExtension.class)
@SpringBootTest
@EnableConfigurationProperties
@ConfigurationProperties("geocoding")
public class GeocodingServiceTest {
String apiKey;
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public GeocodingServiceTest() {
// TODO Auto-generated constructor stub
}
@Tag("DEV")
//@Disabled
@Test
public void deveRetorarMesmaClasse()
{
GeocodingResult[] result = null;
GeocodingResult[] result2 = null;// GeocodingService.searchAddress("Avenida Paulista, 1000", apiKey);
Assert.assertThat(result, IsSame.sameInstance(result2));
}
@Test
public void deveEstarPerto() {
Score score = new Score(ScoreType.ACIMA, ScoreType.MEDIO_OU_ABAIXO, ScoreType.MUITO_ACIMA, ScoreType.MEDIO_OU_ABAIXO);
Geocode item = new Geocode(-23.557713, -46.645364);
Unidade unidade = new Unidade("UBS Mais Mourisco", "Rua Emengarda pires, 123","Jardim Mourisco", "Taubaté", "1287477834", item, score);
item.setUnidade(unidade);
score.setUnidade(unidade);
// isNear foi movida para arquivo oculto por acessibilidade pacote-privado.
//assertTrue(GeocodingService.isNear(unidade, -23.564515, -46.651825, 1500.0));
}
@Test
public void deveArredondarCoordenada() {
DecimalFormat df = new DecimalFormat("#.00");
Double lat = Double.valueOf("-53.1061291694626");
double partial = Double.parseDouble(df.format(lat).replace(',', '.'));
Assert.assertEquals(-23.00, partial, 0.00001);
}
}
|
package support.yz.data.entity.chart;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.List;
/**
* @Author: yangzhuo
* @Description: 用户添加的节点
* @Date: 2018/7/25
*/
@Setter
@Getter
@NodeEntity
public class Node {
@GraphId
private Long id;
private String name;
@Relationship(type = "Have")
@JsonProperty("拥有")
private List<Node> nextNodes;
public Node(){
setName("默认");
}
public Node(String name){
setName(name);
}
}
|
package LeetCode.BloombergPractice;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
public class Leaderboard {
class Pdetail{
int id;
int score;
Pdetail(int id, int score){
this.id = id;
this.score = score;
}
}
HashMap<Integer, Pdetail> map;
TreeSet<Pdetail> set;
public Leaderboard(){
map = new HashMap<>();
set = new TreeSet<>(new Comparator<Pdetail>() {
@Override
public int compare(Pdetail o1, Pdetail o2) {
if(o1.score == o2.score) return o1.id - o2.id;
else return o2.score - o1.score;
}
});
}
public void addScore(int playedId, int score){
Pdetail p;
if(map.containsKey(playedId)) {
p = map.get(playedId);
set.remove(p);
p.score += score;
set.add(p);
} else {
p = new Pdetail(playedId, score);
map.put(playedId, p);
set.add(p);
}
}
public int top(int K){
int sum = 0;
Iterator<Pdetail> i = set.iterator();
while (K-- > 0 && i.hasNext()) {
sum+=i.next().score;
}
return sum;
}
public void reset(int playerId) {
Pdetail p = map.get(playerId);
set.remove(p);
p.score = 0;
}
public static void main(String[] args) {
}
}
|
package cefetiny;
public class ComandoEndIf extends Comando{
@Override
public void executa() {
System.out.println("Opa, endif?");
}
}
|
package com.altimetrik.demo.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ArtistInfo {
private Artist2 artist;
private Album album;
private Lyrics lyrics;
List <Artist> artistlist;
public List<Artist> getArtistList() {
return artistlist;
}
public void setArtistList(List<Artist> artistlist) {
this.artistlist = artistlist;
}
public Artist2 getArtist() {
return artist;
}
public void setArtist(Artist2 artist) {
this.artist = artist;
}
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
this.album = album;
}
// Getter Methods
public Lyrics getLyrics() {
return lyrics;
}
// Setter Methods
public void setLyrics(Lyrics lyrics) {
this.lyrics = lyrics;
}
@Override
public String toString() {
return "ArtistInfo [artist=" + artist + ", album=" + album + ", lyrics=" + lyrics + "]";
}
}
|
package com.mimi.mimigroup.api;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import java.io.IOException;
import okhttp3.OkHttpClient;
//Para: Void1:Kiểu dữ liệu tham số truyền vô doInBackground
//Void2:Kiểu dữ liệu truyền vô hàm onProcessUpdate
//Void3: Kiểu dữ liệu trả vê truyền vô hàm onPostExcute
public class SyncGet extends AsyncTask<Void, Integer, String> {
private String mUrl;
private String mType;
private APINetCallBack mHttpCallBack;
private Exception mException;
ProgressDialog pDialog;
public SyncGet(APINetCallBack mCallBack, String Url, String isType){
this.mUrl=Url;
this.mType=isType;
this.mHttpCallBack=mCallBack;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(mHttpCallBack!=null){
mHttpCallBack.onHttpStart();
}
}
@Override
protected String doInBackground(Void... arg0) {
try {
OkHttpClient Getclient = new OkHttpClient();
String ResponBody = APINet.GET(Getclient, mUrl);
return ResponBody;
/*
Gson gson = new Gson();
Type type = new TypeToken<Collection<ResHT_PARA>>() {}.getType();
Collection<ResHT_PARA> enums = gson.fromJson(response, type);
responseApis = enums.toArray(new ResHT_PARA[enums.size()]);
*/
} catch (IOException e) {
mException=e;
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer...values){
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Call HttpCallBack
//Log.d("SYNC_RESULT",result);
if(mHttpCallBack!=null){
if(mException==null){
mHttpCallBack.onHttpSuccess(result);
}else{
mHttpCallBack.onHttpFailer(mException);
}
}
}
}
|
/*
* 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 halloween.game.jam;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
/**
*
* @author Spencer Pelton
*/
public class MainMenu extends JPanel {
public MainMenu() {
JButton levelPickerBtn = new JButton("Level Picker");
levelPickerBtn.addActionListener((ActionEvent ae) -> {
switchToLevelPicker();
});
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener((ActionEvent ae) -> {
System.exit(0);
});
add(levelPickerBtn);
add(quitBtn);
}
public void switchToLevelPicker() {
MainFrame.switchPanel(new LevelPicker());
}
}
|
package at.fhj.swd.domain.exceptions;
import at.fhj.swd.exceptions.FhjWs2014Sd12PseException;
/**
* Denotes the top-level-exception-base-class for all domain-layer-exceptions.
* */
class DomainLayerException extends FhjWs2014Sd12PseException {
private static final long serialVersionUID = -7147962666368460968L;
DomainLayerException() {
super();
}
DomainLayerException(String msg) {
super(msg);
}
DomainLayerException(String msg, Throwable t) {
super(msg, t);
}
// TODO: Implement domain-layer specific exception-functionalities here!
}
|
package edu.kvcc.cis298.criminalintent;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public
class DatePickerFragment
extends DialogFragment
{
// public variables
public static final String
EXTRA_DATE
= "edu.kvcc.cis298.criminalintent.date";
// private variables
// model variables
private static final String
ARG_DATE
= "date";
private DatePicker
datePicker;
// public methods
public static
DatePickerFragment newInstance(Date date)
{
Bundle
args
= new Bundle();
args.putSerializable(
ARG_DATE,
date
);
DatePickerFragment
fragment
= new DatePickerFragment();
fragment.setArguments( args );
return fragment;
}
@NonNull
@Override
public
Dialog onCreateDialog(Bundle savedInstanceState)
{
Date
date
= (Date) getArguments().getSerializable( ARG_DATE );
Calendar
calendar
= Calendar.getInstance();
calendar.setTime( date );
int
year
= calendar.get( Calendar.YEAR );
int
month
= calendar.get( Calendar.MONTH );
int
day
= calendar.get( Calendar.DAY_OF_MONTH );
View
view
= LayoutInflater
.from( getActivity() )
.inflate(
R.layout.dialog_date,
null
);
datePicker
= (DatePicker) view.findViewById( R.id.dialog_date_date_picker );
datePicker.init(
year,
month,
day,
null
);
return new AlertDialog
.Builder( getActivity() )
.setView( view )
.setTitle( R.string.fragment_date_picker_tv_date_title )
.setPositiveButton(
android.R.string.ok,
new DialogInterface.OnClickListener()
{
@Override
public
void onClick(
DialogInterface dialogInterface,
int which
)
{
int
year
= datePicker.getYear();
int
month
= datePicker.getMonth();
int
day
= datePicker.getDayOfMonth();
Date
date
= new GregorianCalendar(
year,
month,
day
).getTime();
sendResult(
Activity.RESULT_OK,
date
);
}
}
)
.create();
}
// private methods
private
void sendResult(
int resultCode,
Date date
)
{
if ( getTargetFragment()
== null )
{
return;
}
Intent
intent
= new Intent();
intent.putExtra(
EXTRA_DATE,
date
);
getTargetFragment()
.onActivityResult(
getTargetRequestCode(),
resultCode,
intent
);
}
}
|
import java.util.*;
import java.io.*;
import java.nio.file.Path;
/**
* 모든 instruction의 정보를 관리하는 클래스. instruction data들을 저장한다
* 또한 instruction 관련 연산, 예를 들면 목록을 구축하는 함수, 관련 정보를 제공하는 함수 등을 제공 한다.
*/
public class InstTable {
/**
* inst.data 파일을 불러와 저장하는 공간.
* 명령어의 이름을 집어넣으면 해당하는 Instruction의 정보들을 리턴할 수 있다.
*/
HashMap<String, Instruction> instMap;
/**
* 클래스 초기화. 파싱을 동시에 처리한다.
* @param instFile : instuction에 대한 명세가 저장된 파일 이름
*/
public InstTable(String instFile) {
instMap = new HashMap<String, Instruction>();
openFile(instFile);
}
/**
* 입력받은 이름의 파일을 열고 해당 내용을 파싱하여 instMap에 저장한다.
*/
public void openFile(String fileName) {
File file = new File("src\\"+fileName);
String line;
try {
//한 줄씩 읽어 파일에 저장한다.
BufferedReader br = new BufferedReader(new FileReader(file));
while((line = br.readLine()) != null)
{
//'\t'을 기준으로 토큰화 한다.
instMap.put(line.split("\t")[0], new Instruction(line));
}
}
catch(IOException e) {
e.printStackTrace();
}
}
//get, set, search 등의 함수는 자유 구현
//opcode가 있는 명령어있는지 확인한다.
public boolean isOperation(String str) {
if(instMap.get(str) != null)
return true;
return false;
}
//Format을 출력해준다.
public int getForMat(String str) {
return instMap.get(str).format;
}
//Opcode를 출력해준다.
public int getOpcode(String str) {
try {
return instMap.get(str).opcode;
}
catch(Exception e) {
return -1;
}
}
}
/**
* 명령어 하나하나의 구체적인 정보는 Instruction클래스에 담긴다.
* instruction과 관련된 정보들을 저장하고 기초적인 연산을 수행한다.
*/
class Instruction {
/*
* 각자의 inst.data 파일에 맞게 저장하는 변수를 선언한다.
*
* ex)
* String instruction;
* int opcode;
* int numberOfOperand;
* String comment;
*/
/** instruction이 몇 바이트 명령어인지 저장. 이후 편의성을 위함 */
int format;
String instruction;
int opcode;
int numberOfOperand;
/**
* 클래스를 선언하면서 일반문자열을 즉시 구조에 맞게 파싱한다.
* @param line : instruction 명세파일로부터 한줄씩 가져온 문자열
*/
public Instruction(String line) {
parsing(line);
}
/**
* 일반 문자열을 파싱하여 instruction 정보를 파악하고 저장한다.
* @param line : instruction 명세파일로부터 한줄씩 가져온 문자열
*/
public void parsing(String line) {
String[] tok = line.split("\t");
instruction = tok[0];
numberOfOperand = Integer.parseInt(tok[1]);
if("3/4".equals(tok[2]))
format = 3;
else
format = Integer.parseInt(tok[2]);
opcode = Integer.parseInt(tok[3], 16);
}
//그 외 함수 자유 구현
@Override
public String toString() {
return "|"+instruction+"|"+numberOfOperand+"|"+format+'|'+opcode+"|";
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.spring;
import java.io.IOException;
import javax.security.auth.login.LoginContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoginContextFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(LoginContextFilter.class);
@Override
public void init(FilterConfig cfg) throws ServletException {
log.info("Init filter");
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) {
LoginContext ctx = null;
HttpSession sess = (HttpSession)((HttpServletRequest) request).getSession(false);
if (sess != null) {
ctx = (LoginContext) sess.getAttribute("ctx");
log.info("Context: {}", ctx);
}
try {
LoginContextHolder.set(ctx);
chain.doFilter(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
} finally {
LoginContextHolder.set(null);
}
}
@Override
public void destroy() {
log.info("Destroy filter");
}
}
|
package Tasks.LessonThree;
public class ArrayUtil {
public static int min(int[] array){
int min = array[0];
for (int i = 1; i < array.length; i++){
if (min > array[i]){
min = array[i];
}
}
return min;
}
public static int max(int[] array){
int max = 0;
for (int i = 1; i < array.length; i++){
if (max < array[i]){
max = array[i];
}
}
return max;
}
}
|
package edu.neu.dreamapp.ui;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import butterknife.BindView;
import edu.neu.dreamapp.R;
import edu.neu.dreamapp.base.BaseFragment;
import edu.neu.dreamapp.model.News;
/**
* @author agrawroh
* @version v1.0
*/
public class Reports extends BaseFragment {
private static final String ASSET_PATH = "file:///android_asset/";
private static final String CLASS_TAG = "Reports";
@BindView(R.id.news_list)
RecyclerView rv;
@BindView(R.id.refreshLayout)
MaterialRefreshLayout refreshLayout;
@Override
public int getContentViewId() {
return R.layout.reports_main;
}
@Override
protected String getTAG() {
return CLASS_TAG;
}
@Override
protected void initAllMembersView(Bundle savedInstanceState) {
/* Set Recycler View */
rv.setLayoutManager(new LinearLayoutManager(context));
/* Setup RefreshLayout Listener, When Page Refreshes, Load Again */
refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
@Override
public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
/* Load Data */
loadData();
}
});
/* Auto Refreshes The Layout In-Order To Fetch The NEWS */
refreshLayout.autoRefresh();
}
/**
* Load Data
*/
private void loadData() {
SharedPreferences prefs = getActivity().getApplicationContext().getSharedPreferences("DREAM_APP_CXT", Context.MODE_PRIVATE);
/* Get Responses */
Set<String> set = prefs.getStringSet("SR_RESP_SET_PRE", new HashSet<String>());
Log.i("*****", String.valueOf(set.size()));
if (0 < set.size()) {
List<News> newsRecords = new ArrayList<>();
/* Iterate Surveys */
for (final String value : set) {
String[] values = value.split(";");
News n = new News();
n.setHeader("Survey Response");
n.setAuthor("Date: " + values[0]);
n.setContent("Total Students: " + values[1].split(",").length
+ "\n"
+ "Students Present: " + values[2].split(",").length);
newsRecords.add(n);
}
rv.setAdapter(new Reports.NewsListAdapter(newsRecords));
refreshLayout.finishRefresh();
}
}
/**
* News List Adapter
*/
class NewsListAdapter extends RecyclerView.Adapter<Reports.NewsViewHolder> {
private final List<News> news;
NewsListAdapter(List<News> news) {
this.news = news;
}
@Override
public Reports.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View v = layoutInflater.inflate(R.layout.news_card, viewGroup, false);
return new Reports.NewsViewHolder(v);
}
private byte[] loadHTMLasByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
@Override
@SuppressWarnings("all")
public void onBindViewHolder(Reports.NewsViewHolder newsViewHolder, final int i) {
/* Set Attributes */
newsViewHolder.newsImage.setWebViewClient(new InAppBrowser());
newsViewHolder.newsImage.getSettings().setLoadsImagesAutomatically(true);
newsViewHolder.newsImage.getSettings().setJavaScriptEnabled(true);
newsViewHolder.newsImage.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
/* Read Chart HTML */
String fileContent = "";
try {
AssetManager assetManager = getActivity().getAssets();
InputStream in = assetManager.open("piechart.html");
byte[] bytes = loadHTMLasByteArray(in);
fileContent = new String(bytes, "UTF-8");
} catch (IOException ex) {
Toast.makeText(getContext(), "Failed To Load Google Charts!", Toast.LENGTH_LONG).show();
}
final String content = fileContent;
String[] nums = news.get(i).getContent().split("\n");
final String formattedContent = content.replace("[#DataTable#]", "['Attendance','Percentage'],['Present',"
+ Integer.parseInt(nums[0].split(": ")[1])
+ "],['Absent',"
+ Integer.parseInt(nums[1].split(": ")[1]) + "]");
newsViewHolder.newsImage.loadDataWithBaseURL(ASSET_PATH, formattedContent, "text/html", "UTF-8", null);
newsViewHolder.newsHeader.setText(news.get(i).getHeader());
newsViewHolder.newsAuthor.setText(news.get(i).getAuthor());
newsViewHolder.newsContent.setText(news.get(i).getContent());
/* Add Listener */
newsViewHolder.holder.setBackground(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.selector_new_card_white));
newsViewHolder.newsHeader.setTextColor(getActivity().getApplicationContext().getResources().getColor(R.color.app_black));
newsViewHolder.newsAuthor.setTextColor(getActivity().getApplicationContext().getResources().getColor(R.color.app_black));
newsViewHolder.newsContent.setTextColor(getActivity().getApplicationContext().getResources().getColor(R.color.app_black));
newsViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail("agrawroh@bu.edu", "Report", formattedContent.replace("./loader.js", "https://www.gstatic.com/charts/loader.js"));
}
});
}
/**
* Send Email
*
* @param recipient Recipient
* @param subject Subject
* @param body Body
*/
protected void sendEmail(String recipient, String subject, String body) {
String[] recipients = {recipient.toString()};
Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
email.setType("text/html");
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
email.putExtra(Intent.EXTRA_TEXT, body.toString());
try {
startActivity(Intent.createChooser(email, "Choose Email Client..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity().getApplicationContext(), "No Email Client Installed!",
Toast.LENGTH_LONG).show();
}
}
@Override
public int getItemCount() {
return news.size();
}
}
/**
* News View Holder
*/
class NewsViewHolder extends RecyclerView.ViewHolder {
private WebView newsImage;
private TextView newsHeader;
private TextView newsAuthor;
private TextView newsContent;
private View holder;
NewsViewHolder(View itemView) {
super(itemView);
holder = itemView.findViewById(R.id.holder);
newsImage = itemView.findViewById(R.id.news_image);
newsHeader = itemView.findViewById(R.id.news_header);
newsAuthor = itemView.findViewById(R.id.news_author);
newsContent = itemView.findViewById(R.id.news_body);
}
}
/**
* InApp Browser
*/
private class InAppBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
|
package com.example.hp.above;
import android.app.ActionBar;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class AptitudeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aptitude);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public void opennumbers(View view)
{
Intent i = new Intent(this, NumbersActivity.class);
startActivity(i);
}
public void open_lcm_hcf(View view)
{
Intent i = new Intent(this, LCMandHCFActivity.class);
startActivity(i);
}
public void openworkwages(View view)
{
Intent i = new Intent(this, WorkAndWagesActivity.class);
startActivity(i);
}
public void openpipescisterns(View view)
{
Intent i = new Intent(this, PipesAndCisternsActivity.class);
startActivity(i);
}
public void opentimespeeddistance(View view)
{
Intent i = new Intent(this, TimeSpeedDistanceActivity.class);
startActivity(i);
}
public void opentrainsboatsstreams(View view)
{
Intent i = new Intent(this, TrainsBoatsStreamsActivity.class);
startActivity(i);
}
public void openpercentage(View view)
{
Intent i = new Intent(this, PercentageActivity.class);
startActivity(i);
}
public void openratioproprtionpartnership(View view)
{
Intent i = new Intent(this, RatioProportionPartnershipActivity.class);
startActivity(i);
}
public void openmixturesalligation(View view)
{
Intent i = new Intent(this, MixtureAndAlligationActivity.class);
startActivity(i);
}
public void openaverage(View view)
{
Intent i = new Intent(this, AverageActivity.class);
startActivity(i);
}
public void openage(View view)
{
Intent i = new Intent(this, AgeActivity.class);
startActivity(i);
}
public void openprofitloss(View view)
{
Intent i = new Intent(this, ProfitAndLossActivity.class);
startActivity(i);
}
public void opensimpleinterest(View view)
{
Intent i = new Intent(this, SimpleInterestActivity.class);
startActivity(i);
}
public void opencompoundinterest(View view)
{
Intent i = new Intent(this, CompoundInterestActivity.class);
startActivity(i);
}
public void openmensuration2d(View view)
{
Intent i = new Intent(this, Mensuration2dActivity.class);
startActivity(i);
}
public void openmensuration3d(View view)
{
Intent i = new Intent(this, Mensuration3dActivity.class);
startActivity(i);
}
public void openprogression(View view)
{
Intent i = new Intent(this, ProgressionsActivity.class);
startActivity(i);
}
public void openpermutation_combination(View view)
{
Intent i = new Intent(this, PermutationAndCombinationActivity.class);
startActivity(i);
}
public void openprobability(View view)
{
Intent i = new Intent(this, ProbabilityActivity.class);
startActivity(i);
}
public void openclocks(View view)
{
Intent i = new Intent(this, ClocksActivity.class);
startActivity(i);
}
public void opencalenders(View view)
{
Intent i = new Intent(this, CalendersActivity.class);
startActivity(i);
}
public void openrace(View view)
{
Intent i = new Intent(this, RaceActivity.class);
startActivity(i);
}
}
|
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @类名:LetsSimpleController.java
* @创建人:付祉旋
* @创建时间:2019年3月8日
* @版本:1.0
*/
@Controller
@RequestMapping("/LetsSimpleController")
public class LetsSimpleController {
@RequestMapping(value = "/main")
public ModelAndView LetsSimple() {
ModelAndView mv = new ModelAndView();
mv.setViewName("letsSimple");
return mv;
}
@RequestMapping(value = "/about")
public ModelAndView about() {
ModelAndView mv = new ModelAndView();
mv.setViewName("about");
return mv;
}
}
|
package com.classcheck.window;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import com.classcheck.panel.TestCodeTabbedPane;
public class TestCodeEditWindow extends JDialog {
private Map<String, String> exportFileMap;
private TestCodeTabbedPane tctp;
private static boolean opened = false;
private boolean canceled;
private JButton okButton;
private JButton cancelButton;
public TestCodeEditWindow(Map<String, String> fileMap) {
super((JFrame) null);
this.exportFileMap = fileMap;
this.opened = true;
this.canceled = false;
setMinimumSize(new Dimension(800, 500));
setSize(new Dimension(1000, 1000));
setLocationRelativeTo(null);
setModal(true);
initComponent();
initEvent();
pack();
setVisible(true);
}
public static boolean isOpened() {
return opened;
}
public boolean isCanceled() {
return canceled;
}
public Map<String, String> getExportFileMap() {
return exportFileMap;
}
public HashMap<String, RSyntaxTextArea> getExportEditCodeMap() {
return this.tctp.getExportEditCodeMap();
}
private void initComponent() {
JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 60, 5));
this.tctp = new TestCodeTabbedPane(exportFileMap);
this.okButton = new JButton("OK");
this.cancelButton = new JButton("Cancel");
buttonPane.add(okButton);
buttonPane.add(cancelButton);
setTitle("テストコード");
this.setLayout(new BorderLayout());
add(tctp,BorderLayout.CENTER);
add(buttonPane,BorderLayout.SOUTH);
}
private void initEvent() {
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component c = (Component)e.getSource();
Window w = SwingUtilities.getWindowAncestor(c);
w.dispose();
canceled = false;
opened = false;
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component c = (Component)e.getSource();
Window w = SwingUtilities.getWindowAncestor(c);
w.dispose();
canceled = true;
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
opened = true;
}
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
opened = false;
canceled = true;
}
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
opened = false;
canceled = true;
}
});
}
}
|
/*
* 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 tolteco.sigma.view;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Date;
import tolteco.sigma.model.entidades.Version;
import tolteco.sigma.utils.SDate;
/**
* Sobre o SIGMA, contém autores, versão do sistema e data de publicação
* @author Maycon
*/
public class About extends javax.swing.JFrame {
Version ver=null;
Date date=null;
/**
* Creates new form About
*/
public About() {
initComponents();
initNoicon (); //Seta "Logo vazio".
//Abre a janela no meio da tela, independente da resolução.
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
}
/**
* 12/12/15 - Juliano Felipe
* Seta icone 1*1px (para "remover" icone default)
*/
private void initNoicon (){
Image No_ico = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
this.setIconImage(No_ico);
}
public MainFrame telaanterior;
/**
* 03/02/16 - Juliano Felipe
* "Pseudo-construtor", chama o construtor padrão, função de reutilização de jFrame e salva
* a instância do jFrame que chamou este (para poder habilitá-lo quando esta tela é fechada.
* @param telanterior - Instância da tela anterior.
* @param ver
* @param date
*/
public About(MainFrame telanterior, Version ver, Date date) {
//Chamar construtor
this();
this.telaanterior = telanterior;
this.ver = ver;
this.date = date;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
VersionLabel = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
DateLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About SIGMA");
setIconImages(null);
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jLabel2.setText("Sistema Integrado de Gerenciamento de");
jLabel3.setText("Mecânica Automobilística");
jLabel4.setText("Desenvolvido em 2016-2017 por");
jLabel5.setText("Anderson Bottega da Silva");
jLabel6.setText("Juliano Felipe da Silva");
jLabel7.setText("Maycon de Queiroz Oliveira");
jLabel8.setText("Versão:");
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jLabel1.setFont(new java.awt.Font("Cambria Math", 0, 36)); // NOI18N
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tolteco/sigma/view/images/Sigma-100x100.png"))); // NOI18N
jLabel1.setText(" SIGMA");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1))
);
jLabel1.getAccessibleContext().setAccessibleName("SIGMA");
VersionLabel.setText("-.--");
jLabel9.setText("Data de publicação:");
DateLabel.setText("DD/MM/AAAA");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(VersionLabel))
.addComponent(jLabel7)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DateLabel)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(1, 1, 1)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(VersionLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(DateLabel))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//Botão OK pressionado
this.dispose();
telaanterior.setEnabled(true);
telaanterior.requestFocus();
}//GEN-LAST:event_jButton1ActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
/**
* 05/01 - Maycon
* Tela fechada
*/
telaanterior.setEnabled(true);
telaanterior.requestFocus();
}//GEN-LAST:event_formWindowClosed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
VersionLabel.setText(ver.shortString());
DateLabel.setText(SDate.DATE_FORMAT_NOTIME.format(date));
}//GEN-LAST:event_formWindowOpened
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Windows look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Windows (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new About().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel DateLabel;
private javax.swing.JLabel VersionLabel;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package Lab02.Zad2;
public class Sound {
Codec codec = null;
int speakers = 0;
public Sound(int speakers) {
this.speakers = speakers;
}
public void chooseCodec(){
if(speakers <= 2)
this.codec = new DolbyDigital();
else
this.codec = new DolbyProLogic();
}
public void Run(){
this.codec.codec();
}
}
|
package com.rc.portal.dao;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.TMember;
import com.rc.portal.vo.TMemberExample;
public interface TMemberDAO {
int countByExample(TMemberExample example) throws SQLException;
int deleteByExample(TMemberExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(TMember record) throws SQLException;
Long insertSelective(TMember record) throws SQLException;
List selectByExample(TMemberExample example) throws SQLException;
TMember selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(TMember record, TMemberExample example) throws SQLException;
int updateByExample(TMember record, TMemberExample example) throws SQLException;
int updateByPrimaryKeySelective(TMember record) throws SQLException;
int updateByPrimaryKey(TMember record) throws SQLException;
}
|
package pl.coderslab.servlet.order;
import pl.coderslab.dao.DbInit;
import pl.coderslab.dao.OrderDao;
import pl.coderslab.model.Order;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet(name = "OrdersShowAllServlet", urlPatterns = "/orders/show_all")
public class ShowAllServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
try {
// DbInit.createTableOrders();
Order[] orders = OrderDao.loadAll();
request.setAttribute("orders", orders);
getServletContext().getRequestDispatcher("/orders/show_all.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Error while fetching orders. ", e);
}
}
}
|
import java.util.EmptyStackException;
import java.util.Arrays;
/**
A vector array that implements StackInterface.
@author Minwoo Soh
*/
public final class Vector<T> implements StackInterface<T>
{
private static final int DEFAULT_CAPACITY = 5;
private static final int MAX_CAPACITY = 10000; // To make sure memory doesn't run out.
private T[] vector;
private int numberOfEntries;
private boolean initialized = false;
/** Creates an empty vector array with the default capacity of 5 */
public Vector()
{
this(DEFAULT_CAPACITY);
} // end default constructor
/** Creates an empty vector array with the a given capacity.
@param desiredCapacity The integer capacity desired. */
public Vector(int desiredCapacity)
{
if (desiredCapacity <= MAX_CAPACITY)
{
@SuppressWarnings("unchecked")
T[] tempVector = (T[])new Object[desiredCapacity]; // Unchecked cast
vector = tempVector;
numberOfEntries = 0;
initialized = true;
}
else
{
throw new IllegalStateException("Cannot create a vector that exceeds " +
"maximum capacity of 10000.");
} // end if
} // end contructor
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry)
{
checkInitialization();
if(numberOfEntries == vector.length)
{
// Vectory array is full.
increaseCapacity(); // Increases size of vector array before adding.
vector[numberOfEntries] = newEntry;
numberOfEntries++;
}
else
{
// Vector array is not full.
vector[numberOfEntries] = newEntry;
numberOfEntries++;
} // end if
} // end push
/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop()
{
checkInitialization();
T item = null;
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
item = vector[numberOfEntries-1]; // Setting item inside temp.
vector[numberOfEntries-1] = null; // Removing item from array.
numberOfEntries--; // Decrement item in stack count.
return item;
} // end if
} // end pop
/** Retrieves this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek()
{
checkInitialization();
T item = null;
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
item = vector[numberOfEntries-1];
return item;
} // end if
} // end peek
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
/** Removes all entries from this stack. */
public void clear()
{
while(!isEmpty())
{
pop();
} // end while
} // end clear
/** Checks if vector array capacity is too large.
@param capacity Capacity number that will be checked.
@throws IllegalStateException if the capacity excceds maximum capacity. */
public void checkCapacity(int capacity)
{
if(capacity > MAX_CAPACITY)
{
throw new IllegalStateException("Cannot create a vector stack that exceeds" +
"maximum size of " + MAX_CAPACITY);
} // end if
} // end checkCapacity
/** Increases the size of vector array by 1. */
public void increaseCapacity()
{
checkInitialization();
int newLength = vector.length + 1;
checkCapacity(newLength);
vector = Arrays.copyOf(vector, newLength);
} // end increaseCapacity
/** Checks if the Vector object is initialized.
@throws SecurityException if the object is not initialized. */
private void checkInitialization()
{
if (!initialized)
throw new SecurityException("Vector object is not initialized properly.");
} // end checkInitialization
} // end of Vector
|
package com.example.chrisc.bestlineaward;
import Listeners.*;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomArrayAdapter<T> extends ArrayAdapter<T> {
public CustomArrayAdapter(Context context, T[] objects)
{
super(context, android.R.layout.simple_spinner_item, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
((TextView)v).setTextColor(Color.WHITE);
return v;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
TextView text = (TextView)view.findViewById(android.R.id.text1);
text.setBackgroundColor(Color.BLACK);
text.setTextColor(Color.WHITE);
return view;
}
}
|
package org.lightadmin.demo.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class AbstractEntity {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private Long id;
public Long getId() {
return id;
}
@Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( this.id == null || obj == null || !( this.getClass().equals( obj.getClass() ) ) ) {
return false;
}
AbstractEntity that = ( AbstractEntity ) obj;
return this.id.equals( that.getId() );
}
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
}
|
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import jdk.test.lib.Utils;
import jdk.test.lib.util.JarUtils;
/**
* A builder for a common Java agent.
* Can be used directly from the jtreg test header to
* build a java agent before the test is executed.
*
* E.g.:
* @run driver jdk.test.lib.util.JavaAgentBuilder
* jdk.jfr.javaagent.EventEmitterAgent EventEmitterAgent.jar
*
*/
public class JavaAgentBuilder {
/**
* Build a java agent jar file with a given agent class.
*
* @param args[0] fully qualified name of an agent class
* @param args[1] file name of the agent jar to be created
* @throws IOException
*/
public static void main(String... args) throws IOException {
String agentClass = args[0];
String agentJar = args[1];
System.out.println("Building " + agentJar + " with agent class " + agentClass);
build(agentClass, agentJar);
}
/**
* Build a java agent jar file with a given agent class.
* The agent class will be added as both premain class and agent class.
*
* @param agentClass fully qualified name of an agent class
* @param agentJar file name of the agent jar to be created
* the file will be placed in a current work directory
* @throws IOException
*/
public static void build(String agentClass, String agentJar) throws IOException {
Manifest mf = new Manifest();
Attributes attrs = mf.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attrs.putValue("Premain-Class", agentClass);
attrs.putValue("Agent-Class", agentClass);
Path jarFile = Paths.get(".", agentJar);
String testClasses = Utils.TEST_CLASSES;
String agentPath = agentClass.replace(".", File.separator) + ".class";
Path agentFile = Paths.get(testClasses, agentPath);
Path dir = Paths.get(testClasses);
JarUtils.createJarFile(jarFile, mf, dir, agentFile);
System.out.println("Agent built:" + jarFile.toAbsolutePath());
}
}
|
package com.mysql.cj.jdbc.ha;
import com.mysql.cj.jdbc.jmx.ReplicationGroupManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class ReplicationConnectionGroupManager {
private static HashMap<String, ReplicationConnectionGroup> GROUP_MAP = new HashMap<>();
private static ReplicationGroupManager mbean = new ReplicationGroupManager();
private static boolean hasRegisteredJmx = false;
public static synchronized ReplicationConnectionGroup getConnectionGroupInstance(String groupName) {
if (GROUP_MAP.containsKey(groupName))
return GROUP_MAP.get(groupName);
ReplicationConnectionGroup group = new ReplicationConnectionGroup(groupName);
GROUP_MAP.put(groupName, group);
return group;
}
public static void registerJmx() throws SQLException {
if (hasRegisteredJmx)
return;
mbean.registerJmx();
hasRegisteredJmx = true;
}
public static ReplicationConnectionGroup getConnectionGroup(String groupName) {
return GROUP_MAP.get(groupName);
}
public static Collection<ReplicationConnectionGroup> getGroupsMatching(String group) {
if (group == null || group.equals("")) {
Set<ReplicationConnectionGroup> set = new HashSet<>();
set.addAll(GROUP_MAP.values());
return set;
}
Set<ReplicationConnectionGroup> s = new HashSet<>();
ReplicationConnectionGroup o = GROUP_MAP.get(group);
if (o != null)
s.add(o);
return s;
}
public static void addSlaveHost(String group, String hostPortPair) throws SQLException {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
cg.addSlaveHost(hostPortPair);
}
public static void removeSlaveHost(String group, String hostPortPair) throws SQLException {
removeSlaveHost(group, hostPortPair, true);
}
public static void removeSlaveHost(String group, String hostPortPair, boolean closeGently) throws SQLException {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
cg.removeSlaveHost(hostPortPair, closeGently);
}
public static void promoteSlaveToMaster(String group, String hostPortPair) throws SQLException {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
cg.promoteSlaveToMaster(hostPortPair);
}
public static long getSlavePromotionCount(String group) throws SQLException {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
long promoted = 0L;
for (ReplicationConnectionGroup cg : s) {
long tmp = cg.getNumberOfSlavePromotions();
if (tmp > promoted)
promoted = tmp;
}
return promoted;
}
public static void removeMasterHost(String group, String hostPortPair) throws SQLException {
removeMasterHost(group, hostPortPair, true);
}
public static void removeMasterHost(String group, String hostPortPair, boolean closeGently) throws SQLException {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
cg.removeMasterHost(hostPortPair, closeGently);
}
public static String getRegisteredReplicationConnectionGroups() {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(null);
StringBuilder sb = new StringBuilder();
String sep = "";
for (ReplicationConnectionGroup cg : s) {
String group = cg.getGroupName();
sb.append(sep);
sb.append(group);
sep = ",";
}
return sb.toString();
}
public static int getNumberOfMasterPromotion(String groupFilter) {
int total = 0;
Collection<ReplicationConnectionGroup> s = getGroupsMatching(groupFilter);
for (ReplicationConnectionGroup cg : s)
total = (int)(total + cg.getNumberOfSlavePromotions());
return total;
}
public static int getConnectionCountWithHostAsSlave(String groupFilter, String hostPortPair) {
int total = 0;
Collection<ReplicationConnectionGroup> s = getGroupsMatching(groupFilter);
for (ReplicationConnectionGroup cg : s)
total += cg.getConnectionCountWithHostAsSlave(hostPortPair);
return total;
}
public static int getConnectionCountWithHostAsMaster(String groupFilter, String hostPortPair) {
int total = 0;
Collection<ReplicationConnectionGroup> s = getGroupsMatching(groupFilter);
for (ReplicationConnectionGroup cg : s)
total += cg.getConnectionCountWithHostAsMaster(hostPortPair);
return total;
}
public static Collection<String> getSlaveHosts(String groupFilter) {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(groupFilter);
Collection<String> hosts = new ArrayList<>();
for (ReplicationConnectionGroup cg : s)
hosts.addAll(cg.getSlaveHosts());
return hosts;
}
public static Collection<String> getMasterHosts(String groupFilter) {
Collection<ReplicationConnectionGroup> s = getGroupsMatching(groupFilter);
Collection<String> hosts = new ArrayList<>();
for (ReplicationConnectionGroup cg : s)
hosts.addAll(cg.getMasterHosts());
return hosts;
}
public static long getTotalConnectionCount(String group) {
long connections = 0L;
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
connections += cg.getTotalConnectionCount();
return connections;
}
public static long getActiveConnectionCount(String group) {
long connections = 0L;
Collection<ReplicationConnectionGroup> s = getGroupsMatching(group);
for (ReplicationConnectionGroup cg : s)
connections += cg.getActiveConnectionCount();
return connections;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\ha\ReplicationConnectionGroupManager.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
/**
*
*/
package com.elitech.quicktortoise.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
//import com.orhanobut.logger.Logger;
/**
* @author King
*/
public class BaseFragment extends Fragment {
protected final String LOG_TAG = this.getClass().getSimpleName();
protected BaseFragment mFContext;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
//
super.onCreate(savedInstanceState);
mFContext = this;
// Logger.init(LOG_TAG);
// Logger.i(LOG_TAG, "creating " + getClass() + " at " + System.currentTimeMillis());
}
@Override
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
//
// Logger.i(LOG_TAG, "onCreateView called! ");
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onPause() {
//
super.onPause();
// Logger.i(LOG_TAG, "onPause called! ");
}
@Override
public void onResume() {
//
super.onResume();
// Logger.i(LOG_TAG, "onResume called! ");
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
//
super.setUserVisibleHint(isVisibleToUser);
// Logger.i(LOG_TAG, "onResume called! ");
}
@Override
public void onStop() {
//
super.onStop();
// Logger.i(LOG_TAG, "onStop called! ");
}
@Override
public void onDestroy() {
//
super.onDestroy();
// Logger.i(LOG_TAG, "onDestroy called! ");
}
}
|
/*
* 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 tolteco.sigma.model.dao.jdbc;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import tolteco.sigma.model.dao.DatabaseException;
import tolteco.sigma.model.dao.ServicoDAO;
import tolteco.sigma.model.entidades.Servico;
import tolteco.sigma.model.entidades.Situacao;
import tolteco.sigma.view.Sistema;
/**
*
* @author Juliano_Felipe
*/
public class JDBCServicoDAO extends JDBCAbstractDAO<Servico> implements ServicoDAO{
@Override
public int insert(Servico t) throws DatabaseException {
String query = "INSERT INTO Servico " +
"(userId,clienteId,Placa,Quilometragem,Modelo,Situacao,Observacoes) " +
"VALUES (?,?,?,?,?,?,?)";
PreparedStatement pst = null;
try {
pst = connection.prepareStatement(query);
pst.setInt (1, Sistema.getUserID());
pst.setInt (2, t.getIdcliente());
pst.setString(3, t.getPlaca());
pst.setDouble(4, t.getKm());
pst.setString(5, t.getModelo());
pst.setInt (6, t.getSituacao().getCodigo());
pst.setString(7, t.getObs());
pst.execute();
} catch (SQLException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return getNextId()-1;
}
@Override
public boolean remove(Servico t) throws DatabaseException {
String query = "DELETE FROM Servico WHERE servicoId=" + t.getRowid();
PreparedStatement pst = null;
try {
pst = connection.prepareStatement(query);
pst.execute();
} catch (SQLException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return true;
}
@Override
public boolean update(Servico t) throws DatabaseException {
String query = "UPDATE Servico " +
"SET userId=?, clienteId=?, PlacaPlaca=?, " +
"Quilometragem=?, Modelo=?, Situacao=?, Observacoes=? " +
"WHERE servicoId=" + t.getRowid();
PreparedStatement pst = null;
try {
pst = connection.prepareStatement(query);
pst.setInt (1, Sistema.getUserID());
pst.setInt (2, t.getIdcliente());
pst.setString(3, t.getPlaca());
pst.setDouble(4, t.getKm());
pst.setString(5, t.getModelo());
pst.setInt (6, t.getSituacao().getCodigo());
pst.setString(7, t.getObs());
pst.execute();
} catch (SQLException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return true;
}
@Override
public List<Servico> selectAll() throws DatabaseException {
List<Servico> lista = new ArrayList<>();
String query = "SELECT servicoId, * FROM Servico";
PreparedStatement pst = null;
ResultSet rs=null;
try {
pst = connection.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next()){
lista.add(getInstance(rs));
}
rs.close();
} catch (SQLException | DatabaseException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return lista;
}
@Override
public Servico search(int primaryKey) throws DatabaseException {
Servico cliente;
String query = "SELECT servicoId, * FROM Servico WHERE servicoId=?";
PreparedStatement pst = null;
ResultSet rs;
try {
pst = connection.prepareStatement(query);
pst.setInt(1, primaryKey);
rs = pst.executeQuery();
cliente = getInstance(rs);
rs.close();
} catch (SQLException | DatabaseException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return cliente;
}
@Override
public List<Servico> select(String modelo) throws DatabaseException {
List<Servico> lista = new ArrayList<>();
String query = "SELECT servicoId, * FROM Servico WHERE"
+ " (Modelo LIKE '%" + modelo + "%')";
PreparedStatement pst = null;
ResultSet rs;
try {
pst = connection.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next()){
lista.add(getInstance(rs));
}
rs.close();
} catch (SQLException | DatabaseException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return lista;
}
@Override
public List<Servico> searchByPlaca(String placa) throws DatabaseException {
List<Servico> lista = new ArrayList();
String query = "SELECT servicoId, * FROM Servico WHERE placa=?";
PreparedStatement pst = null;
ResultSet rs;
try {
pst = connection.prepareStatement(query);
pst.setString(1, placa);
rs = pst.executeQuery();
while (rs.next()){
lista.add(getInstance(rs));
}
rs.close();
} catch (SQLException | DatabaseException e) {
//String error = e.getClass().getName() + ": " + e.getMessage();
throw new DatabaseException(e);
} finally {
if (pst != null)
try {
pst.close();
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
return lista;
}
@Override
protected Servico getInstance(ResultSet rs) throws DatabaseException{
try {
return new Servico(
rs.getInt("servicoId"),
rs.getInt("clienteId"),
rs.getString("Placa"),
rs.getString("Modelo"),
rs.getDouble("Quilometragem"),
Situacao.porCodigo(rs.getInt("Situacao")),
rs.getString("Observacoes"),
rs.getInt("userId"));
} catch (SQLException ex) {
//Logger.getLogger(JDBCClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
throw new DatabaseException(ex);
}
}
@Override
public int getNextId() throws DatabaseException {
String query = "SELECT servicoId FROM Servico ORDER BY servicoId";
int lastId = -2;
try (PreparedStatement pst = connection.prepareStatement(query); ResultSet rs = pst.executeQuery()) {
lastId = -1;
while (rs.next()){
lastId = rs.getInt("servicoId");
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
return lastId+1;
}
}
|
package cn.jishuz.library.adpter;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.jishuz.library.R;
public class BookAdapter extends BaseAdapter {
private ArrayList<String> mBookCore = new ArrayList<String>();
private ArrayList<Bitmap> mBookImage = new ArrayList<Bitmap>();
private LayoutInflater mInflater;
private Context mContext;
LinearLayout.LayoutParams params;
private int resourceId;
public BookAdapter(Context context, int textViewResourceId, ArrayList<String> bookCore,
ArrayList<Bitmap> bookImage) {
mContext = context;
mBookCore = bookCore;
mBookImage = bookImage;
mInflater = LayoutInflater.from(mContext);
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
resourceId = textViewResourceId;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mBookCore.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mBookCore.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
View view;
if (convertView == null) {
viewHolder = new ViewHolder();
view = mInflater.inflate(resourceId, null);
viewHolder.bookScore = (TextView) view.findViewById(R.id.adapter_textView);
viewHolder.bookImage = (ImageView) view.findViewById(R.id.adapter_iamge);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.bookScore.setText(mBookCore.get(position));
viewHolder.bookImage.setImageBitmap(mBookImage.get(position));
return view;
}
class ViewHolder {
TextView bookScore;
ImageView bookImage;
}
}
|
package firstPg.exceptions;
public class BookDoesNotExistException extends Exception{
public BookDoesNotExistException (String title) {
super(String.format("A book with this title %s doesn't exist!", title));
}
}
|
package pl.training.shop.product.ui;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import pl.training.shop.category.model.CategoriesService;
import pl.training.shop.product.model.ProductsService;
@Route("add-product")
public class AddProductView extends VerticalLayout {
private ProductForm productForm;
public AddProductView(ProductsService productsService, CategoriesService categoriesService) {
productForm = new ProductForm(productsService, categoriesService);
add(productForm);
}
}
|
package com.lubao.forbackend.controller;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.SimpleFormatter;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lubao.forbackend.domain.CommentMix;
import com.lubao.forbackend.domain.CommentMix_2;
import com.lubao.forbackend.domain.CommentTable;
import com.lubao.forbackend.domain.CoversionMix;
import com.lubao.forbackend.domain.CoversionRequest;
import com.lubao.forbackend.domain.CoversionTable;
import com.lubao.forbackend.domain.NidAndCid;
import com.lubao.forbackend.domain.NidsRequest;
import com.lubao.forbackend.domain.PersonalTable;
import com.lubao.forbackend.domain.SupportRequest;
import com.lubao.forbackend.domain.Test;
import com.lubao.forbackend.service.CommentService;
import com.lubao.forbackend.service.CoversionService;
import com.lubao.forbackend.service.PersonalService;
import com.lubao.forbackend.util.Constant;
@Controller
@RequestMapping("api")
public class DbController {
@Resource
private CommentService commentServiceImp;
@Resource
private CoversionService coversionServiceImp;
@Resource
private PersonalService personalServiceImp;
// 获得帖子
@RequestMapping(value = "coversion/getCoversionList", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getCoversionList(@RequestParam("nid") String nid) {
// 暂时用,获得一个
System.out.println("获得帖子");
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CoversionMix[] mixs = coversionServiceImp.getCoversions();
int index = 0;
for (CoversionMix coversionMix : mixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", coversionMix.getCid());
jsonObject.put("nid", coversionMix.getNid());
jsonObject.put("titleText", coversionMix.getTitle());
jsonObject.put("contentText", coversionMix.getContent());
jsonObject.put("supportNum", coversionMix.getSupportNum());
jsonObject.put("commitNums", coversionMix.getCommentNum());
jsonObject.put("nick", coversionMix.getNick());
jsonObject.put("url", coversionMix.getImageUrl());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(coversionMix.getDate()));
jsonObject.put("index", index);
jsonObject.put("thumbnail", coversionMix.getThumbnail());
NidAndCid nidAndCid = new NidAndCid();
nidAndCid.setCid(coversionMix.getCid());
nidAndCid.setNid(Integer.parseInt(nid));
boolean isSupprot = coversionServiceImp.isSupport(nidAndCid);
if (isSupprot == true)
jsonObject.put("isSupport", "true");
else
jsonObject.put("isSupport", "false");
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("coversionList", jsonArray);
return bigjJsonObject;
}
// 获得帖子
@RequestMapping(value = "coversion/getCoversionByCid", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getCoversionByCid(@RequestParam("cid") int cid,@RequestParam("nid") int nid) {
System.out.println("获得帖子,一个");
JSONObject jsonObject = new JSONObject();
CoversionMix coversionMix=coversionServiceImp.getCoversionMix(cid);
jsonObject.put("cid", coversionMix.getCid());
jsonObject.put("nid", coversionMix.getNid());
jsonObject.put("titleText", coversionMix.getTitle());
jsonObject.put("contentText", coversionMix.getContent());
jsonObject.put("supportNum", coversionMix.getSupportNum());
jsonObject.put("commitNums", coversionMix.getCommentNum());
jsonObject.put("nick", coversionMix.getNick());
jsonObject.put("url", coversionMix.getImageUrl());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(coversionMix.getDate()));
jsonObject.put("thumbnail", coversionMix.getThumbnail());
NidAndCid nidAndCid = new NidAndCid();
nidAndCid.setCid(coversionMix.getCid());
nidAndCid.setNid(nid);
boolean isSupprot = coversionServiceImp.isSupport(nidAndCid);
if (isSupprot == true)
jsonObject.put("isSupport", "true");
else
jsonObject.put("isSupport", "false");
return jsonObject;
}
// 获得评论,根据cid
@RequestMapping(value = "comment/getCommentList", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getCommentList(@RequestParam("cid") int cid) {
// 获取一个coversion的commentList
System.out.println("获得评论,根据cid");
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CommentMix[] commentMixs = commentServiceImp.getCommentMixsByID(cid);
int index = 0;
for (CommentMix commentMix : commentMixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", commentMix.getCid());
jsonObject.put("nid", commentMix.getNid());
jsonObject.put("content", commentMix.getContent());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(commentMix.getDate()));
jsonObject.put("nick", commentMix.getNick());
jsonObject.put("thumbnail", commentMix.getThumbnail());
jsonObject.put("index", index);
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("commentList", jsonArray);
return bigjJsonObject;
}
// 搜索帖子
@RequestMapping(value = "coversion/searchCoversionList", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject searchCovesionList(
@RequestParam("keyword") String keyword,
@RequestParam("nid") String nid) {
System.out.println(" 搜索帖子 keyword:" + keyword);
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CoversionMix[] coversionMixs = coversionServiceImp
.searchCoversions(keyword);
int index = 0;
for (CoversionMix coversionMix : coversionMixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", coversionMix.getCid());
jsonObject.put("nid", coversionMix.getNid());
jsonObject.put("titleText", coversionMix.getTitle());
jsonObject.put("contentText", coversionMix.getContent());
jsonObject.put("supportNum", coversionMix.getSupportNum());
jsonObject.put("commitNums", coversionMix.getCommentNum());
jsonObject.put("nick", coversionMix.getNick());
jsonObject.put("url", coversionMix.getImageUrl());
jsonObject.put("thumbnail", coversionMix.getThumbnail());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(coversionMix.getDate()));
jsonObject.put("index", index);
NidAndCid nidAndCid = new NidAndCid();
nidAndCid.setCid(coversionMix.getCid());
nidAndCid.setNid(Integer.parseInt(nid));
boolean isSupprot = coversionServiceImp.isSupport(nidAndCid);
if (isSupprot == true)
jsonObject.put("isSupport", "true");
else
jsonObject.put("isSupport", "false");
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("coversionList", jsonArray);
return bigjJsonObject;
}
// 插入评论
@RequestMapping(value = "comment/insertComment", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject insertComment(@RequestParam("nid") int nid,
@RequestParam("cid") int cid,
@RequestParam("content") String content,
@RequestParam("date") String date) {
// 插入一个评论,相关的评论的数量加1,然后返回新的列表
System.out.println("插入评论");
CommentTable commentTable = creatOneComment(cid, nid, content, date);
coversionServiceImp.upDateCoversion(cid);// 更新
int rowsNum = commentServiceImp.insertComment(commentTable);
return getCommentMixsMethod(cid, rowsNum);// 返回新的评论,方法不可取
}
// 插入帖子
@RequestMapping(value = "coversion/insertCoversion", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject insertCoversion(@RequestParam("nid") int nid,
@RequestParam("content") String content,
@RequestParam("date") String date,
@RequestParam("title") String title) throws ParseException {
// 插入一个话题,返回新话题
System.out.println("插入帖子 ");
CoversionTable coversionTable = creatOneCoversion(nid, title, content,
date);
int rowsNum = coversionServiceImp.insertCoversion(coversionTable);
return getCoversionMixsMethod(nid, rowsNum);// 返回新的评论,方法不可取
}
// json方式获得评论表
@RequestMapping(value = "comment/getCommentList_json", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getCommentListByJson(@RequestBody Test test) {
System.out.println("json方式获得评论表");
int cid = test.getCid();
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CommentMix[] commentMixs = commentServiceImp.getCommentMixsByID(cid);
int index = 0;
for (CommentMix commentMix : commentMixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", commentMix.getCid());
jsonObject.put("nid", commentMix.getNid());
jsonObject.put("content", commentMix.getContent());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(commentMix.getDate()));
jsonObject.put("nick", commentMix.getNick());
jsonObject.put("thumbnail", commentMix.getThumbnail());
jsonObject.put("index", index);
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("commentList", jsonArray);
return bigjJsonObject;
}
// 点赞 comment/upDateSupportNums
@RequestMapping(value = "comment/upDateSupportNums", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject upDateSupportNums(@RequestBody SupportRequest sRequest) {
JSONObject bigjJsonObject = new JSONObject();
System.out.println("点赞 comment/upDateSupportNums");
int state = coversionServiceImp.supportCoversionOrNot(
sRequest.getCid(), sRequest.getNid(), sRequest.getType());
bigjJsonObject.put("nowState", state);// 应该和传过来的state一样
return bigjJsonObject;
}
// 获得个人信息
@RequestMapping(value = "personal/getPersonalMsg", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getPersonalMsg(@RequestParam("nid") int nid) {
System.out.println("获得个人信息");
PersonalTable pTable = personalServiceImp.getPersonMsgById(nid);
JSONObject biJsonObject = new JSONObject();
/*
*
* nid nick sex thumbnail passPort pwd phone
*/
biJsonObject.put("nid", pTable.getNid());
biJsonObject.put("nick", pTable.getNick());
biJsonObject.put("sex", (int)pTable.getSex() == 1 ? "男":"女" );
biJsonObject.put("passPort", pTable.getPassPort());
biJsonObject.put("pwd", pTable.getPwd());
biJsonObject.put("phone", pTable.getPhone());
biJsonObject.put("thumbnail", pTable.getThumbnail());
return biJsonObject;
}
// 获得个人未通知信息
@RequestMapping(value = "personal/getMsgNew", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getMsgNew(@RequestParam("nid") int nid) {
//自己的不应该在消息通知里面出现
System.out.println("// 获得个人未通知信息");
PersonalTable pTable = personalServiceImp.getPersonMsgById(nid);
JSONObject biJsonObject = new JSONObject();
CommentMix_2[] commentMixs=personalServiceImp.getMsgNew(nid);
JSONArray jsonArray=new JSONArray();
for (CommentMix_2 commentMix : commentMixs) {
if(commentMix.getNid() == nid )continue;
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", commentMix.getCid());
jsonObject.put("nid", commentMix.getNid());
jsonObject.put("content", commentMix.getContent());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(commentMix.getDate()));
jsonObject.put("nick", commentMix.getNick());
jsonObject.put("thumbnail", commentMix.getThumbnail());
jsonObject.put("title", commentMix.getCoversionTitle());//返回相关的标题
jsonArray.add(jsonObject);// 放进来
}
biJsonObject.put("commentList", jsonArray);
return biJsonObject;
}
//登陆
@RequestMapping(value = "personal/Login", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject Login(@RequestParam("passPort") String passPort,@RequestParam("pwd") String pwd){
System.out.println("登陆:"+" "+passPort+" "+pwd);
PersonalTable pTable=personalServiceImp.Login(passPort, pwd);
JSONObject biJsonObject = new JSONObject();
if(pTable != null){
biJsonObject.put("nid", pTable.getNid());
biJsonObject.put("nick", pTable.getNick());
biJsonObject.put("sex", (int)pTable.getSex() == 1 ? "男":"女" );
biJsonObject.put("passPort", pTable.getPassPort());
biJsonObject.put("pwd", pTable.getPwd());
biJsonObject.put("phone", pTable.getPhone());
biJsonObject.put("thumbnail", pTable.getThumbnail());
biJsonObject.put("isLogined","true");
}else {
biJsonObject.put("isLogined","false");
}
return biJsonObject;
}
// 获得个人未通知信息数量
@RequestMapping(value = "personal/getMsgNewNums", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject getMsgNewNums(@RequestParam("nid") int nid) {
System.out.println("获得个人未通知信息数量");
JSONObject bigJsonObject=new JSONObject();
bigJsonObject.put("nums", personalServiceImp.getNewsMsgNums(nid));
return bigJsonObject;
}
// 设置未通知信息为已读
@RequestMapping(value = "personal/setMsgViewed", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public JSONObject setMsgViewed(@RequestBody NidsRequest nidsRequest) {
System.out.println(" 设置未通知信息为已读");
JSONObject biJsonObject = new JSONObject();
int nums=personalServiceImp.setMsgViewed(nidsRequest.getCids(), nidsRequest.getNids());
biJsonObject.put("nums", nums);
System.out.println("nums:"+nums);
return biJsonObject;
}
// ------------------------------------------------------------------------
public CommentTable creatOneComment(int cid, int nid, String content,
String date) {
CommentTable commentTable = new CommentTable();
commentTable.setCid(cid);
commentTable.setNid(nid);
commentTable.setContent(content);
commentTable.setDate(Timestamp.valueOf(date));
return commentTable;
}
public CoversionTable creatOneCoversion(int nid, String title,
String content, String date) throws ParseException {
CoversionTable coversionTable = new CoversionTable();
coversionTable.setNid(nid);// cid自己生成
coversionTable.setTitle(title);
coversionTable.setCommentNum(0);
coversionTable.setSupportNum(0);
coversionTable.setContent(content);
coversionTable.setDate(Timestamp.valueOf(date));
coversionTable.setImageUrl("");
return coversionTable;
}
public CommentMix creatOneCommentMix(int cid, String content,
Timestamp date, String nick, int nid) {
CommentMix commentMix = new CommentMix();
commentMix.setCid(cid);
commentMix.setContent(content);
commentMix.setDate(date);
commentMix.setNick(nick);
commentMix.setNid(nid);
commentMix.setThumbnail("");// 应该是先上传图片,然后放在目录里,然后赋值
return commentMix;
}
public CoversionMix creatOneCoversionMix() {
return null;
}
public JSONObject getCommentMixsMethod(int cid, int rowNum) {
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CommentMix[] commentMixs = commentServiceImp.getCommentMixsByID(cid);
int index = 0;
for (CommentMix commentMix : commentMixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", commentMix.getCid());
jsonObject.put("nid", commentMix.getNid());
jsonObject.put("contentText", commentMix.getContent());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(commentMix.getDate()));
jsonObject.put("nick", commentMix.getNick());
jsonObject.put("thumbnail", commentMix.getThumbnail());
jsonObject.put("index", index);
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("commentList", jsonArray);
bigjJsonObject.put("rowNum", rowNum);
return bigjJsonObject;
}
public JSONObject getCoversionMixsMethod(int cid, int rowNum) {
JSONObject bigjJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
CoversionMix[] mixs = coversionServiceImp.getCoversions();
int index = 0;
for (CoversionMix coversionMix : mixs) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cid", coversionMix.getCid());
jsonObject.put("nid", coversionMix.getNid());
jsonObject.put("titleText", coversionMix.getTitle());
jsonObject.put("contentText", coversionMix.getContent());
jsonObject.put("supportNum", coversionMix.getSupportNum());
jsonObject.put("commitNums", coversionMix.getCommentNum());
jsonObject.put("nick", coversionMix.getNick());
jsonObject.put("url", coversionMix.getImageUrl());
jsonObject.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(coversionMix.getDate()));
jsonObject.put("index", index);
index++;
jsonArray.add(jsonObject);// 放进来
}
bigjJsonObject.put("coversionList", jsonArray);
bigjJsonObject.put("rowNum", rowNum);
return bigjJsonObject;
}
// 以json的方式获得评论
@Service
class RequestBody_comment implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
private int cid;
}
}
|
package com.springboot.quickstart.mapper;
import com.springboot.quickstart.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* class_name: UserMapper
* package: com.springboot.quickstart.mapper
* describe: TODO
* @author: Liuxianglong
* @date: 2018/1/20
* creat_time: 16:02
**/
@Mapper
public interface UserMapper {
@Select("select * from user")
List<User> selectUser();
}
|
package domain;
import domain.api.Item;
public class ItemImpl implements Item {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.example.lookie;
public class DrinkCartData {
String drink;
String size;
int price;
int amount;
public DrinkCartData(String drink, String size, int price, int amount) {
this.drink = drink;
this.size = size;
this.price = price;
this.amount = amount;
}
public String getDrink() {
return drink;
}
public void setDrink(String drink) {
this.drink = drink;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
|
package com.pfchoice.springboot.repositories;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.pfchoice.springboot.model.PlaceOfService;
import com.pfchoice.springboot.repositories.intf.RecordDetailsAwareRepository;
@Repository
public interface PlaceOfServiceRepository
extends PagingAndSortingRepository<PlaceOfService, Integer>, JpaSpecificationExecutor<PlaceOfService>, RecordDetailsAwareRepository<PlaceOfService, Integer> {
PlaceOfService findByDescription(String description);
PlaceOfService findByCode(String code);
}
|
package com.example.user.testteamextention.data;
import com.example.user.testteamextention.model.ExchangeObject;
import com.example.user.testteamextention.model.ItemResponse;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
@GET("transactions.json")
Call<ItemResponse> getItemsList();
@GET("rates.json")
Call<List<ExchangeObject>> getExchangeRate();
}
|
/*As we know to test our rest API we have to use POSTMAN/SWAGGER etc..... tools (i'm using POSTMAN here)
* we have to pass request body as shown as below and the api will give the response in below format
* request in JSON format
* =========================
* {
"name":"mobile",
"cardType":"HDFC",
"price":51000
}
*response in JSON format
*==========================
*{
"name": "mobile",
"cardType": "HDFC",
"discount": 10,
"price": 51000
}
*/
package com.nt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDroolsDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDroolsDemoApplication.class, args);
}
}
|
package com.tencent.mm.ui.b;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.ActionBar;
import android.support.v7.view.menu.f;
import android.support.v7.widget.u;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
public final class b extends a implements android.support.v7.view.menu.f.a, android.support.v7.view.menu.l.a {
public ViewGroup CK;
private boolean EE;
private f bq;
a tqW;
boolean tqX;
private final Runnable tqY = new Runnable() {
public final void run() {
android.support.v7.view.menu.f.a aVar = b.this;
Context context = aVar.mActivity;
ActionBar supportActionBar = aVar.getSupportActionBar();
if (supportActionBar != null) {
context = supportActionBar.getThemedContext();
}
f fVar = new f(context);
fVar.a(aVar);
if (b.this.tqW != null) {
b.this.tqW.d(fVar);
b.this.tqW.c(fVar);
b.a(b.this, fVar);
} else {
b.a(b.this, null);
}
fVar.p(true);
b.this.tqX = false;
}
};
public interface a {
boolean c(Menu menu);
boolean d(Menu menu);
boolean j(MenuItem menuItem);
}
public b(Activity activity, a aVar) {
super(activity);
this.tqW = aVar;
}
public final ActionBar cqY() {
if (!this.EE) {
this.EE = true;
supportInvalidateOptionsMenu();
}
if (this.mActionBar == null) {
this.mActionBar = new d(this.mActivity, this.CK);
}
return this.mActionBar;
}
public final boolean a(f fVar, MenuItem menuItem) {
if (this.tqW != null) {
return this.tqW.j(menuItem);
}
return false;
}
public final void b(f fVar) {
if (this.mActionBar != null) {
u uVar = ((d) this.mActionBar).Fs;
if (uVar != null && uVar.ef()) {
if (uVar.isOverflowMenuShowing()) {
uVar.hideOverflowMenu();
return;
} else if (uVar.getVisibility() == 0) {
uVar.showOverflowMenu();
return;
} else {
return;
}
}
}
fVar.close();
}
public final void a(f fVar, boolean z) {
}
public final boolean d(f fVar) {
return false;
}
public final void supportInvalidateOptionsMenu() {
if (!this.tqX) {
this.tqX = true;
this.tqY.run();
}
}
}
|
package random;
public class NestedExceptionTryCatchBehaviorTest {
public static void main(String[] args) {
try {
try {
int x = 0 / 0 ;
} catch (RuntimeException e) {
// once caught it is dealt with..
System.out.println("inner");
}
} catch (RuntimeException e) {
// doesn't run
System.out.println("outer");
}
}
}
|
package com.noteshare.solr.utils;
import java.io.IOException;
import org.apache.solr.client.solrj.SolrServerException;
import com.noteshare.solr.model.Entity;
import com.noteshare.solr.services.SolrService;
public class ExcuteSolr {
public static void excute(SolrService solrService,Entity entity,String operType){
Excuter excuter = new Excuter(solrService,entity,operType);
Thread thread = new Thread(excuter);
thread.start();
}
}
class Excuter implements Runnable{
private SolrService solrService;
private Entity entity;
private String operType;
public Excuter(){}
/**
* <p>Title : </p>
* <p>Description : 更新索引</p>
* @param solrService
* @param entity
* @param operType 操作类型
*/
public Excuter(SolrService solrService,Entity entity,String operType){
this.solrService = solrService;
this.entity = entity;
this.operType = operType;
}
@Override
public void run() {
try {
if(SolrConstant.UPDATE.equals(operType)){
solrService.updateIndex(entity);
}else if(SolrConstant.ADD.equals(operType)){
solrService.addIndex(entity);
}
} catch (IOException e) {
e.printStackTrace();
} catch (SolrServerException e) {
e.printStackTrace();
}
}
}
|
package com.spring.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This program demonstrates the following basic use cases for the REST API:
* - authentication with OAuth 2.0 (This is for development purposes only. Not a real implementation.)
* - querying (using account records)
* - inserting (using a contact record related to one of the retrieved account records)
* - updating (updates contact record added in previous step)
*
* @author salesforce training
*/
public class SALESFORCEauth {
private static Logger logger = Logger.getLogger(SALESFORCEauth.class);
//---------Credentials----------
//Credentials providing access to a specific Salesforce organization.
private static final String userName = "sfa.admin@smelending.com"; // COPY USERNAME
private static final String password = "P@ssword123HlfNV2uKzJdFgIU3ODiiwKoP"; // COPY PASSWORD AND TOKEN
//---------REST and OAuth-------
//Portions of the URI for REST access that are re-used throughout the code
private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";
//Holds URI returned from OAuth call, which is then used throughout the code.
String baseUri;
//The oauthHeader set in the oauth2Login method, and then added to
//each HTTP object that is used to invoke the REST API.
Header oauthHeader;
//Basic header information added to each HTTP object that is used
//to invoke the REST API.
Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
//----------Data specific---------
//Retrieved accountId that is used when contact is added.
private static String accountId;
//Id of inserted contact. Used to update contact.
private static String contactId;
//----------Utility-------------
//Used to get input from console.
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
/**
* This class holds all the values related to the credentials needed to
* make the OAuth2 request for authentication. Normally they would not be set in
* this manner.
*/
class UserCredentials {
String loginInstanceDomain = "ap2.salesforce.com"; // COPY YOUR SERVER INSTANCE
String apiVersion = "37"; // COPY YOU API VERSION
String userName = "sfa.admin@smelending.com";
String password = "P@ssword123HlfNV2uKzJdFgIU3ODiiwKoP";
String consumerKey = "3MVG9ZL0ppGP5UrDrEtcdSurr6Hx1VewngWvpy7yp.Dr0k1Q.ctMrp6lSTFbydaRN7FSfaRsj8LeIusPC64Sq"; // COPY YOUR CONSUMER KEY
String consumerSecret = "8305535735246224767"; // COPY YOUR CONSUMER SECRET
String grantType = "password";
}
/**
* Constructor drives console interaction and calls appropriate methods.
*/
public SALESFORCEauth() {
logger.info("Program complete.");
}
/**
* This method connects the program to the Salesforce organization using OAuth.
* It stores returned values for further access to organization.
* @param userCredentials Contains all credentials necessary for login
* @return
*/
public HttpResponse oauth2Login() {
logger.info("_______________ Login _______________");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
String loginHostUri = "https://" + userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;
try {
//Construct the objects for making the request
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText = new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
// logger.info("final request lokks likes::::"+requestBodyText);
logger.info("Enviado: "+requestBodyText.toString());
StringEntity requestBody = new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);
//Make the request and store the result
response = httpClient.execute(httpPost);
//Parse the result if we were able to connect.
if ( response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
logger.info("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
StringWriter stack = new StringWriter();
je.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
baseUri = oauth2Response.instance_url + REST_ENDPOINT + "/v" + userCredentials.apiVersion +".0";
oauthHeader = new BasicHeader("Authorization", "OAuth " + oauth2Response.access_token);
logger.info("\nSuccessfully logged in to instance: " + baseUri);
} else {
logger.info("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
logger.info(getBody(response.getEntity().getContent()));
// System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
StringWriter stack = new StringWriter();
uee.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} catch (IOException ioe) {
StringWriter stack = new StringWriter();
ioe.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} catch (NullPointerException npe) {
StringWriter stack = new StringWriter();
npe.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
return response;
}
/**
* This class is used to hold values returned by the OAuth request.
*/
static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;
public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");
} catch (JSONException e) {
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
}
}
//==========utility methods=============
/**
* Utility method for changing a stream into a String.
* @param inputStream
* @return
*/
private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
StringWriter stack = new StringWriter();
ioe.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
return result;
}
//--------------utility methods for user input----------
/**
* A utility method to be used for getting user input from the console.
*/
public static void main(String s[])
{
SALESFORCEauth salesforcEauth=new SALESFORCEauth();
HttpResponse httpResponse=salesforcEauth.oauth2Login();
logger.info("Status :: "+httpResponse.getStatusLine().getStatusCode());
}
}
|
/*
* Copyright (c) 2017. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*
*/
package org.librairy.modeler.performance;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import es.cbadenes.lab.test.IntegrationTest;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.librairy.boot.model.domain.resources.Resource;
import org.librairy.boot.model.utils.TimeUtils;
import org.librairy.boot.storage.generator.URIGenerator;
import org.librairy.computing.Config;
import org.librairy.computing.cluster.ComputingContext;
import org.librairy.computing.helper.ComputingHelper;
import org.librairy.computing.helper.StorageHelper;
import org.librairy.modeler.lda.dao.SimilaritiesDao;
import org.librairy.modeler.lda.dao.SimilarityRow;
import org.librairy.modeler.lda.helper.ModelingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*/
@Category(IntegrationTest.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@TestPropertySource(properties = {
"librairy.computing.fs = local"
})
public class LocalFSPerformanceTest {
private static final Logger LOG = LoggerFactory.getLogger(LocalFSPerformanceTest.class);
@Autowired
StorageHelper storageHelper;
@Autowired
URIGenerator uriGenerator;
@Autowired
ComputingHelper computingHelper;
@Autowired
ModelingHelper helper;
StructType edgeDataType = DataTypes
.createStructType(new StructField[]{
DataTypes.createStructField(SimilaritiesDao.RESOURCE_URI_1, DataTypes.StringType, false),
DataTypes.createStructField(SimilaritiesDao.RESOURCE_URI_2, DataTypes.StringType, false),
DataTypes.createStructField(SimilaritiesDao.SCORE, DataTypes.DoubleType, false),
DataTypes.createStructField(SimilaritiesDao.RESOURCE_TYPE_1, DataTypes.StringType, false),
DataTypes.createStructField(SimilaritiesDao.RESOURCE_TYPE_2, DataTypes.StringType, false)
});
@Test
public void save() throws InterruptedException {
Instant startG = Instant.now();
ComputingContext context = computingHelper.newContext("sample");
List<Integer> elements = IntStream.range(1, 2000).boxed().collect(Collectors.toList());
JavaRDD<Integer> rdd = context.getSparkContext().parallelize(elements);
JavaRDD<SimilarityRow> simRows = rdd
.cartesian(rdd)
.repartition(context.getRecommendedPartitions())
.map(pair -> {
SimilarityRow row1 = new SimilarityRow();
row1.setResource_uri_1(String.valueOf(pair._1));
row1.setResource_uri_2(String.valueOf(pair._2));
row1.setScore(pair._1.doubleValue() + pair._2.doubleValue());
row1.setResource_type_1(Resource.Type.ITEM.key());
row1.setResource_type_2(Resource.Type.ITEM.key());
row1.setDate(TimeUtils.asISO());
return row1;
})
.persist(helper.getCacheModeHelper().getLevel());
LOG.info("calculating similarities btw documents ");
simRows.take(1);
LOG.info("saving subgraph edges from sector ");
JavaRDD<Row> rows = simRows.map(sr -> RowFactory.create(sr.getResource_uri_1(), sr.getResource_uri_2(), sr.getScore(), sr.getResource_type_1(), sr.getResource_type_2()));
DataFrame dataframe = context
.getSqlContext()
.createDataFrame(rows, edgeDataType)
.persist(helper.getCacheModeHelper().getLevel());
dataframe.take(1);
List<Integer> sample = Arrays.asList(new Integer[]{
1,
2,
Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors()*2,
context.getRecommendedPartitions(),
100,
500,
1000
});
List<Integer> partitions = sample;//Lists.reverse(sample);
saveData(partitions.get(0),dataframe);
for (Integer partition : partitions){
saveData(partition, dataframe);
}
LOG.info("Total elapsed time: " + Duration.between(startG, Instant.now()).toMillis() + " msecs");
}
private void saveData(Integer partitions, DataFrame dataFrame) {
try {
Instant start = Instant.now();
String path = "/librairy/tests/data-" + partitions;
storageHelper.deleteIfExists(path);
// Save the model
dataFrame
.repartition(partitions)
.write()
.mode(SaveMode.Overwrite)
.save(path);
LOG.info("Saved at "+path + " in " + Duration.between(start, Instant.now()).toMillis() + "msecs");
}catch (Exception e){
if (e instanceof java.nio.file.FileAlreadyExistsException) {
LOG.warn(e.getMessage());
}else {
LOG.error("Error saving model", e);
}
}
}
private void loadData(Integer partitions, ComputingContext context){
try {
Instant start = Instant.now();
String path = "/librairy/tests/data-" + partitions;
storageHelper.deleteIfExists(path);
// Save the model
DataFrame dataframe = context.getSqlContext()
.read()
.schema(edgeDataType)
.load(path);
// .repartition(partitions);
dataframe.count();
LOG.info("Loaded from "+path + " in " + Duration.between(start, Instant.now()).toMillis() + "msecs");
}catch (Exception e){
if (e instanceof java.nio.file.FileAlreadyExistsException) {
LOG.warn(e.getMessage());
}else {
LOG.error("Error saving model", e);
}
}
}
@Test
public void read() throws InterruptedException {
ComputingContext context = computingHelper.newContext("sample");
List<Integer> sample = Arrays.asList(new Integer[]{
1,
2,
Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors()*2,
context.getRecommendedPartitions(),
100,
500,
1000
});
List<Integer> partitions = sample;//Lists.reverse(sample);
loadData(partitions.get(0), context);
for (Integer partition : partitions){
loadData(partition, context);
}
}
}
|
package ru.hitpoint.lib.hitpoint.heatmap;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Painter implements PainterInt {
private List<TouchInfo> motionEvents = new ArrayList<>();
private Paint point;
private Paint background;
private boolean putNumbers = true;
private Painter() {
this.point = new Paint();
this.background = new Paint();
point.setARGB(50, 237, 126, 23);
point.setStrokeWidth(45);
background.setARGB(60, 0, 0, 255);
}
@Override
public void dispatchTouchEvent(MotionEvent ev) {
Log.d("FOR TOLYA CHECK ", "PRIVET");
if (ev.getAction() == MotionEvent.ACTION_MOVE) {
motionEvents.add(new TouchInfo(ev));
}
if (ev.getAction() == MotionEvent.ACTION_UP) {
motionEvents.add(new TouchInfo(ev));
}
Log.d("MOTION EVENT ", String.valueOf(ev.getAction()));
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
motionEvents.add(new TouchInfo(ev));
}
}
@Override
public Bitmap takeScreenshot(Activity activity) {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
Bitmap bitmap = null;
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = activity.getWindow().getDecorView().getRootView();
// v1.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height)
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
// Bitmap bitmap = Bitmap.createBitmap(v1.getLayoutParams().width , v1.getLayoutParams().height,
// Bitmap.Config.ARGB_8888);
v1.setDrawingCacheEnabled(false);
Canvas canvas = new Canvas(bitmap);
canvas.drawRect(0.0f, 0.0f, Float.parseFloat(Integer.toString(v1.getWidth())),
Float.parseFloat(Integer.toString(v1.getHeight())), background);
// canvas.drawColor(Color.BLUE, PorterDuff.Mode.LIGHTEN);
float start = 0;
float finish = 0;
int i = 0;
Paint textPaint = new Paint();
textPaint.setARGB(100, 0, 0, 0);
textPaint.setTextSize(40);
for (TouchInfo ev : motionEvents) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
start = ev.getX();
finish = ev.getY();
canvas.drawCircle(start, finish, 50, point);
i++;
if (putNumbers) {
canvas.drawText(String.valueOf(i), start - 10, finish + 10, textPaint);
}
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
canvas.drawLine(start, finish, ev.getX(), ev.getY(), point);
start = ev.getX();
finish = ev.getY();
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
canvas.drawLine(start, finish, ev.getX(), ev.getY(), point);
start = 0;
finish = 0;
}
}
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
motionEvents.clear();
// openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
return bitmap;
}
// private void openScreenshot(File imageFile) {
// Intent intent = new Intent();
// intent.setAction(Intent.ACTION_VIEW);
// Uri uri = Uri.fromFile(imageFile);
// intent.setDataAndType(uri, "image/*");
// activity.startActivity(intent);
// }
public static Builder newBuilder() {
return new Painter().new Builder();
}
public class Builder {
private Builder() {
point = new Paint();
background = new Paint();
point.setARGB(50, 237, 126, 23);
point.setStrokeWidth(45);
background.setARGB(60, 0, 0, 255);
}
public Builder setPointArgb(int transparency, int r, int g, int b) {
point.setARGB(transparency, r, g, b);
return this;
}
public Builder setPointWidth(int width) {
point.setStrokeWidth(width);
return this;
}
public Builder setBackgroundArgb(int transparency, int r, int g, int b) {
background.setARGB(transparency, r, g, b);
return this;
}
public Builder setPutNumber(boolean putNumber) {
putNumbers = putNumber;
return this;
}
public Painter build() {
return Painter.this;
}
}
}
|
public class MainAnimal {
public static void main(String[] args) {
Animal animal1 = new Dog();
animal1.makeNoise("","") ;
animal1.sleep("", "");
animal1.eat("", "");
;
Animal animal2 = new Cat();
animal2.makeNoise("", "");
animal2.sleep("", "");
animal2.eat("", "");
Animal animal3 = new Horse();
animal3.makeNoise("", "");
animal3.sleep("", "");
animal3.eat("", "");
}
}
|
package com.tuitaking.race.r20201227;
import java.util.HashMap;
import java.util.List;
/**
* 给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。
* 两个字符串 相似 的前提是它们都含有相同数目的元音('a','e','i','o','u','A','E','I','O','U')。注意,s 可能同时含有大写和小写字母。
* 如果 a 和 b 相似,返回 true ;否则,返回 false 。
* 示例 1:
* 输入:s = "book"
* 输出:true
* 解释:a = "bo" 且 b = "ok" 。a 中有 1 个元音,b 也有 1 个元音。所以,a 和 b 相似。
* 示例 2:
*
* 输入:s = "textbook"
* 输出:false
* 解释:a = "text" 且 b = "book" 。a 中有 1 个元音,b 中有 2 个元音。因此,a 和 b 不相似。
* 注意,元音 o 在 b 中出现两次,记为 2 个。
* 示例 3:
*
* 输入:s = "MerryChristmas"
* 输出:false
* 示例 4:
*
* 输入:s = "AbCdEfGh"
* 输出:true
*/
public class HalvesAreAlike {
public boolean halvesAreAlike(String s) {
if(s.length()==0){
return false;
}
HashMap<Character,Integer> count=new HashMap<>();
count.put('a',1);
count.put('e',1);
count.put('i',1);
count.put('o',1);
count.put('u',1);
count.put('A',1);
count.put('E',1);
count.put('I',1);
count.put('O',1);
count.put('U',1);
int mid=s.length()/2;
int right=mid;
int leftC=0;
int rightC=0;
for(int i = 0 ; i <mid;i++){
if(count.get(s.charAt(i))!=null){
leftC++;
}
// right+=i;
if(count.get(s.charAt(right+i))!=null){
rightC++;
}
}
return leftC==rightC;
}
// public static void main(String[] args) {
// System.out.println(halvesAreAlike("book"));
// System.out.println(halvesAreAlike("textbook"));
// System.out.println(halvesAreAlike("MerryChristmas"));
// System.out.println(halvesAreAlike("AbCdEfGh"));
// }
}
|
package permafrost.game;
import permafrost.core.lang.GList;
import permafrost.core.module.ModuleManager;
import permafrost.core.module.PermafrostModule;
public class GameController<T extends Playable> extends PermafrostModule
{
protected final GList<T> games;
public GameController(ModuleManager manager)
{
super(manager);
this.games = new GList<T>();
}
public GList<T> getGames()
{
return games.copy();
}
public void onEnable()
{
}
public void onDisable()
{
for(T i : getGames())
{
i.stop();
}
games.clear();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlets;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author milandobrota
*/
public class RemoveFriendshipServlet extends HttpServlet {
public static final int TCP_PORT = 9999;
String hostname = "localhost";
public static String SEPARATOR = "#_%";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext ctx = getServletConfig().getServletContext();
HttpSession session = request.getSession(true);
String currentUsername = (String)session.getAttribute("username");
if(currentUsername == null){
response.sendRedirect("Login.jsp");
return;
}
try {
// odredi adresu racunara sa kojim se povezujemo
InetAddress addr = InetAddress.getByName(hostname);
// otvori socket prema drugom racunaru
Socket sock = new Socket(addr, TCP_PORT);
// inicijalizuj ulazni stream
BufferedReader in =
new BufferedReader(
new InputStreamReader(
sock.getInputStream()));
// inicijalizuj izlazni stream
PrintWriter cmdOut =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
sock.getOutputStream())), true);
String username = request.getParameter("username");
String resp;
String list = "";
cmdOut.println("friend_remove" + SEPARATOR + username + SEPARATOR + currentUsername);
// retrieve response
while (!(resp = in.readLine()).equals("END")) {
list += resp + "\n";
}
response.sendRedirect("Profile?username=" + username);
// zatvori konekciju
in.close();
cmdOut.close();
sock.close();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
/**
*Rm.java
*Version1.0
*2015年8月30日
*Copyright easecredit.com
*
*/
package org.enilu.hellohadoop.hdfs;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* descript<br>
* </p>
* Copyright by easecredit.com<br>
* 作者: zhangtao <br>
* 创建日期: 2015年8月30日<br>
*/
public class Rm extends HDFS {
@Override
public void execute1(FileSystem fs) throws Exception {
Path path = new Path("profile");
if(fs.exists(path)){
fs.deleteOnExit(path);
System.out.println("删除文件:"+path.toString()+"成功");
}else{
System.out.println("不存在该文件:"+path.toString());
}
}
}
|
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class ForgotPasswordPage
{
private WebDriver driver;
private By emailField = By.id("email");
private By retrievePasswordButton = By.cssSelector("#form_submit i");
public ForgotPasswordPage(WebDriver driver)
{
this.driver = driver;
}
public void enterEmail(String email)
{
driver.findElement(emailField).sendKeys(email);
}
public void clickRetrievePassword()
{
driver.findElement(retrievePasswordButton).click();
}
}
|
package uns.ac.rs.hostplatserver.mapper;
import java.util.stream.Collectors;
import uns.ac.rs.hostplatserver.dto.ProjectDTO;
import uns.ac.rs.hostplatserver.model.Project;
public class ProjectMapper {
public static ProjectDTO toDTO(Project project) {
return new ProjectDTO(project.getId(),
project.getName(),
project.getDescription(),
project.getCreate_date(),
project.getUsers().stream().map(UserMapper::toDTO).collect(Collectors.toSet()),
project.isPrivate_project()
);
}
public static Project toProject(ProjectDTO projectDTO) {
return new Project(projectDTO.getId(),
projectDTO.getName(),
projectDTO.getDescription(),
projectDTO.getUsers().stream().map(UserMapper::toUser).collect(Collectors.toSet()),
projectDTO.isPrivate_project()
);
}
}
|
package com.redscarf.admin.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.redscarf.admin.mapper.SysMenuMapper;
import com.redscarf.admin.model.entity.SysMenu;
import com.redscarf.admin.model.vo.MenuVO;
import com.redscarf.admin.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 菜单权限表 服务实现类
* </p>
*
* @author lengleng
* @since 2017-10-29
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
@Cacheable(value = "menu_details", key = "#role + '_menu'")
public List<MenuVO> findMenuByRoleName(String role) {
return sysMenuMapper.findMenuByRoleName(role);
}
@Override
@CacheEvict(value = "menu_details", allEntries = true)
public Boolean updateMenuById(SysMenu sysMenu) {
return this.updateById(sysMenu);
}
}
|
package com.jim.mpviews.calendar;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jim.mpviews.R;
import com.jim.mpviews.utils.CalendarDate;
import java.util.Calendar;
public class CalendarDayView extends LinearLayout {
private CalendarDate mCalendarDate;
private TextView mTextDay, mDiff, mStartTime, mEndTime;
private LinearLayout mLayoutBackground;
public CalendarDayView(Context context, CalendarDate calendarDate) {
super(context);
mCalendarDate = calendarDate;
init();
}
private void init() {
inflate(getContext(), R.layout.mp_calendar_day, this);
mLayoutBackground = (LinearLayout) findViewById(R.id.mpDayBg);
mTextDay = (TextView) findViewById(R.id.mpDay);
mDiff = (TextView) findViewById(R.id.mpDiff);
mStartTime = (TextView) findViewById(R.id.mpStartTime);
mEndTime = (TextView) findViewById(R.id.mpEndTime);
mTextDay.setText("" + mCalendarDate.getDay());
}
public void setStartTime(String date) {
mStartTime.setText(date);
}
public void setEndTime(String date) {
mEndTime.setText(date);
}
public CalendarDate getDate() {
return mCalendarDate;
}
public void setThisMothTextColor() {
mTextDay.setTextColor(ContextCompat.getColor(getContext(), R.color.colorBlue));
mStartTime.setTextColor(ContextCompat.getColor(getContext(), R.color.colorMainText));
mEndTime.setTextColor(ContextCompat.getColor(getContext(), R.color.colorMainText));
}
public void setOtherMothTextColor() {
mTextDay.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTransparentBlue));
mStartTime.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTransparentMainText));
mEndTime.setTextColor(ContextCompat.getColor(getContext(), R.color.colorTransparentMainText));
}
public void setGreenBackground() {
mLayoutBackground.setBackgroundResource(R.color.colorLightGreen);
}
public void setWhiteBackground() {
mLayoutBackground.setBackgroundResource(R.color.colorWhite);
}
public void setGreyBackground() {
mLayoutBackground.setBackgroundResource(R.color.colorBackground);
}
}
|
package top.kylewang.bos.service.system.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.kylewang.bos.dao.system.PermissionRepository;
import top.kylewang.bos.domain.system.Permission;
import top.kylewang.bos.domain.system.User;
import top.kylewang.bos.service.system.PermissionService;
import java.util.List;
/**
* @author Kyle.Wang
* 2018/1/10 0010 18:03
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl implements PermissionService{
@Autowired
private PermissionRepository permissionRepository;
@Override
public List<Permission> findByUser(User user) {
// 判断:如果是管理员则获得所有权限
if("admin".equals(user.getUsername())){
return permissionRepository.findAll();
}else{
return permissionRepository.findByUser(user.getId());
}
}
@Override
public List<Permission> findAll() {
return permissionRepository.findAll();
}
@Override
public void save(Permission permission) {
permissionRepository.save(permission);
}
}
|
package com.example.heng.jredu.jredu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.heng.jredu.R;
import com.example.heng.jredu.entity.UserDemo;
import com.example.heng.jredu.util.StringPostRequest;
import com.example.heng.jredu.util.SystemBarTintManager;
import com.example.heng.jredu.util.UrlUtil;
import com.google.gson.Gson;
public class MainActivity_pwd_change extends Activity {
private RelativeLayout back;//返回
private EditText oldEdit;//旧密码
private EditText newEdit;//新密码
private EditText newConEdit;//确认新密码
private Button bt_pwd;//确定
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_pwd_change);
back = (RelativeLayout) findViewById(R.id.left_icon);
bt_pwd = (Button) findViewById(R.id.bt_pwd);
oldEdit = (EditText) findViewById(R.id.userOldPwd);
newEdit = (EditText) findViewById(R.id.userNewPwd);
newConEdit = (EditText) findViewById(R.id.userNewConPwd);
//返回
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
pwd();
//沉浸式状态栏
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
mTintManager.setStatusBarTintEnabled(true);
mTintManager.setNavigationBarTintEnabled(true);
mTintManager.setStatusBarTintResource(R.color.tongzhilan);
}
private void pwd() {
bt_pwd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String oldPwd = oldEdit.getText().toString();
final String newPwd = newEdit.getText().toString();
String conNewPwd = newConEdit.getText().toString();
if (TextUtils.isEmpty(oldPwd)) {
Toast.makeText(getApplicationContext(), "请填写当前密码", Toast.LENGTH_SHORT).show();
return;
}
final UserDemo userDemo =MyApplaction.getMyApplaction().getUser();
if (!oldPwd.equals(userDemo.getUpwd())) {
Toast.makeText(getApplicationContext(), "当前密码错误", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(newPwd)) {
Toast.makeText(getApplicationContext(), "请填写新密码", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(conNewPwd)) {
Toast.makeText(getApplicationContext(), "请填写确认密码", Toast.LENGTH_SHORT).show();
return;
}
if (!newPwd.equals(conNewPwd)) {
Toast.makeText(getApplicationContext(), "新密码与确认密码不一致", Toast.LENGTH_SHORT).show();
return;
}
userDemo.setUpwd(newPwd);
String url = UrlUtil.UserLogin;
StringPostRequest str_nick = new StringPostRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Gson gson = new Gson();
UserDemo user = gson.fromJson(s, UserDemo.class);
if (user.getUname().equals("")) {
Toast.makeText(getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
} else {
MyApplaction.getMyApplaction().setUser(user);
Intent it = new Intent(MainActivity_pwd_change.this, MainActivity_on.class);
Toast.makeText(getApplicationContext(), "检测到您的密码已修改,请重新登陆"
, Toast.LENGTH_SHORT).show();
startActivity(it);
finish();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
str_nick.putParams("uname", userDemo.getUname());
str_nick.putParams("upwd", userDemo.getUpwd());
str_nick.putParams("unickname", userDemo.getNickName());
str_nick.putParams("sexid", userDemo.getSexId());
str_nick.putParams("photoUrl", userDemo.getPhotoUri());
str_nick.putParams("flag", "3");
MyApplaction.getMyApplaction().getRequestQueue().add(str_nick);
}
});
}
}
|
package rjm.romek.awscourse.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rjm.romek.awscourse.SpringContext;
import rjm.romek.awscourse.model.Chapter;
import rjm.romek.awscourse.model.Task;
import rjm.romek.awscourse.model.User;
import rjm.romek.awscourse.model.UserTask;
import rjm.romek.awscourse.repository.TaskRepository;
import rjm.romek.awscourse.repository.UserTaskRepository;
import rjm.romek.awscourse.verifier.TaskVerifier;
@Service
public class UserTaskService {
private UserTaskRepository userTaskRepository;
private TaskRepository taskRepository;
@Autowired
public UserTaskService(UserTaskRepository userTaskRepository, TaskRepository taskRepository) {
this.taskRepository = taskRepository;
this.userTaskRepository = userTaskRepository;
}
public List<UserTask> getOrCreate(User user, Chapter chapter) {
List<Task> byChapter = taskRepository.findByChapter(chapter);
List<UserTask> userTasks = userTaskRepository.findAllByUserAndTask_Chapter(user, chapter);
for (Task task : byChapter) {
if (userTasks.stream().noneMatch(ut -> ut.getTask().getTaskId() == task.getTaskId())) {
userTaskRepository.save(new UserTask(user, task));
}
}
return userTaskRepository.findAllByUserAndTask_Chapter(user, chapter);
}
public Boolean checkTaskAndSaveAnswer(UserTask userTask, Map<String, String> answers) {
final Class<? extends TaskVerifier> validatorClass = userTask.getTask().getVerifier();
TaskVerifier taskVerifier = null;
try {
taskVerifier = SpringContext.getAppContext().getBean(validatorClass);
} catch (BeansException e) {
throw new RuntimeException(e);
}
userTask.setAnswers(answers);
Boolean done = taskVerifier.isCompleted(userTask);
userTask.setDone(done);
userTaskRepository.save(userTask);
return done;
}
}
|
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LaunchScreen extends JPanel implements ActionListener {
// Field Variables
private final int sideSize = 500;
public String chessPlayer1;
public String chessPlayer2;
public Color color1;
public Color color2;
private Font playerFont;
private Font settingsFont;
private JLabel player1;
private JLabel player2;
private JLabel settings;
private JLabel checkerColor1;
private JLabel checkerColor2;
private JTextField enterPlayer1;
private JTextField enterPlayer2;
private JTextField enterColor1;
private JTextField enterColor2;
private JButton play;
private Chess chess;
LaunchScreen(Chess chess) {
// Initializing Field Variables
this.chess = chess;
settingsFont = new Font("Arial", Font.BOLD, 15);
playerFont = new Font("Arial", Font.ITALIC, 12);
player1 = new JLabel("Player 1: ");
player2 = new JLabel("Player 2: ");
settings = new JLabel("Settings:");
checkerColor1 = new JLabel("Color 1: ");
checkerColor2 = new JLabel("Color 2: ");
enterPlayer1 = new JTextField("Enter Some Text");
enterPlayer2 = new JTextField("Enter Some Text");
enterColor1 = new JTextField("Enter Some Text");
enterColor2 = new JTextField("Enter Some Text");
play = new JButton("START");
// Settings
settings.setFont(settingsFont);
player1.setFont(playerFont);
player2.setFont(playerFont);
this.setLayout(null);
play.setForeground(Color.GREEN);
play.addActionListener(this);
// Adding Components to Each Other
this.add(player1);
this.add(enterPlayer1);
this.add(player2);
this.add(enterPlayer2);
this.add(settings);
this.add(checkerColor1);
this.add(checkerColor2);
this.add(enterColor1);
this.add(enterColor2);
this.add(play);
// Setting Custom Boundaries
player1.setBounds(0, 3, 52, 15);
enterPlayer1.setBounds(54, 0, 200, 20);
player2.setBounds(0, 23, 52, 15);
enterPlayer2.setBounds(54, 20, 200, 20);
settings.setBounds(0, 53, 63, 40);
checkerColor1.setBounds(0, 93, 54, 20);
checkerColor2.setBounds(0, 113, 54, 20);
enterColor1.setBounds(48, 90, 100, 20);
enterColor2.setBounds(48, 110, 100, 20);
play.setBounds(20, 150, 100, 100);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == play) {
// Get Player Names
chessPlayer1 = enterPlayer1.getText();
chessPlayer2 = enterPlayer2.getText();
// Get Colors by Calling Method
color1 = initializeColors(enterColor1.getText());
color2 = initializeColors(enterColor2.getText());
// Notify User
// JOptionPane.showMessageDialog(null, "Let's go!");
chess.changePanel(this, new Board());
}
// Call Another Constructor in Another Class Here
}
private Color initializeColors(String color) {
if (color.equalsIgnoreCase("red")) {
return new Color(255, 0, 0);
} else if (color.equalsIgnoreCase("green")) {
return new Color(0, 255, 0);
} else if (color.equalsIgnoreCase("blue")) {
return new Color(0, 0, 255);
} else {
return null;
}
}
}
|
package com.codementor.android.starwarsbattlefrontcommunity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import com.codementor.android.starwarsbattlefrontcommunity.model.Post;
import com.codementor.android.starwarsbattlefrontcommunity.view.CommentViewAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tonyk_000 on 1/6/2016.
*/
public class DiscussionActivity extends AppCompatActivity {
private Post post;
private RecyclerView mCommentView;
private CommentViewAdapter mCommentList;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discussion);
Bundle b = getIntent().getExtras();
post = b.getParcelable(MainActivity.EXTRA_POST);
List<Post> posts = new ArrayList<>();
posts.add(post);
mCommentView = (RecyclerView) findViewById(R.id.rv_comment_view);
mCommentView.setLayoutManager(new LinearLayoutManager(this));
mCommentList = new CommentViewAdapter(post.getComments(),post);
mCommentView.setAdapter(mCommentList);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"Replies to post", Toast.LENGTH_SHORT).show();
}
});
}
}
|
package com.hqhcn.android.dao;
import com.hqh.android.entity.Examsite;
import com.hqh.android.entity.ExamsiteExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ExamsiteMapper {
long countByExample(ExamsiteExample example);
int deleteByExample(ExamsiteExample example);
int deleteByPrimaryKey(String kcdddh);
int insert(Examsite record);
int insertSelective(Examsite record);
List<Examsite> selectByExample(ExamsiteExample example);
Examsite selectByPrimaryKey(String kcdddh);
int updateByExampleSelective(@Param("record") Examsite record, @Param("example") ExamsiteExample example);
int updateByExample(@Param("record") Examsite record, @Param("example") ExamsiteExample example);
int updateByPrimaryKeySelective(Examsite record);
int updateByPrimaryKey(Examsite record);
List selectByExampleToPage(ExamsiteExample example);
}
|
package com.netease.course;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* @author menglanyingfei
* @date 2017-8-27
*/
/**
*
* @author 15072 使用Spring JDBC
*/
@Repository
public class JdbcTemplateDao {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void resetMoney() {
jdbcTemplate.update("update UserBalance set balance=1000");
}
// 加上传播行为, 使用Annotation的方式添加事务
@Transactional(propagation = Propagation.REQUIRED)
public void transferMoney(Long srcUserId, Long targetUserId, double count) {
this.jdbcTemplate.update(
"update UserBalance set balance=balance-? where userId=?",
count, srcUserId);
this.jdbcTemplate.update(
"update UserBalance set balance=balance+? where userId=?", count,
targetUserId);
}
public List<UserBalance> userBalanceList() {
return this.jdbcTemplate.query("select * from UserBalance",
new RowMapper<UserBalance>() {
public UserBalance mapRow(ResultSet rs, int rowNum)
throws SQLException {
UserBalance userBalance = new UserBalance();
userBalance.setUserId(rs.getLong("userId"));
userBalance.setBalance(rs.getDouble("balance"));
return userBalance;
}
});
}
}
|
package es.maltimor.genericRest;
import java.util.Map;
public interface GenericTableResolverTestParams {
public Map<String,Object> getTestParams(String table);
}
|
package org.gbif.kvs.indexing.species;
import org.gbif.dwc.terms.DwcTerm;
import org.gbif.dwc.terms.GbifTerm;
import org.gbif.dwc.terms.Term;
import org.gbif.kvs.species.SpeciesMatchRequest;
import java.util.Optional;
import java.util.function.Consumer;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
/** Utility to convert HBase occurrence records into LatLng objects. */
class OccurrenceToNameUsageRequestHBaseBuilder {
// Occurrence column family
private static final byte[] CF = Bytes.toBytes("o");
// each UnknownTerm is prefixed differently
private static final String VERBATIM_TERM_PREFIX = "v_";
/** Private constructor of utility class. */
private OccurrenceToNameUsageRequestHBaseBuilder() {
// DO NOTHING
}
/**
* Translates an HBase record/result into a SpeciesMatchRequest object.
*
* @param result HBase row/col
* @return a SpeciesMatchRequest object
*/
public static SpeciesMatchRequest toSpeciesMatchRequest(Result result) {
SpeciesMatchRequest.Builder builder = SpeciesMatchRequest.builder();
// Interpret common
putIfExists(result, DwcTerm.kingdom, builder::withKingdom);
putIfExists(result, DwcTerm.phylum, builder::withPhylum);
putIfExists(result, DwcTerm.class_, builder::withClazz);
putIfExists(result, DwcTerm.order, builder::withOrder);
putIfExists(result, DwcTerm.family, builder::withFamily);
putIfExists(result, DwcTerm.genus, builder::withGenus);
putIfExists(result, DwcTerm.specificEpithet, builder::withScientificName);
putIfExists(result, DwcTerm.infraspecificEpithet, builder::withInfraspecificEpithet);
putIfExists(result, DwcTerm.genus, builder::withGenus);
putIfExists(result, DwcTerm.taxonRank, builder::withRank);
putIfExists(result, DwcTerm.verbatimTaxonRank, builder::withVerbatimRank);
putIfExists(result, GbifTerm.genericName, builder::withGenericName);
putIfExists(result, DwcTerm.scientificName, builder::withScientificName);
putIfExists(result, DwcTerm.scientificNameAuthorship, builder::withScientificNameAuthorship);
return builder.build();
}
/**
* Reads the verbatim value associated to a term into the consumer 'with'.
* @param result HBase result
* @param term verbatim field/term
* @param with consumer
*/
private static void putIfExists(Result result, Term term, Consumer<String> with) {
Optional.ofNullable(result.getValue(CF, Bytes.toBytes(VERBATIM_TERM_PREFIX + term.simpleName())))
.map(Bytes::toString).ifPresent(with);
}
}
|
package com.google.android.gms.common.internal;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
class s$a$a implements s {
private IBinder aFh;
s$a$a(IBinder iBinder) {
this.aFh = iBinder;
}
public final void a(r rVar, int i) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
this.aFh.transact(4, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(3, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(2, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, IBinder iBinder, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeStrongBinder(iBinder);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(19, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
this.aFh.transact(34, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2, String str3, String[] strArr) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeString(str3);
obtain.writeStringArray(strArr);
this.aFh.transact(33, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2, String[] strArr) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeStringArray(strArr);
this.aFh.transact(10, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2, String[] strArr, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeStringArray(strArr);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(30, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2, String[] strArr, String str3, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeStringArray(strArr);
obtain.writeString(str3);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(1, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String str2, String[] strArr, String str3, IBinder iBinder, String str4, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeStringArray(strArr);
obtain.writeString(str3);
obtain.writeStrongBinder(iBinder);
obtain.writeString(str4);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(9, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, int i, String str, String[] strArr, String str2, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeStringArray(strArr);
obtain.writeString(str2);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(20, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, GetServiceRequest getServiceRequest) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
if (getServiceRequest != null) {
obtain.writeInt(1);
getServiceRequest.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(46, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void a(r rVar, ValidateAccountRequest validateAccountRequest) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
if (validateAccountRequest != null) {
obtain.writeInt(1);
validateAccountRequest.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(47, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final IBinder asBinder() {
return this.aFh;
}
public final void b(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(21, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void b(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(5, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void c(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(22, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void c(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(6, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void d(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(24, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void d(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(7, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void e(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(26, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void e(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(8, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void f(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(31, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void f(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(11, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void g(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(32, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void g(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(12, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void h(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(35, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void h(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(13, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void i(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(36, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void i(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(14, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void j(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(40, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void j(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(15, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void k(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(42, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void k(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(16, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void l(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(44, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void l(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(17, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void m(r rVar, int i, String str) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
this.aFh.transact(45, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void m(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(18, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void n(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(23, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void o(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(25, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void p(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(27, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void pq() {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
this.aFh.transact(28, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void q(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(37, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void r(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(38, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void s(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(41, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public final void t(r rVar, int i, String str, Bundle bundle) {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken("com.google.android.gms.common.internal.IGmsServiceBroker");
obtain.writeStrongBinder(rVar != null ? rVar.asBinder() : null);
obtain.writeInt(i);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.aFh.transact(43, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.