text
stringlengths
10
2.72M
package com.example.nihar.delta; import android.content.Context; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.Locale; public class TTS { private static TextToSpeech mTTS; private static Locale lang= Locale.ENGLISH; public static void Initalize(Context ctx){ mTTS = new TextToSpeech(ctx, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = mTTS.setLanguage(lang); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language not supported"); } } else { Log.e("TTS", "Initialization failed"); } } }); mTTS.setPitch((float) 1.0); } public static void setPitch(float f){ mTTS.setPitch(f); } public static void setSpeedRate(float f){ mTTS.setSpeechRate(f); } public static void speak(String text) { /* String text = mEditText.getText().toString(); float pitch = (float) mSeekBarPitch.getProgress() / 50; if (pitch < 0.1) pitch = 0.1f; float speed = (float) mSeekBarSpeed.getProgress() / 50; if (speed < 0.1) speed = 0.1f; */ mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null); } public static void speakQueue(String text){ mTTS.speak(text, TextToSpeech.QUEUE_ADD, null); } public static void pause(){ if (mTTS != null) { mTTS.stop(); } } public static void destroy(){ if (mTTS != null) { mTTS.stop(); mTTS.shutdown(); } } }
package com.reigens.screens; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import com.reigens.controlers.InputControler; /** * Created by Rich on 8/10/2014. */ public class play implements Screen { private final float TIMESTEP = 1 / 60f; private final int VELOCITYINTERATIONS = 8, POSITIONITERATIONS = 3; private World world; private Box2DDebugRenderer debugRenderer; private OrthographicCamera camera; private Body box; private float speed = 150; private Vector2 movement = new Vector2(); @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); world.step(TIMESTEP, VELOCITYINTERATIONS, POSITIONITERATIONS); box.applyForceToCenter(movement, true); debugRenderer.render(world, camera.combined); camera.position.set(box.getPosition().x, box.getPosition().y, 0); camera.update(); } @Override public void resize(int width, int height) { camera.viewportWidth = width / 25; camera.viewportHeight = height / 25; camera.update(); } @Override public void show() { world = new World(new Vector2(0, -9.81f), true); debugRenderer = new Box2DDebugRenderer(); camera = new OrthographicCamera(); Gdx.input.setInputProcessor(new InputControler() { @Override public boolean keyDown(int keycode) { switch (keycode) { case Input.Keys.ESCAPE: ((Game) Gdx.app.getApplicationListener()).setScreen(new Levels()); break; case Input.Keys.W: movement.y = speed; break; case Input.Keys.A: movement.x = -speed; break; case Input.Keys.S: movement.y = -speed; break; case Input.Keys.D: movement.x = speed; break; } return true; } @Override public boolean keyUp(int keycode) { switch (keycode) { case Input.Keys.W: case Input.Keys.S: movement.x = -0; break; case Input.Keys.A: case Input.Keys.D: movement.y = -0; break; } return true; } @Override public boolean scrolled(int amount) { camera.zoom += amount / 25f; return true; } }); FixtureDef fixtureDef = new FixtureDef(); BodyDef bodyDef = new BodyDef(); //Box bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(2.25f, 10); //box shape PolygonShape boxShape = new PolygonShape(); boxShape.setAsBox(.5f, 1); //box fixture definition fixtureDef.shape = boxShape; fixtureDef.friction = .75f; fixtureDef.restitution = .1f; fixtureDef.density = 5; box = world.createBody(bodyDef); box.createFixture(fixtureDef); boxShape.dispose(); //Ball //Ball Shape CircleShape ballshape = new CircleShape(); ballshape.setPosition(new Vector2(0, 1.5f)); ballshape.setRadius(.5f); //Fixture Definition fixtureDef.shape = ballshape; fixtureDef.density = 2.5f; fixtureDef.friction = .25f; fixtureDef.restitution = .75f; box.createFixture(fixtureDef); ballshape.dispose(); //Ground //Body Definition bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(0, 0); //Ground Shape ChainShape groundShape = new ChainShape(); groundShape.createChain(new Vector2[]{new Vector2(-50, 0), new Vector2(50, 0)}); //Fixture Definition fixtureDef.shape = groundShape; fixtureDef.friction = .5f; fixtureDef.restitution = 0; world.createBody(bodyDef).createFixture(fixtureDef); groundShape.dispose(); } @Override public void hide() { dispose(); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { world.dispose(); debugRenderer.dispose(); } }
package com.tencent.mm.plugin.card.d; import com.tencent.mm.plugin.card.d.d.b; public class d$a implements b { public void avQ() { } public void ayM() { } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.consent.impl; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.commerceservices.consent.dao.ConsentDao; import de.hybris.platform.commerceservices.consent.dao.ConsentTemplateDao; import de.hybris.platform.commerceservices.model.consent.ConsentModel; import de.hybris.platform.commerceservices.model.consent.ConsentTemplateModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.servicelayer.time.TimeService; @UnitTest @RunWith(MockitoJUnitRunner.class) public class DefaultCommerceConsentServiceTest { public static final Date currentTime = new Date(); public static final String consentTemplateId = "consentTemplateId"; public static final Integer consentTemplateVersion = Integer.valueOf(0); @Mock private ConsentDao consentDao; @Mock private ConsentTemplateDao consentTemplateDao; @Mock private ModelService modelService; @Mock private TimeService timeService; @Mock private ConsentTemplateModel consentTemplateModel, consentTemplateModel2; @Mock private ConsentModel existingConsentModel, newConsentModel; @Mock private BaseSiteModel baseSite; @Mock private CustomerModel customerModel; @Spy @InjectMocks private DefaultCommerceConsentService commerceConsentService; @Before public void setup() { doReturn(currentTime).when(timeService).getCurrentTime(); doReturn("1").when(consentTemplateModel).getId(); doReturn(consentTemplateModel).when(existingConsentModel).getConsentTemplate(); doReturn(newConsentModel).when(modelService).create(ConsentModel._TYPECODE); doReturn(consentTemplateModel2).when(consentTemplateDao).findLatestConsentTemplateByIdAndSite(consentTemplateId, baseSite); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplateWhenCosentTemplateIdNull() { commerceConsentService.getConsentTemplate(null, consentTemplateVersion, baseSite); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplateWhenCosentTemplateVersionNull() { commerceConsentService.getConsentTemplate(consentTemplateId, null, baseSite); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplateWhenBaseSiteNull() { commerceConsentService.getConsentTemplate(consentTemplateId, consentTemplateVersion, null); } @Test public void testGetConsentTemplateWhenConsentTemplateDoesNotExist() { doReturn(null).when(consentTemplateDao).findConsentTemplateByIdAndVersionAndSite(consentTemplateId, consentTemplateVersion, baseSite); final ConsentTemplateModel consentTemplateModel = commerceConsentService.getConsentTemplate(consentTemplateId, consentTemplateVersion, baseSite); assertNull(consentTemplateModel); } @Test public void testGetConsentTemplateWhenConsentTemplateExists() { doReturn(consentTemplateModel).when(consentTemplateDao).findConsentTemplateByIdAndVersionAndSite(consentTemplateId, consentTemplateVersion, baseSite); final ConsentTemplateModel retrievedConsentTemplateModel = commerceConsentService.getConsentTemplate(consentTemplateId, consentTemplateVersion, baseSite); assertSame(consentTemplateModel, retrievedConsentTemplateModel); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplateWhenConsentTemplateIdIsNull() { commerceConsentService.getLatestConsentTemplate(null, baseSite); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplateWhenBaseSiteIsNull() { commerceConsentService.getLatestConsentTemplate(consentTemplateId, null); } @Test public void testGetLatestConsentTemplateWhenConsentTemplateIdAndBaseSiteProvided() { final ConsentTemplateModel retrievedConsentModel = commerceConsentService.getLatestConsentTemplate(consentTemplateId, baseSite); verify(consentTemplateDao).findLatestConsentTemplateByIdAndSite(consentTemplateId, baseSite); assertEquals(consentTemplateModel2, retrievedConsentModel); } @Test(expected = IllegalArgumentException.class) public void testGetConsentTemplatesWhenBaseSiteIsNull() { commerceConsentService.getConsentTemplates(null); } @Test public void testGetConsentTemplates() { commerceConsentService.getConsentTemplates(baseSite); verify(consentTemplateDao).findConsentTemplatesBySite(baseSite); } @Test public void testGetActiveConsentByCustomer() { commerceConsentService.getActiveConsent(customerModel, consentTemplateModel); verify(consentDao).findConsentByCustomerAndConsentTemplate(customerModel, consentTemplateModel); } @Test(expected = IllegalArgumentException.class) public void testGiveConsentWhenCustomerIsNull() { commerceConsentService.giveConsent(null, consentTemplateModel); } @Test(expected = IllegalArgumentException.class) public void testGiveConsentWhenConsentTemplateIsNull() { commerceConsentService.giveConsent(customerModel, null); } @Test public void testGiveConsentWhenNoActiveConsents() { doReturn(null).when(commerceConsentService).getActiveConsent(customerModel, consentTemplateModel); commerceConsentService.giveConsent(customerModel, consentTemplateModel); verify(commerceConsentService).createConsentModel(customerModel, consentTemplateModel); verify(modelService, times(1)).save(newConsentModel); } @Test public void testGiveConsentWhenConsentPreviouslyWithdrawn() { doReturn(new Date()).when(existingConsentModel).getConsentWithdrawnDate(); doReturn(existingConsentModel).when(commerceConsentService).getActiveConsent(customerModel, consentTemplateModel); commerceConsentService.giveConsent(customerModel, consentTemplateModel); verify(commerceConsentService).createConsentModel(customerModel, consentTemplateModel); verify(modelService, times(1)).save(newConsentModel); } @Test public void testGiveConsentWhenConsentAlreadyGiven() { doReturn(null).when(existingConsentModel).getConsentWithdrawnDate(); doReturn(existingConsentModel).when(commerceConsentService).getActiveConsent(customerModel, consentTemplateModel); commerceConsentService.giveConsent(customerModel, consentTemplateModel); verify(commerceConsentService, times(0)).createConsentModel(customerModel, consentTemplateModel); verify(modelService, times(0)).save(newConsentModel); } @Test(expected = IllegalArgumentException.class) public void testWithdrawConsentWhenConsentTemplateIsNull() { commerceConsentService.withdrawConsent(null); } @Test public void testWithdrawConsentWhenConsentAlreadyWithdrawn() { doReturn(new Date()).when(existingConsentModel).getConsentWithdrawnDate(); commerceConsentService.withdrawConsent(existingConsentModel); verify(modelService, never()).save(existingConsentModel); } @Test public void testGiveConsentWhenConsentAvailableAndNotWithdrawnYet() { doReturn(null).when(existingConsentModel).getConsentWithdrawnDate(); commerceConsentService.withdrawConsent(existingConsentModel); verify(existingConsentModel).setConsentWithdrawnDate(currentTime); verify(modelService).save(existingConsentModel); } }
package more.muny.mainproject; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class colculator extends AppCompatActivity { Button button_clear; Button button_0; Button button_1; Button button_2; Button button_3; Button button_4; Button button_5; Button button_6; Button button_7; Button button_8; Button button_9; Button button_dot; Button button_equals; TextView input; TextView output; Intent intent; TextView nameValute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_colculator); button_clear=findViewById(R.id.Button_clear); button_0=findViewById(R.id.Button_0); button_1=findViewById(R.id.Button_1); button_2=findViewById(R.id.Button_2); button_3=findViewById(R.id.Button_3); button_4=findViewById(R.id.Button_4); button_5=findViewById(R.id.Button_5); button_6=findViewById(R.id.Button_6); button_7=findViewById(R.id.Button_7); button_8=findViewById(R.id.Button_8); button_9=findViewById(R.id.Button_9); button_dot=findViewById(R.id.Button_dot); button_equals=findViewById(R.id.Button_equals); input = findViewById(R.id.Input); output = findViewById(R.id.Output); intent = getIntent(); nameValute = findViewById(R.id.nameValute); nameValute.setText(intent.getStringExtra("name")); button_clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(""); output.setText(""); } }); button_0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("0")); } }); button_1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("1")); } }); button_2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("2")); } }); button_3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText( addToInputText("3")); } }); button_4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("4")); } }); button_5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("5")); } }); button_6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("6")); } }); button_7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText( addToInputText("7")); } }); button_8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("8")); } }); button_9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText("9")); } }); button_dot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input.setText(addToInputText(".")); } }); button_equals.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Double inputValue = Double.valueOf(input.getText().toString()); Double result = inputValue / Double.valueOf(intent.getStringExtra("course")); output.setText(String.format("%.2f", result)); } }); } private String addToInputText(String buttonValue) { return input.getText()+buttonValue; } }
package com.jlgproject.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.jlgproject.R; import com.jlgproject.activity.The_Answer_Tu; import com.jlgproject.base.BaseActivity; import com.jlgproject.model.AnswerMode; import com.jlgproject.util.ConstUtils; import java.util.List; /** * Created by sunbeibei on 2017/8/4. */ public class The_Answer_Adapter extends BaseAdapter { private List<AnswerMode.DataBean.ItemsBean> items; private Context context; public The_Answer_Adapter(Context context,List<AnswerMode.DataBean.ItemsBean> items) { this.context = context; this.items=items; } @Override public int getCount() { return items.size(); } public void setItems(List<AnswerMode.DataBean.ItemsBean> items) { this.items = items; } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHoler_Answer answer; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.the_anwer_item, null); answer = new ViewHoler_Answer(); answer.buju = (LinearLayout) convertView.findViewById(R.id.buju); answer.the_anwers = (TextView) convertView.findViewById(R.id.the_answers); convertView.setTag(answer); } else { answer = (ViewHoler_Answer) convertView.getTag(); } answer.the_anwers.setText(items.get(position).getSubtitle()); answer.buju.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, The_Answer_Tu.class); intent.putExtra(ConstUtils.DYJH_ID,items.get(position).getId()); intent.putExtra("title",items.get(position).getSubtitle()); context.startActivity(intent); } }); return convertView; } public class ViewHoler_Answer { private LinearLayout buju; private TextView the_anwers; } }
package com.tencent.mm.plugin.translate.a; import com.tencent.mm.sdk.platformtools.al.a; import com.tencent.mm.sdk.platformtools.x; class d$1 implements a { final /* synthetic */ d oEE; d$1(d dVar) { this.oEE = dVar; } public final boolean vD() { if (this.oEE.oEA) { x.e("MicroMsg.WorkingTranslate", "this work is time out, index: %s", new Object[]{Integer.valueOf(this.oEE.index)}); this.oEE.bIS(); this.oEE.oEC.a(-1, this.oEE.oEz, null); } return false; } }
public class SetInitialValues2 extends SetInitialValues { Data2 d; public SetInitialValues2(Data data) { d=(Data2)data; } @Override public void SetInitialValues() { d.setL(0); d.setTotal(0); } }
package org.apache.commons.net.ftp; public class FTPFileFilters { public static final FTPFileFilter ALL = new FTPFileFilter() { public boolean accept(FTPFile file) { return true; } }; public static final FTPFileFilter NON_NULL = new FTPFileFilter() { public boolean accept(FTPFile file) { return (file != null); } }; public static final FTPFileFilter DIRECTORIES = new FTPFileFilter() { public boolean accept(FTPFile file) { return (file != null && file.isDirectory()); } }; } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\ftp\FTPFileFilters.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.cyl.basic; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.cyl.sql.DBService; public class WorkStatusService { private static ArrayList<WorkStatus> list = new ArrayList<WorkStatus>(); private static WorkStatusService instance = null; /** * 初始化时先获取数据 * 这样只需要连接一次数据库 */ private WorkStatusService(){ String sql = "select * from workStatus order by number"; Connection conn = DBService.getConn(); Statement stmt = DBService.getStmt(conn); ResultSet rs = DBService.getRs(stmt, sql); try { while(rs.next()){ WorkStatus c = new WorkStatus(rs.getInt("number"), rs.getString("workStatus")); list.add(c); } } catch (SQLException e) { e.printStackTrace(); } finally { DBService.close(rs); DBService.close(stmt); DBService.close(conn); } } /** * 获取实例 * @return 该实例 */ public static WorkStatusService getInstance(){ if(instance == null){ synchronized (WorkStatusService.class) { if(instance == null){ instance = new WorkStatusService(); } } } return instance; } /** * 载入支付方式数据到数据库中 * @param pp 支付方式信息 * @return 载入成功返回true */ public boolean load(WorkStatus pp){ if(! list.contains(pp)){ return false; } Connection conn = DBService.getConn(); PreparedStatement preStmt = null; try { conn.setAutoCommit(false); String sql = "insert into paypath (number, payPath) values (?, ?)"; preStmt = DBService.getPreStmt(conn, sql); preStmt.setInt(1, list.size() + 1); preStmt.setString(2, pp.getWorkStatus()); preStmt.executeUpdate(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } finally{ DBService.close(preStmt); DBService.close(conn); } //更新list中该对象的数据 list.add(pp); return true; } /** * 得到指定范围内PayPath对象list * @param start 开始的下标,下标从 1 开始 * @param num 从start开始往后的元素个数 * @return 返回该List数据对象 */ public List<WorkStatus> getLimitData(int start, int num){ start --; return list.subList(start, start + num); } /** * PayPath类对象的个数 * @return PayPath类对象的个数 */ public int getNum(){ return list.size(); } /** * 删除该对象 * @param pp 该对象 */ public void del(WorkStatus pp){ String sql = "delete from workstatus where name = '"+ pp.getWorkStatus() +"'"; Connection conn = DBService.getConn(); Statement stmt = DBService.getStmt(conn); try { stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); }finally { DBService.close(stmt); DBService.close(conn); } //PayPath equals() hashCode() 方法得到重写 //内存中移除 list.remove(pp); } /** * 修改指定PayPath对象中的信息 * @param pp 指定的对象 * @param ppn 修改之后的对象 */ public void modify(WorkStatus pp, WorkStatus ppn){ String sql = "update workstatus set workstatus ='"+ ppn.getWorkStatus() +"' where workstatus = '"+ pp.getWorkStatus() + "'"; // System.out.println(sql); Connection conn = DBService.getConn(); Statement stmt = DBService.getStmt(conn); try { stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); }finally { DBService.close(stmt); DBService.close(conn); } list.set(list.indexOf(pp), ppn); } /** * 根据序号来获取员工工作状态途径的对象 * <li>insert into workstatus values(1,'非工作'); <li>insert into workstatus values(2,'工作中'); <li>insert into workstatus values(3,'待接收'); <li>insert into workstatus values(4,'服务中'); <li>insert into workstatus values(5,'空闲'); * @param index 支付序号,从1开始 * @return */ public WorkStatus getWorkStatusByNum(int index){ return list.get(index - 1); } }
package models.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; /** * Created by shanmao on 15-12-28. * * 任务书上传锁定状态 */ @Entity @Data public class LockTable { @Id String key; int value; }
package com.enjoy.controller.cinema.vo.request; import com.enjoy.controller.common.BaseVO; import com.enjoy.controller.exception.ParamErrorException; import lombok.Data; @Data public class DescribeCinemaInfoVO extends BaseVO { private Integer brandId; private Integer hallType; private Integer districtId; private Integer pageSize; private Integer nowPage; @Override public void checkParam() throws ParamErrorException { } }
package com.qcwp.carmanager.enumeration; /** * Created by qyh on 2017/1/3. */ public enum OBDConnectStateEnum { connectTypeConnectSuccess(1), connectTypeDisconnection (2), connectTypeDisconnectionWithTimeOut (3), connectTypeDisconnectionWithProtocol(4), connectTypeGetData (5), connectTypeConnectingWithWiFi (6), connectTypeConnectingWithOBD (7), connectTypeConnectingWithSP (8), connectTypeHaveBinded (9), connectTypeDisconnectionWithWIFi (10), connectTypeDisconnectionWithOBD (11), Unknown(-1); private final int value; OBDConnectStateEnum(int value) { this.value = value; } public int getValue() { return value; } }
package cn.edu.zucc.music.service; import cn.edu.zucc.music.model.Sheet; import cn.edu.zucc.music.model.Song; import java.util.List; public interface SongService { int addSong(Song song); int deleteSong(Song song); int updateSong(Song song); Song findById(String id); List<Song> selectTenSongs(); List<Song> findAll(); }
package com.tencent.mm.plugin.fav.ui; import android.content.Context; import android.content.res.Configuration; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.tencent.mm.plugin.fav.a.n; import com.tencent.mm.plugin.fav.a.n.a; import com.tencent.mm.plugin.fav.ui.m.e; import com.tencent.mm.plugin.fav.ui.m.h; import com.tencent.mm.plugin.fav.ui.m.i; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public class FavVoiceBaseView extends LinearLayout implements a { private int bOS; private int duration; private n iXl; private ViewGroup jaD; private TextView jaE; private ImageButton jaF; private TextView jaG; private a jaH; private String path = ""; static /* synthetic */ void i(FavVoiceBaseView favVoiceBaseView) { x.d("MicroMsg.FavVoiceBaseView", "start play, path[%s] voiceType[%d]", new Object[]{favVoiceBaseView.path, Integer.valueOf(favVoiceBaseView.bOS)}); if (favVoiceBaseView.iXl.startPlay(favVoiceBaseView.path, favVoiceBaseView.bOS)) { favVoiceBaseView.jaE.setKeepScreenOn(true); favVoiceBaseView.jaH.begin(); return; } Toast.makeText(favVoiceBaseView.getContext(), i.favorite_voice_play_error, 1).show(); } static /* synthetic */ boolean j(FavVoiceBaseView favVoiceBaseView) { x.i("MicroMsg.FavVoiceBaseView", "resume play"); boolean aLr = favVoiceBaseView.iXl.aLr(); a aVar = favVoiceBaseView.jaH; aVar.isPaused = false; aVar.sendEmptyMessage(4096); aVar.jaI.jaF.setImageResource(h.voicepost_pauseicon); aVar.jaI.jaF.setContentDescription(aVar.jaI.getContext().getResources().getString(i.app_pause)); favVoiceBaseView.jaE.setKeepScreenOn(true); return aLr; } public FavVoiceBaseView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); x.i("MicroMsg.FavVoiceBaseView", "on configuration changed, is paused ? %B", new Object[]{Boolean.valueOf(this.jaH.isPaused)}); if (this.jaH.isPaused) { this.jaH.postDelayed(new Runnable() { public final void run() { FavVoiceBaseView.this.jaH.aMv(); } }, 128); } } protected void onFinishInflate() { super.onFinishInflate(); this.jaD = (ViewGroup) findViewById(e.voice_player_progress_bg); this.jaG = (TextView) findViewById(e.voice_player_length); this.jaE = (TextView) findViewById(e.voice_player_progress); this.jaF = (ImageButton) findViewById(e.voice_player_btn); this.jaH = new a(this, (byte) 0); this.jaF.setOnClickListener(new 2(this)); } public void setVoiceHelper(n nVar) { this.iXl = nVar; this.iXl.a(this); } public final void P(String str, int i, int i2) { this.path = bi.aG(str, ""); this.bOS = i; this.duration = i2; a aVar; if (!this.path.equals(this.iXl.path)) { this.jaH.pO(i2); } else if (this.iXl.aLq()) { x.i("MicroMsg.FavVoiceBaseView", "updateInfo .isPlay()"); aVar = this.jaH; this.iXl.wb(); aVar.eT(true); } else if (this.iXl.wc()) { x.i("MicroMsg.FavVoiceBaseView", "updateInfo .isPause()"); aVar = this.jaH; this.iXl.wb(); aVar.eT(false); } else { this.jaH.pO(i2); } } public final boolean aLs() { x.i("MicroMsg.FavVoiceBaseView", "pause play"); boolean aLs = this.iXl.aLs(); a aVar = this.jaH; aVar.isPaused = true; aVar.removeMessages(4096); aVar.jaI.jaF.setImageResource(h.voicepost_beginicon); aVar.jaI.jaF.setContentDescription(aVar.jaI.getContext().getResources().getString(i.app_play)); this.jaE.setKeepScreenOn(false); return aLs; } public final void stopPlay() { x.d("MicroMsg.FavVoiceBaseView", "stop play"); this.iXl.stopPlay(); this.jaH.stop(); this.jaE.setKeepScreenOn(false); } public final void aW(String str, int i) { x.d("MicroMsg.FavVoiceBaseView", "on play, my path %s, my duration %d, play path %s", new Object[]{this.path, Integer.valueOf(this.duration), str}); if (bi.aG(str, "").equals(this.path)) { this.jaE.setKeepScreenOn(true); this.jaH.begin(); return; } this.jaH.stop(); this.jaE.setKeepScreenOn(false); } public final void onFinish() { stopPlay(); } public final void onPause() { aLs(); } }
package ws_service; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.xml.ws.Endpoint; @WebListener public class MyWebServicePublishListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //WebService的发布地址 String address = "http://192.168.155.3:8080/webservice"; //发布WebService,WebServiceImpl类是WebServie接口的具体实现类 Endpoint.publish(address, new MyWebServiceImpl()); System.out.println("使用WebServicePublishListener发布webservice成功!"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
package org.devdays.completeablefuture.puzzlers; import org.junit.Test; import java.util.concurrent.CompletableFuture; import static java.lang.System.out; import static java.util.concurrent.CompletableFuture.supplyAsync; import static org.awaitility.Awaitility.await; //thenRunAsync() called in ForkJoinPool public class Quiz2 extends AbstractQuiz { @Test public void test() throws Exception { CompletableFuture<Void> future = supplyAsync(() -> "42", executor) .thenRunAsync(() -> out.println( Thread.currentThread().getName())); await().until(future::isDone); } }
package com.canfield010.mygame.actors; import com.canfield010.mygame.Main; import com.canfield010.mygame.item.ProtectionRing; import com.canfield010.mygame.item.armor.Armor; import com.canfield010.mygame.mapsquare.MapSquare; import javax.imageio.ImageIO; import java.awt.*; import java.io.File; public class Player extends Actor { public static Image image; public Player(MapSquare squareOn) { super("Player", (byte)10, squareOn); Main.actors.add(this); } public static void setImage() { try { image = ImageIO.read(new File("img/player.png")); } catch (Exception ignored) {} } public Image getImage() { return image; }; @Override public void damage(int damage) { for (Armor armor: inventory.armor) { if (armor!=null) { damage -= damage * armor.reduction; } } if (inventory.specialItem instanceof ProtectionRing) damage-=damage*15; health -= damage; } }
package br.com.sciensa.corujaoapi.model; import org.threeten.bp.OffsetDateTime; public class ResponseMeta { private String version = null; private OffsetDateTime timestamp = null; private String hostname = null; private Integer numberOfRecords = null; private Integer page = null; private Integer size = null; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public Integer getNumberOfRecords() { return numberOfRecords; } public void setNumberOfRecords(Integer numberOfRecords) { this.numberOfRecords = numberOfRecords; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } }
package littleservantmod.inventory; import littleservantmod.entity.EntityLittleServant; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; public class ContainerServantProfession extends ContainerServantBase { public ContainerServantProfession(InventoryPlayer playerInventory, IInventory servantInventoryIn, EntityLittleServant servantIn) { super(playerInventory, servantInventoryIn, servantIn); // TODO 自動生成されたコンストラクター・スタブ //プレイヤーのアイテム欄 for (int l = 0; l < 3; ++l) { for (int j1 = 0; j1 < 9; ++j1) { this.addSlotToContainer(new Slot(playerInventory, j1 + (l + 1) * 9, 8 + j1 * 18, 84 + 42 + l * 18)); } } //プレイヤーのアイテム欄その2 for (int i1 = 0; i1 < 9; ++i1) { this.addSlotToContainer(new Slot(playerInventory, i1, 8 + i1 * 18, 142 + 42)); } } @Override public boolean canInteractWith(EntityPlayer playerIn) { return true; } }
/** * Copyright 2013-present febit.org (support@febit.org) * * 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.febit.web.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jodd.util.collection.SortedArrayList; import org.febit.util.StringUtil; /** * * @author zqq90 */ public class ActionMacroPath { public static Parser newParser() { return new Parser(); } public final String key; public final Map<String, String> params; public ActionMacroPath(String key, Map<String, String> params) { this.key = key; this.params = params; } public static class Parser { protected static final int INDEXERS_SIZE = 10; protected final Set<String> directPaths = new HashSet<>(); @SuppressWarnings("unchecked") protected final SortedArrayList<ParserEntry>[] segmentIndexers = new SortedArrayList[INDEXERS_SIZE]; protected final SortedArrayList<ParserEntry> segmentIndexerX = new SortedArrayList<>(); { // Notice: skip init segmentIndexers[0] for (int i = 1; i < INDEXERS_SIZE; i++) { segmentIndexers[i] = new SortedArrayList<>(); } } public void add(String key) { // TODO check ParserEntry conflict ParserEntry parserEntry = parseParserEntry(key); if (parserEntry == null) { directPaths.add(key); } else { getIndexer(parserEntry.pathParamSegments).add(parserEntry); } } public ActionMacroPath parse(String key) { if (directPaths.contains(key)) { return new ActionMacroPath(key, Collections.emptyMap()); } String[] pathSegments = pathToSegment(key); ParserEntry parserEntry = findParserEntry(pathSegments); if (parserEntry == null) { return new ActionMacroPath(key, Collections.emptyMap()); } Map<String, String> params = makeMap(parserEntry.paramKeys, parserEntry.exportParams(pathSegments)); return new ActionMacroPath(parserEntry.key, params); } protected SortedArrayList<ParserEntry> getIndexer(String[] pathSegments) { return pathSegments.length < INDEXERS_SIZE ? segmentIndexers[pathSegments.length] : segmentIndexerX; } protected ParserEntry findParserEntry(String[] pathSegments) { if (pathSegments == null) { return null; } SortedArrayList<ParserEntry> list = getIndexer(pathSegments); for (ParserEntry parserEntry : list) { if (parserEntry.match(pathSegments)) { return parserEntry; } } return null; } } protected static Map<String, String> makeMap(String[] keys, String[] values) { Map<String, String> map = new HashMap<>(); if (keys.length != values.length) { throw new IllegalArgumentException("length of keys and values are not match"); } for (int i = 0; i < keys.length; i++) { map.put(keys[i], values[i]); } return Collections.unmodifiableMap(map); } protected static String[] pathToSegment(String path) { if (path == null) { return null; } String[] segments = StringUtil.splitc(path, '/'); // if start with '/' if (segments.length != 0 && segments[0].isEmpty()) { segments = Arrays.copyOfRange(segments, 1, segments.length); } if (segments.length == 0) { return null; } return segments; } /** * * @param key * @return null if without dynamic params */ protected static ParserEntry parseParserEntry(String key) { if (key == null) { return null; } if (!key.contains("/$")) { return null; } String[] segments = pathToSegment(key); if (segments == null || segments.length == 0) { return null; } String[] pathSegments = new String[segments.length]; String[] pathParamSegments = new String[segments.length]; for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (!segment.isEmpty() && segment.charAt(0) == '$') { pathParamSegments[i] = segment.substring(1); } else { pathSegments[i] = segment; } } return new ParserEntry(key, pathSegments, pathParamSegments); } protected static class ParserEntry implements Comparable<ParserEntry> { protected final String key; protected final String[] pathSegments; protected final String[] pathParamSegments; protected final String[] paramKeys; public boolean match(String[] segments) { if (segments.length != this.pathSegments.length) { return false; } for (int i = 0; i < segments.length; i++) { String expect = pathSegments[i]; String segment = segments[i]; if (expect != null && !expect.equals(segment)) { return false; } } return true; } public ParserEntry(String key, String[] pathSegments, String[] pathParamSegments) { this.key = key; this.pathSegments = pathSegments; this.pathParamSegments = pathParamSegments; List<String> keys = new ArrayList<>(); for (String segment : pathParamSegments) { if (segment != null) { keys.add(segment); } } this.paramKeys = keys.toArray(new String[keys.size()]); } public String[] exportParams(String[] pathSegments) { String[] params = new String[paramKeys.length]; int index = 0; for (int i = 0; i < pathParamSegments.length; i++) { String segment = pathParamSegments[i]; if (segment != null) { params[index++] = pathSegments[i]; } } return params; } @Override public int compareTo(ParserEntry o) { return Integer.compare(this.paramKeys.length, o.paramKeys.length); } } }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int len1 = Integer.valueOf(scan.nextLine()); String str1 = scan.nextLine().replace(" ", ""); int len2 = Integer.valueOf(scan.nextLine()); String[] array = new String[len2]; for(int i = 0; i < len2; i++){ array[i] = scan.nextLine().replace(" ", ""); } ArrayList<Integer> list = new ArrayList<>(); Map<Integer, Integer> map = new HashMap<>(); String str = ""; for(int i = 0; i < len2; i++ ){ int a = 0; int l = (int)(array[i].charAt(0)) - 48; int r = (int)(array[i].charAt(1)) - 48; int k = (int)(array[i].charAt(2)) - 48; for(int m = l; m <= r; m++){ if((int)(str1.charAt(m - 1)) - 48 == k){ a++; } } // map.put(i, a); str = str + a + "\n"; } System.out.println(str); } }
package modelBridge; public class stockAssessor { }
package model; import java.security.Timestamp; /** * Created by 11437 on 2017/12/20. */ public class Post { private int postid; private String text; private String nickname; private int love; private int dislike; private int timestamp; private int attitude; private String imageUrl; public Post(int postid,String text,int like,int dislike,int timestamp,int attitude,String nickname,String imageUrl){ this.postid=postid; this.text=text; this.love=like; this.dislike=dislike; this.timestamp=timestamp; this.attitude=attitude; this.nickname=nickname; this.imageUrl=imageUrl; } public void setPostid(int postid){this.postid=postid;} public void setText(String text){this.text=text;} public void setLike(int like){this.love=like;} public void setDislike(int dislike){this.dislike=dislike;} public void setTimestamp(int timestamp){this.timestamp=timestamp;} public void setAttitude(int attitude){this.attitude=attitude;} public void setNickname(String nickname){this.nickname=nickname;} public void setImageUrl(String imageUrl){this.imageUrl=imageUrl;} public int getPostid(){return this.postid;} public String getText(){return this.text;} public int getLike(){return this.love;} public int getDislike(){return this.dislike;} public int getTimestamp(){return this.timestamp;} public int getAttitude(){return this.attitude;} public String getNickname(){return this.nickname;} public String getImageUrl(){return this.imageUrl;} }
import java.awt.Color; import java.awt.Point; import java.util.Random; /** * MVC - MODEL * @author Saverchenko * */ public class TetrisModel { /** default number of rows in a standard Tetris board **/ public static final int NUM_ROWS=18; /** number of columns in a standard Tetris board **/ public static final int NUM_COLS=10; /** number of shapes **/ private static final int NUM_SHAPES=7; /** number of cleaned lines for next level */ private static final int NUM_LINES_NEXT_LEVEL=10; /** number of cleaned lines for next level */ private static final double SPEED_INCREASE= 0.8; // 0.8 increase speed by 20% /** current board **/ private int [][] board; /** current shape **/ private Shape currentShape; /** next shape **/ private Shape nextShape; /** true when game over **/ private boolean isFinished = false; /** number of lines cleared */ private int linesCleared=0; /** number of tetrises cleared */ private int tetrisesCleared=0; /** speed of pieces falling */ private int speed=1000; // 1 sec. /** level of the game */ private int level=1; /** variable of a thread allows to interrupt the running thread. It's necessary to change speed and start a new thread */ private Thread t; /** saved board (allows the user to restart a level) */ private int savedBoard[][]; /** saved number of lines cleared (allows the user to restart a level) */ private int savedLinesCleared; /** saved number of tetrises cleared (allows the user to restart a level) */ private int savedTetrisesCleared; /** * Constructor. */ public TetrisModel() { board = new int[NUM_COLS][NUM_ROWS]; // initialization a new game with a clear board clearBoard(); // get the first shape currentShape=generateRandomShape(); // get the next shape nextShape=generateRandomShape(); // create additional array with a board (allows the user to restart a level) savedBoard= new int[NUM_COLS][NUM_ROWS]; startGame(); // start to move a shape down } /** * Starts a game */ public void startGame(){ // every 1 sec. moves current shape down t=new Thread(new Runnable() { public void run() { while (true) { if(!Thread.interrupted()){ try { Thread.sleep(speed); moveDown(); // moves current shape down } catch ( InterruptedException e ) {} }else return; // interrupt the running thread } } }); t.start(); } /** * Saves a game and allows the user to restart the last level */ public void saveGame(){ for (int y=0; y<NUM_ROWS;y++) for (int x=0; x<NUM_COLS; x++){ savedBoard[x][y]=board[x][y]; } savedLinesCleared=linesCleared; savedTetrisesCleared=tetrisesCleared; } /** * Restores a game and allows the user to restart the last level */ public void restartGame(){ for (int y=0; y<NUM_ROWS;y++) for (int x=0; x<NUM_COLS; x++){ board[x][y]=savedBoard[x][y]; } linesCleared=savedLinesCleared; tetrisesCleared=savedTetrisesCleared; isFinished=false; currentShape=generateRandomShape(); // get the first shape nextShape=generateRandomShape(); // get the next shape startGame(); // start to move a shape down } /** * * Return an array of the board. * @return an array with a board */ public int[][] getBoard(){ return board; } /** * Return the name of the the next shape * @return the name of the the next shape */ public String getNextPieceName(){ return nextShape.getPieceName(); } /** * Return the current level of the game * @return the current level */ public int getLevel(){ return level; } /** * Return current shape * @return current Shape */ public Shape getCurrentShape(){ return currentShape; } /** * Return true if the game is finished * @return boolean */ public boolean getIsFinished(){ return isFinished; } /** * Return number of lines cleared * @return */ public int getLinesCleared(){ return linesCleared; } /** * Return number of tetrisesCleared * @return */ public int getTetrisesCleared(){ return tetrisesCleared; } /** * Clear the board to start a new game. * populated with 0. 0 means no figure present. */ public void clearBoard(){ for (int y=0; y<NUM_ROWS;y++) for (int x=0; x<NUM_COLS; x++){ board[x][y]=0; } } /** * Generates a random number to represent one of the Tetris shapes available * in Full version there is MUST BE 7 shapes */ public Shape generateRandomShape(){ Random randomNumber = new Random (); int iNumber=randomNumber.nextInt(NUM_SHAPES); //generates a random number from 0 to NUMBER_SHAPES-1 switch (iNumber){ case 0: return new ShapeT(); case 1: return new ShapeZ(); case 2: return new ShapeI(); case 3: return new ShapeL(); case 4: return new ShapeO(); case 5: return new ShapeS(); case 6: return new ShapeJ(); default: return null; } } /** * Check free space for a piece moving down, left or right */ private boolean checkSpace(int plusX, int plusY, Shape currentShape) { for (int i = 0; i < 4; i++) { // for all blocks in the current shape... // calculates perspective coordinates int x = currentShape.getBlockArray()[i].getXPos() + plusX; int y = currentShape.getBlockArray()[i].getYPos() + plusY; if (x < 0 | x >= NUM_COLS | y < 0 | y >= NUM_ROWS){ return false; // false if we try to move outside the playing area } if (board[x][y]!=0){ // false if the other shape is already on this place return false; } } return true; // all positions are vacant } /** * Check free space for a piece rotation */ private boolean checkSpaceForRoration(int [][] newCoordinates, Shape currentShape) { for (int i = 0; i < 4; i++) { // for all blocks in the current shape... // calculates perspective coordinates int x = currentShape.getBlockArray()[i].getXPos() + newCoordinates[i][0]; int y = currentShape.getBlockArray()[i].getYPos() + newCoordinates[i][1]; if (x < 0 | x >= NUM_COLS | y < 0 | y >= NUM_ROWS){ return false; // false if we try to move outside the playing area } if (board[x][y]!=0){ // false if the other shape is already on this place return false; } } return true; // can be rotated } /** * Move a shape one row down */ public void moveDown(){ if (checkSpace(0, +1, currentShape)==true){ // check if perspective coordinates for all blocks of the current shape are vacant for (int i = 0; i < 4; i++) { currentShape.getBlockArray()[i].setYPos(currentShape.getBlockArray()[i].getYPos()+1); // add to the Y-coordinates all blocks of the current shape +1 } } else { // if we can't move down current shape for (int i = 0; i < 4; i++) { // the current shape becomes a part of the board board[currentShape.getBlockArray()[i].getXPos()][currentShape.getBlockArray()[i].getYPos()]=currentShape.getBlockArray()[i].getColor(); // save color all blocks of the current shape // check a status of the game. If a part of shape lying on the first row of the board then the game over if (currentShape.getBlockArray()[i].getYPos()<1) { gameLost(); return; // exit from "for" loop } } if (isFinished==false) { // clear completed rows clearLines(); // generate a new shape currentShape=nextShape; nextShape=generateRandomShape(); } } } /** * Move a shape one colon left of right */ public void moveLeftOrRight(int newX){ if (checkSpace(newX, 0, currentShape)==true){ // check if perspective coordinates for all blocks of the current shape are vacant for (int i = 0; i < 4; i++) { currentShape.getBlockArray()[i].setXPos(currentShape.getBlockArray()[i].getXPos()+newX); // add to the X-coordinates all blocks of the current shape +1 if move right and -1 when move left } } } /** * Invoked when a Tetris shape reaches the top of the game board */ public void gameLost() { isFinished=true; t.interrupt(); // interrupt the running thread } /** * Rotate current shape clockwise or counter-clockwise * @param isRotateClockwise */ public void rotate (boolean isRotateClockwise){ int rotationIndex=currentShape.getRotationIndex(); if (isRotateClockwise==false){ // if rotate counter-clockwise than take (not current) the previous rotationIndex if (rotationIndex==0){ rotationIndex=3; } else rotationIndex--; } int [][] newCoordinates=currentShape.rotate(rotationIndex); if (isRotateClockwise==false){ // if rotate counter-clockwise than convert rotate values to opposite for (int i = 0; i < 4; i++) { newCoordinates[i][0]*=-1; newCoordinates[i][1]*=-1; } } if (checkSpaceForRoration(newCoordinates, currentShape)){ // check if perspective coordinates for all blocks of the current shape are vacant currentShape.setRotationIndex(isRotateClockwise); // save new value of rotationIndex of the current shape for (int i = 0; i < 4; i++) { // change coordinates for all blocks of the current shape currentShape.getBlockArray()[i].setXPos (currentShape.getBlockArray()[i].getXPos() + newCoordinates[i][0]); currentShape.getBlockArray()[i].setYPos (currentShape.getBlockArray()[i].getYPos() + newCoordinates[i][1]); } } } /** * Invoked when a line of Tetris blocks is formed */ public void clearLines() { boolean hasRowSpace; int numberLinesCleared = 0; for (int y=0; y<NUM_ROWS;y++) { hasRowSpace = false; for (int x=0; x<NUM_COLS; x++){ if (board[x][y]==0) { hasRowSpace=true; break; } } if (hasRowSpace==false) { numberLinesCleared++; shiftBlocksDown(y); // clear completed row y--; } } // compute award score switch (numberLinesCleared) { case 1: linesCleared += 1; break; case 2: linesCleared += 2; break; case 3: linesCleared += 3;; break; case 4: linesCleared += 4; tetrisesCleared +=1; break; } if (((int)(linesCleared/NUM_LINES_NEXT_LEVEL))>level) { // every 10 cleared lines increase the level and the speed of pieces falling level++; speed=(int) (speed*SPEED_INCREASE); // increase speed by 20% t.interrupt(); // interrupt the running thread saveGame(); // save the game (allow the user to restart a level) startGame(); // restart a thread with increased speed } } /** * Shifts the static blocks down when line/tetris is removed */ public void shiftBlocksDown(int rowNumber) { for (int y = rowNumber; y > 0; y--) { for (int x = 0; x < NUM_COLS; x++) { board[x][y] = board[x][y-1]; } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jFrontd.Classes; import Classes.FileManager; import Classes.Globals; import jFrontd.UI.MainWindow; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * * @author sj */ public class FavoriteGame { private final File ConfigDir = new File(Globals.Home+Globals.Separator+".jFrontd"); private final File FavoritesDir = new File(ConfigDir+Globals.Separator+"Favorites"); private String newline = Globals.Newline; private int ID; private String Name; private String Path; private int EmulatorID; private String Icon; private String Comment; private int TimesPlayed; private long TimeWasted; public FavoriteGame(String Name, String Path, int EmulatorID, String Icon, String Comment){ //create file ID = FavoritesDir.list().length; this.Name = Name; this.Path = Path; this.EmulatorID = EmulatorID; this.Icon = Icon; this.Comment = Comment; this.TimesPlayed = 0; this.TimeWasted = 0; //write file MakeNewFile(); } public FavoriteGame(int ID){ this.ID = ID; ReadFile(); //load file } private void MakeNewFile(){ //create the file variable File newfile = new File(FavoritesDir+Globals.Separator+ID); //If the file exists, delete it, and remake it, because it shouldn't. if (newfile.exists()){ try { newfile.delete(); newfile.createNewFile(); } catch (Exception ex) { Globals.ShowError(ex); } } //save new information to the file UpdateFile(); } private void ReadFile(){ //read the information from the file try { File newfile = new File(FavoritesDir + Globals.Separator + ID); FileReader fr = new FileReader(newfile); BufferedReader br = new BufferedReader(fr); Name = br.readLine(); Path = br.readLine(); EmulatorID = Integer.parseInt(br.readLine()); Icon = br.readLine(); Comment = br.readLine(); TimesPlayed = Integer.parseInt(br.readLine()); TimeWasted = Long.parseLong(br.readLine()); br.close(); fr.close(); } catch (Exception ex) { Globals.ShowError(ex); } } private void UpdateFile(){ try { //check arguments if (Comment.isEmpty()) { Comment = new String(" "); } //update the file File oldfile = new File(FavoritesDir + Globals.Separator + ID); oldfile.delete(); oldfile.createNewFile(); //save new information to the file FileWriter fw = new FileWriter(oldfile); fw.write(Name); fw.write(newline); fw.write(Path); fw.write(newline); fw.write(String.valueOf(EmulatorID)); fw.write(newline); fw.write(Icon); fw.write(newline); fw.write(Comment); fw.write(newline); fw.write(String.valueOf(TimesPlayed)); fw.write(newline); fw.write(String.valueOf(TimeWasted)); fw.close(); } catch (IOException ex) { Globals.ShowError(ex); } } public void DeleteFile(){ //put the reminder files into an array int DirLength = FavoritesDir.list().length; File newfiles[] = new File[DirLength]; for(int i=0;i<DirLength;i++) newfiles[i] = new File(FavoritesDir+Globals.Separator+i); //delete the current reminder File todelete = new File(FavoritesDir+Globals.Separator+ID); todelete.delete(); //move all of the ones past the deleted file to -1 for(int i=ID+1;i<DirLength;i++) newfiles[i].renameTo(newfiles[i-1]); } public void MoveUp(){ if(ID==0){ //already at the top return; } //this method will change the filename/ID so that it moves up in the displayed lists File ThisFavorite = new File(FavoritesDir+Globals.Separator+ID); File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File PrevFavorite = new File(FavoritesDir+Globals.Separator+(ID-1)); //move files around FileManager.MoveFile(PrevFavorite, Temp); FileManager.MoveFile(ThisFavorite, PrevFavorite); FileManager.MoveFile(Temp, ThisFavorite); } public void MoveDown(){ if(ID==(FavoritesDir.list().length-1)){ //already at the bottom return; } //this method will change the filename/ID so that it moves up in the displayed lists File ThisFavorite = new File(FavoritesDir+Globals.Separator+ID); File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File PrevFavorite = new File(FavoritesDir+Globals.Separator+(ID+1)); //move files around FileManager.MoveFile(PrevFavorite, Temp); FileManager.MoveFile(ThisFavorite, PrevFavorite); FileManager.MoveFile(Temp, ThisFavorite); } public void MoveTo(int newID){ if(newID < 0){ //you can't move it past the firs }else if(newID >= FavoritesDir.list().length){ //you can't move it past the last }else if(newID == ID+1){ //just use move down MoveDown(); }else if (newID == ID-1){ //just use move up MoveUp(); }else{ //move it to the selected ID //put the current in a temporary file File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File ThisFavorite = new File(FavoritesDir+Globals.Separator+ID); File NewFavorite = new File(FavoritesDir+Globals.Separator+newID); //create all files File[] AllFiles = new File[FavoritesDir.list().length]; for(int i=0;i<AllFiles.length;i++){ AllFiles[i] = new File(FavoritesDir+Globals.Separator+i); } //move ID to temporary file FileManager.MoveFile(ThisFavorite, Temp); //decide if we are moving forwards or backwards if(ID > newID){ //moving it backwards //SO, move from newID, to one before the current ID, forwards //move first file on its own for(int i=(ID-1);i>=newID;i--){ FileManager.MoveFile(AllFiles[i], AllFiles[i+1]); } //move temp file into newID FileManager.MoveFile(Temp, AllFiles[newID]); }else if(ID < newID){ //moving it forwards //SO, move from newID, to one after the current ID, backwards //move first file on its own for(int i=(ID+1);i<=newID;i++){ FileManager.MoveFile(AllFiles[i], AllFiles[i-1]); } //move temp file into newID FileManager.MoveFile(Temp, NewFavorite); } } } public String getName(){ return Name; } public String getPath(){ return Path; } public int getEmulator(){ return EmulatorID; } public String getIcon(){ return Icon; } public String getComment(){ return Comment; } public int getTimesPlayed(){ return TimesPlayed; } public void setName(String Name){ this.Name = Name; UpdateFile(); } public void setPath(String Path){ this.Path = Path; UpdateFile(); } public void setEmulator(int EmulatorID){ this.EmulatorID = EmulatorID; UpdateFile(); } public void setIcon(String Icon){ this.Icon = Icon; UpdateFile(); } public void setComment(String Comment){ this.Comment = Comment; UpdateFile(); } public void IncreaseTimesPlayed(){ TimesPlayed++; UpdateFile(); } public void IncreaseTimeWasted(long TimeWasted){ this.TimeWasted+=TimeWasted; UpdateFile(); } public long getTimeWasted(){ return TimeWasted; } public void setID(int ID){ this.ID = ID; } }
package com.example.threegoodthings; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.example.threegoodthings.MemoContract.*; import android.support.v7.app.AppCompatActivity; /** * Created by Ορφέας Τσαρτσιανίδης on 5/13/2016. */ public class AddEntry extends AppCompatActivity { private MemoDBHelper dbHelper; private long id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_entry); Intent intent = getIntent(); id = intent.getLongExtra("key1", -99); if (id != -99) { String[] projection = new String[]{ MemoContract.MemoEntry._ID, MemoContract.MemoEntry.COLUMN_NAME_DATE, MemoContract.MemoEntry.COLUMN_NAME_TEXT1, MemoContract.MemoEntry.COLUMN_NAME_TEXT2, MemoContract.MemoEntry.COLUMN_NAME_TEXT3 }; dbHelper = new MemoDBHelper(this); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(MemoContract.MemoEntry.TABLE_NAME, projection, "_ID = ?", new String[]{"" + id}, null, null, null, null); cursor.moveToFirst(); String date = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_NAME_DATE)); EditText etDate = (EditText) findViewById(R.id.date); etDate.setText(date); String text1 = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_NAME_TEXT1)); EditText etText1 = (EditText) findViewById(R.id.text1); etText1.setText(text1); String text2 = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_NAME_TEXT2)); EditText etText2 = (EditText) findViewById(R.id.text2); etText2.setText(text2); String text3 = cursor.getString(cursor.getColumnIndex(MemoContract.MemoEntry.COLUMN_NAME_TEXT3)); EditText etText3 = (EditText) findViewById(R.id.text3); etText3.setText(text3); } } public void update(View view) { // Gets the data repository in write mode dbHelper = new MemoDBHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); String date = ((EditText) findViewById(R.id.date)).getText().toString(); values.put(MemoContract.MemoEntry.COLUMN_NAME_DATE, date); String text1 = ((EditText) findViewById(R.id.text1)).getText().toString(); values.put(MemoContract.MemoEntry.COLUMN_NAME_TEXT1, text1); String text2 = ((EditText) findViewById(R.id.text2)).getText().toString(); values.put(MemoContract.MemoEntry.COLUMN_NAME_TEXT2, text2); String text3 = ((EditText) findViewById(R.id.text3)).getText().toString(); values.put(MemoContract.MemoEntry.COLUMN_NAME_TEXT2, text3); // Insert the new row, returning the primary key value of the new row if (id == -99) { long newRowId = db.insert(MemoContract.MemoEntry.TABLE_NAME, null, values); } else { db.update(MemoContract.MemoEntry.TABLE_NAME, values, "_ID = ?", new String[]{"" + id}); } Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } public void delete(View view) { dbHelper = new MemoDBHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); if(id == -99) { } else { db.delete(MemoContract.MemoEntry.TABLE_NAME, "_ID = ?", new String[]{"" + id}); } Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }
package com.research.hadoop.join.reduce; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.MultipleInputs; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.net.URI; /** * @fileName: JoinReduceDriver.java * @description: JoinReduceDriver.java类说明 * @author: by echo huang * @date: 2020-03-27 11:49 */ public class JoinReduceDriver extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = Job.getInstance(getConf(), "joinReduce"); job.setJarByClass(getClass()); String output = "/user/join/reduce"; FileSystem fs = FileSystem.get(URI.create(output), getConf()); if (fs.exists(new Path(output))) { fs.delete(new Path(output), true); } Path stationInputPath = new Path("/user/station.txt"); Path record = new Path("/user/record.txt"); MultipleInputs.addInputPath(job, stationInputPath, TextInputFormat.class, StationMapper.class); MultipleInputs.addInputPath(job, record, TextInputFormat.class, RecordMapper.class); FileOutputFormat.setOutputPath(job, new Path(output)); job.setPartitionerClass(JoinRecordWithStationName.class); job.setCombinerKeyGroupingComparatorClass(TextPair.FirstCompartor.class); job.setReducerClass(JoinReducer.class); job.setMapOutputKeyClass(TextPair.class); job.setMapOutputValueClass(Text.class); job.setOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); return job.waitForCompletion(true) ? 1 : 0; } public static void main(String[] args) throws Exception { int exit = ToolRunner.run(new JoinReduceDriver(), args); System.exit(exit); } }
package com.service.impl; import com.bean.Role; import com.mapper.RoleMapper; import com.service.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("RoleService") public class RoleServiceImpl implements RoleService { @Autowired RoleMapper roleMapper; public List<Role> getRole(Role role){ return roleMapper.getRole(role); } }
package gov.samhsa.c2s.pcm.service.consentexport; import gov.samhsa.c2s.pcm.service.dto.ConsentXacmlDto; import gov.samhsa.c2s.pcm.service.dto.XacmlRequestDto; public interface ConsentExportService { /** * Export consent to xacml format. * * @param xacmlRequestDto the consent * @return the string */ ConsentXacmlDto exportConsent2XACML(XacmlRequestDto xacmlRequestDto); }
package com.boot.third.Repository; import com.boot.third.domain.User; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.CrudRepository; import java.util.Collection; import java.util.List; public interface UserRepository extends CrudRepository<User, Integer> { public List<User> findUserByName(String name); public Collection<User> findByAge(int age); public Collection<User> findByNameContaining(String name); public Collection<User> findByNameContainingOrEmailContaining(String name, String email); public Collection<User> findByNameContainingAndUserNoGreaterThan(String name, int userNo); public Collection<User> findByUserNoGreaterThanOrderByUserNoDesc(int userNo); public List<User> findByUserNoGreaterThanOrderByUserNoDesc(int userNo, Pageable paging); public List<User> findByUserNoGreaterThan(int userNo, Pageable paging); }
package DomFaryna.FiveGuysOneRobot.HelloWorld; import org.junit.Test; public class HelloWorld { @Test public void HelloWorldTest(){ System.out.println("Hello test"); } }
/* * 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 stockmanagement; import java.sql.Connection; /** * * @author haktu */ public interface StockManagament { public void stockSell(Connection con); public void AddProducts(Connection con); public void DeleteProduct(Connection con); public void SelectProducts(Connection con); public void UrunlerTabloGuncelle(Connection con); }
package com.bluemingo.bluemingo.util; import java.io.File; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.bluemingo.bluemingo.domain.ImageVO; @Component("fileUtils") public class FileUtils { // private static final String filePath = "C:\\Download\\"; private static final String filePath = "www/bluemingo/image/"; public ImageVO parseInsertFileInfo(HttpServletRequest request) throws Exception{ MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request; Iterator<String> iterator = multipartHttpServletRequest.getFileNames(); MultipartFile multipartFile = null; String originalFileName = null; String originalFileExtension = null; String storedFileName = null; ImageVO cvo = new ImageVO(); /* * vo로 해야할 것 * 이미지가 사용될 table_name과 key값이 저장 되어 있다. * 이를 이용하여 연결해야한다. */ File file = new File(filePath); if(file.exists() == false){ file.mkdirs(); } while(iterator.hasNext()){ multipartFile = multipartHttpServletRequest.getFile(iterator.next()); if(multipartFile.isEmpty() == false){ originalFileName = multipartFile.getOriginalFilename(); originalFileExtension = originalFileName.substring(originalFileName.lastIndexOf(".")); storedFileName = CommonUtils.getRandomString() + originalFileExtension; file = new File(filePath + storedFileName); multipartFile.transferTo(file); cvo.setOriginal_file_name(originalFileName); cvo.setStored_file_name(storedFileName); cvo.setFile_size(multipartFile.getSize()); } } return cvo; } public void downloadFile(ImageVO ivo, HttpServletResponse response) throws Exception{ String storedFileName = ivo.getStored_file_name(); String originalFileName = ivo.getOriginal_file_name(); byte fileByte[] = org.apache.commons.io.FileUtils.readFileToByteArray(new File("www/bluemingo/image/"+storedFileName)); // byte fileByte[] = org.apache.commons.io.FileUtils.readFileToByteArray(new File("C:\\Download\\"+storedFileName)); response.setContentType("application/octet-stream"); response.setContentLength(fileByte.length); response.setHeader("Content-Disposition", "attachment; fileName=\"" + URLEncoder.encode(originalFileName,"UTF-8")+"\";"); response.setHeader("Content-Transfer-Encoding", "binary"); response.getOutputStream().write(fileByte); response.getOutputStream().flush(); response.getOutputStream().close(); } }
package com.tencent.mm.plugin.location.ui.impl; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; class TrackPointAnimAvatar$2 implements AnimationListener { final /* synthetic */ TrackPointAnimAvatar kKr; TrackPointAnimAvatar$2(TrackPointAnimAvatar trackPointAnimAvatar) { this.kKr = trackPointAnimAvatar; } public final void onAnimationStart(Animation animation) { } public final void onAnimationRepeat(Animation animation) { } public final void onAnimationEnd(Animation animation) { this.kKr.bringToFront(); TrackPointAnimAvatar.b(this.kKr).startAnimation(TrackPointAnimAvatar.c(this.kKr)); } }
package com.tencent.mm.g.a; public final class ic$a { public String Yy; public int errCode; }
package com.liferay.mobile.screens.messageboardscreenlet.interactor; import com.liferay.mobile.screens.base.list.interactor.BaseListInteractorListener; /** * Created by darshan on 6/8/15. */ public interface MyListInteractorListener<E> extends BaseListInteractorListener<E> { void setTotalCount(Integer result); }
package com.example.parkminhyun.trackengine; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by 12aud on 2017-06-26. */ public class AccreditAdapter extends RecyclerView.Adapter<AccreditAdapter.ItemViewHolder> { public class ItemViewHolder extends RecyclerView.ViewHolder{ CardView cv; // cardView TextView name; // 아이템 이름 Context mContext; public ItemViewHolder(final View itemView) { super(itemView); cv = (CardView)itemView.findViewById(R.id.cv_accredit); name = (TextView)itemView.findViewById(R.id.accredit_name); name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("onClick",name.getText().toString()); if(name.getText().equals("공업수학1")) { new AlertDialog.Builder(itemView.getContext()).setTitle("공학수학1") .setMessage("공학도가 기본적으로 습득해야 할 수학분야인 상미분방정식의 " + "기본개념을 이해시키고 여러 형태의 상미분 방정식과 그에 관한 해법을" + " 체계적으로 지도하여 다양한 공학분야의 전공과목 이수를 도울 뿐만 아니라, 수학적 소양과 과학적 사고 능력을 배양한다.") .setNeutralButton("닫기",new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dig,int sumthin){ } }).show(); } else if(name.getText().equals("컴퓨터네트워크")) { new AlertDialog.Builder(itemView.getContext()).setTitle("컴퓨터네트워크") .setMessage("컴퓨터 네트워크의 계층화된 구조를 알아보고 관련된 프로토콜과 라우팅 알고리즘들에 대해서 학습한다.") .setNeutralButton("닫기",new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dig,int sumthin){ } }).show(); } else if(name.getText().equals("이산수학및프로그래밍")) { new AlertDialog.Builder(itemView.getContext()).setTitle("이산수학및프로그래밍") .setMessage("컴퓨터는 이진수 체계로 운영되는 특성상 그 응용과정에서도 주로 이산적인 자료를 대상으로 하게 된다. 컴퓨터에 관련된 집합과 함수, 행렬, 부울대수, 알고리즘 등의 수학적 배경을 학습한다.") .setNeutralButton("닫기",new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dig,int sumthin){ } }).show(); } else if(name.getText().equals("알고리즘및실습")) { new AlertDialog.Builder(itemView.getContext()).setTitle("알고리즘및실습") .setMessage("알고리즘이란 어떤 구체적 목표를 달성하기 위한 분명한 절차를 말한다. 컴퓨터를 사용하여 어러 가지 유형의 문제를 해결하는 일반적인 알고리즘 기법을 소개한다.") .setNeutralButton("닫기",new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dig,int sumthin){ } }).show(); } // switch(name.getText()) // { // case "공업수학1": // mContext.startActivity(new Intent(mContext, VirtualRealityActivity.class)); // break; // case 1: // mContext.startActivity(new Intent(mContext, ArtificialIntelligenceActivity.class)); // break; // case 2: // mContext.startActivity(new Intent(mContext, ApplicationSWActivity.class)); // break; // case 3: // mContext.startActivity(new Intent(mContext, HCIAndVCActivity.class)); // break; // case 4: // mContext.startActivity(new Intent(mContext, MultiMediaActivity.class)); // break; // ((AdapterCallback)mContext).startEachActivity(getPosition()); } }); } } List<Item> items; Context mContext; public AccreditAdapter(Context context, List<Item> items) { this.mContext = context; this.items = items; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.accredit_card, viewGroup, false); ItemViewHolder ivh = new ItemViewHolder(v); return ivh; } @SuppressLint("NewApi") @Override public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) { itemViewHolder.name.setText(items.get(i).getName()); } @Override public int getItemCount() { return items.size(); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView){ super.onAttachedToRecyclerView(recyclerView); } }
package SEED128; import org.apache.commons.codec.CharEncoding; /** * * @author 인프라닉스 * */ public class Test { private final static String KEY = "0000000000000000"; private final static String DATA = "0123456789abcdef"; public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { try { SEED_KISA seed_KISA = new SEED_KISA(); // Round keys for encryption or decryption int pdwRoundKey[] = new int[32]; // User secret key byte pbUserKey[] = KEY.getBytes(CharEncoding.UTF_8); // input plaintext to be encrypted byte pbData[] = DATA.getBytes(CharEncoding.UTF_8); byte pbCipher[] = new byte[16]; byte pbPlain[] = new byte[16]; System.out.println("[ Test SEED reference code ]"); System.out.print("\n\n"); // Derive roundkeys from user secret key seed_KISA.SeedRoundKey(pdwRoundKey, pbUserKey); // Encryption seed_KISA.SeedEncrypt(pbData, pdwRoundKey, pbCipher); System.out.println("[ Test Encrypt mode ]"); System.out.print("Key\t\t: "); System.out.println(new String(pbUserKey,CharEncoding.UTF_8)); System.out.print("Plaintext\t: "); System.out.println(new String(pbData,CharEncoding.UTF_8)); System.out.print("Ciphertext\t: "); for (int i = 0; i < 16; i++) System.out.print(Integer.toHexString(0xff & pbCipher[i])); System.out.print("\n\n"); // Decryption seed_KISA.SeedDecrypt(pbCipher, pdwRoundKey, pbPlain); System.out.println("[ Test Decrypt mode ]"); System.out.print("Key\t\t: "); System.out.println(new String(pbUserKey,CharEncoding.UTF_8)); System.out.print("Ciphertext\t: "); for (int i = 0; i < 16; i++) System.out.print(Integer.toHexString(0xff & pbCipher[i])); System.out.print("\n"); System.out.print("Plaintext\t: "); System.out.println(new String(pbPlain,CharEncoding.UTF_8)); } catch (Exception e) { } } }
package org.spring.fom.support.task.download.helper; import java.util.zip.ZipOutputStream; import org.spring.fom.support.task.download.DownloadZipTask; /** * ZipDownloadTask中需要的具体操作方法 * * @see DownloadHelper * @see DownloadZipTask * * @author shanhm1991@163.com * */ public interface DownloadZipHelper extends DownloadHelper { /** * 根据sourceUri获取资源名称 * @param sourceUri 资源uri * @return source name */ String getSourceName(String sourceUri); /** * 将uri对应的资源写入zipOutStream * @param name 写入zip时使用的文件名称 * @param sourceUri 资源uri * @param zipOutStream zip输出流 * @return 写入字节数 * @throws Exception Exception */ long zipEntry(String name, String sourceUri, ZipOutputStream zipOutStream) throws Exception; }
package ioccontainer.materials; public class AnotherDependency { }
package de.zarncke.lib.www; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.simpleframework.http.Request; import org.simpleframework.http.Response; import org.simpleframework.http.core.Container; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import de.zarncke.lib.coll.L; import de.zarncke.lib.err.ExceptionUtil; import de.zarncke.lib.io.IOTools; import de.zarncke.lib.log.Log; /** * Http container which support WebDAV (basically). Currently doesn't work with Windows. * * @author Gunnar Zarncke */ public class WebService implements Container { private static final String MIMETYPE_HTML = "text/html"; public interface Content { Result get(String path) throws Exception; void addName(Object it, Map m); Object getProp(String path); List<Object> children(Object base); String getPath(Object it); Date getCreationDate(Object it); Result putOrPost(String path, String ctIn, byte[] bin, boolean isPost); void stopAll(); String getCursor(Object it); Object getMime(Object it); } public static class Result { public Object obj; public int code; public String type; } private static final String HEADER_CONTENT_TYPE = "Content-Type"; private static class ErrorMethod implements HttpMethod { public void execute(final Request req, final Response resp) throws IOException { resp.set("DAV", "1"); resp.setCode(501); byte[] ba = "unsupported operation".getBytes(); OutputStream os = resp.getOutputStream(ba.length); os.write(ba); os.close(); } } private class GetMethod implements HttpMethod { private final boolean isHead; public GetMethod(final boolean isHead) { this.isHead = isHead; } public void execute(final Request req, final Response resp) throws IOException { resp.set("DAV", "1"); resp.setDate("Last-Modified", System.currentTimeMillis()); String path = preprocessUri(req.getPath().getPath()); int code; Object obj; String ct = "text/plain"; try { Result res = WebService.this.content.get(path); code = res.code; obj = res.obj; if (res.code == 302) { resp.set("Location", obj.toString()); } if (res.type != null) { ct = res.type; } } catch (Throwable t) { // NOPMD Log.LOG.get().report(t); obj = ExceptionUtil.getStackTrace(t).getBytes(); code = 500; } byte[] ba; if (obj instanceof byte[]) { ba = (byte[]) obj; } else { ba = "no byte[] found".getBytes(); code = 500; } resp.set("Content-Type", ct); resp.setCode(code); OutputStream os = resp.getOutputStream(ba.length); if (this.isHead) { resp.setContentLength(0); } else { os.write(ba); } os.close(); } } private interface HttpMethod { public void execute(Request req, Response resp) throws IOException; } private class OptionsMethod implements HttpMethod { public void execute(final Request req, final Response resp) throws IOException { String path = req.getPath().getPath(); log(path, ""); // if ( "*".equals(path) ) // { // // } // else // { resp.set("Allow", "COPY,DELETE,GET,HEAD,MKCOL,MOVE,OPTIONS,PROPFIND,PROPPATCH,PUT"); resp.set("DAV", "1"); // hack for M$: resp.set("MS-Author-Via", "DAV"); // } resp.setCode(200); resp.setContentLength(0); resp.getOutputStream().close(); } } private class PropMethod implements HttpMethod { public void execute(final Request req, final Response resp) throws IOException { resp.set("DAV", "1"); String path = preprocessUri(req.getPath().getPath()); // TODO: this is a workaround for WebDAV collection handling! if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } byte[] ba; try { Object base; try { base = WebService.this.content.getProp(path); log(path, base); } catch (Throwable t) { // NOPMD Log.LOG.get().report(t); throw new StatusCodeExit(500, ExceptionUtil.getStackTrace(t)); } String dep = req.getValue("Depth"); int d; if (dep == null || "infinity".equals(dep)) { d = -1; } else { try { d = Integer.parseInt(dep); } catch (NumberFormatException nfe) { throw new StatusCodeExit(400, "Depth invalid"); } } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler() { public void error(final SAXParseException exception) throws SAXException { exception.printStackTrace(System.out); } public void fatalError(final SAXParseException exception) throws SAXException { exception.printStackTrace(System.out); throw exception; } public void warning(final SAXParseException exception) throws SAXException { exception.printStackTrace(System.out); } }); InputStream ins = req.getInputStream(); byte[] iba = IOTools.getAllBytes(ins); if (iba.length == 0) { makeMultiStatus(WebService.this.baseUri, L.l(base), resp); return; // throw new StatusCodeExit(400, "missing xml body"); } System.out.println(new String(iba)); Document doc = db.parse(new ByteArrayInputStream(iba));// ins); Element rootElement = doc.getDocumentElement(); if (!DAV_NAMESPACE.equals(rootElement.getNamespaceURI()) || !"propfind".equals(rootElement.getLocalName())) { throw new StatusCodeExit(400, "missing root element DAV:propfind"); } NodeList nl = rootElement.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { if (DAV_NAMESPACE.equals(n.getNamespaceURI())) { String nn = n.getLocalName(); if ("prop".equals(nn)) { Collection rprops = new HashSet(8); NodeList nl2 = n.getChildNodes(); for (int i2 = 0; i2 < nl2.getLength(); i2++) { Node n2 = nl2.item(i2); if (n2.getNodeType() == Node.ELEMENT_NODE) { rprops.add(n2.getNamespaceURI() + n2.getLocalName()); } } makeMultiStatus(WebService.this.baseUri, findThemByDepth(base, d), resp); return; } if ("allprop".equals(nn)) { // Collection rprops = getProps(base).keySet(); makeMultiStatus(WebService.this.baseUri, findThemByDepth(base, d), resp); return; } if ("propname".equals(nn)) { // Set s = getProps(base).keySet(); makeMultiStatus(WebService.this.baseUri, Collections.EMPTY_LIST, resp); return; } } } } resp.setCode(500); ba = "unsupported operation".getBytes(); } catch (ParserConfigurationException e) { resp.setCode(500); String err = "parser config excep " + ExceptionUtil.getStackTrace(e); ba = err.getBytes(); } catch (SAXException e) { resp.setCode(422); String err = "parser excep " + ExceptionUtil.getStackTrace(e); ba = err.getBytes(); } catch (StatusCodeExit e) { resp.setCode(e.getCode()); String err = e.getMessage(); ba = err.getBytes(); } log(path, resp.getCode() + "->" + new String(ba)); OutputStream os = resp.getOutputStream(ba.length); os.write(ba); os.close(); } } private class PropPatchMethod implements HttpMethod { public void execute(final Request req, final Response resp) throws IOException { String path = req.getPath().getPath(); log(path, ""); resp.setCode(403); resp.setContentLength(0); resp.getOutputStream().close(); } } private class PutMethod implements HttpMethod { private final boolean isPost; public PutMethod(final boolean isPost) { this.isPost = isPost; } public void execute(final Request req, final Response resp) throws IOException { // dav req headers: // If = "If" ":" ( 1*No-tag-list | 1*Tagged-list) // Depth = "Depth" ":" ("0" | "1" | "infinity") // COPY+MOVE: // Destination = "Destination" ":" absoluteURI // Overwrite = "Overwrite" ":" ("T" | "F") // responses: // Status-URI = "Status-URI" ":" *(Status-Code Coded-URL) resp.set("DAV", "1"); resp.setDate("Last-Modified", System.currentTimeMillis()); String path = preprocessUri(req.getPath().getPath()); String ctIn = req.getValue(HEADER_CONTENT_TYPE); InputStream ins = req.getInputStream(); byte[] bin = IOTools.getAllBytes(ins); System.out.println("PUT " + new String(bin)); int code = 404; String ct = MIMETYPE_HTML; Object obj; try { Result res = WebService.this.content.putOrPost(path, ctIn, bin, this.isPost); obj = res.obj; code = res.code; if (res.type != null) { ct = res.type; } } catch (Throwable t) { // NOPMD Log.LOG.get().report(t); obj = ExceptionUtil.getStackTrace(t).getBytes(); code = 500; } byte[] ba; if (obj instanceof byte[]) { ba = (byte[]) obj; } else { code = 500; ba = "error".getBytes(); } resp.set(HEADER_CONTENT_TYPE, ct); resp.setCode(code); OutputStream os = resp.getOutputStream(ba.length); os.write(ba); os.close(); } } private static class StatusCodeExit extends Exception { private final int code; public StatusCodeExit(final int code, final String msg) { super(msg); this.code = code; } public int getCode() { return this.code; } @Override public String toString() { return this.code + " " + super.toString(); } } private static final String DAV_NAMESPACE = "DAV:"; private static final String DAV_PREFIX = "D"; private static final int INFINITE_DEPTH = 6; // Map of String (propname) to propvalue private Map getProps(final Object it, final Document doc, final boolean asCollection) { Map m = new HashMap(12); this.content.addName(it, m); String path = this.content.getPath(it); int p = path.lastIndexOf("/"); if (p >= 0) { path = path.substring(p + 1); } if (asCollection) { path = ".." + path; } Date date = this.content.getCreationDate(it); m.put("DAV:creationdate", date); m.put("DAV:displayname", path); String len = "0"; m.put("DAV:getcontentlength", len); m.put("DAV:getcontenttype", this.content.getMime(it)); m.put("DAV:getetag", "xyz"); m.put("DAV:getlastmodified", date); if (asCollection) { Element el = doc.createElementNS(DAV_NAMESPACE, "collection"); el.setPrefix(DAV_PREFIX); m.put("DAV:resourcetype", el); } else { m.put("DAV:resourcetype", ""); } m.put("DAV:supportedlock", ""); m.put("DAV:lockdiscovery", ""); m.put("DAV:source", ""); /* * <D:link> <F:projfiles>Makefile </F:projfiles> <D:src>http://foo.bar/program </D:src> * <D:dst>http://foo.bar/src/makefile </D:dst> </D:link> */ m.put("DAV:executable", "false"); return m; } private final String baseUri; private final HttpMethod defaultMethod = new ErrorMethod(); private final Map methods = new HashMap(); Content content; private final File docRoot; public WebService(final String baseUri, final String docRoot, final Content content) { this.docRoot = new File(docRoot); this.baseUri = baseUri; this.content = content; this.methods.put("GET", new GetMethod(false)); this.methods.put("PUT", new PutMethod(false)); this.methods.put("POST", new PutMethod(true)); this.methods.put("HEAD", new GetMethod(true)); this.methods.put("OPTIONS", new OptionsMethod()); this.methods.put("PROPFIND", new PropMethod()); this.methods.put("PROPPATCH", new PropPatchMethod()); this.methods.put("LOCK", new ErrorMethod()); this.methods.put("UNLOCK", new ErrorMethod()); this.methods.put("COPY", new ErrorMethod()); this.methods.put("MOVE", new ErrorMethod()); this.methods.put("MKCOL", new ErrorMethod()); this.methods.put("DELETE", new ErrorMethod()); } private Collection findThemByDepth(final Object base, final int d) { Collection c = new LinkedList(); findThemByDepth(base, d < 0 ? INFINITE_DEPTH : d, c); return c; } private void findThemByDepth(final Object base, final int d, final Collection accu) { accu.add(base); if (d > 0) { for (Object child : this.content.children(base)) { findThemByDepth(child, d - 1, accu); } } } private void log(final String path, final Object res) { System.out.println(path + "->" + res); } // prefix = url part before path // Collection of It private void makeMultiStatus(final String baseUri, final Collection coll, final Response resp) throws IOException { resp.setCode(207); resp.set("Content-Type", "text/xml; charset=\"utf-8\""); OutputStream outs = resp.getOutputStream(); Document doc; try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element multistatus = doc.createElementNS(DAV_NAMESPACE, "multistatus"); multistatus.setPrefix(DAV_PREFIX); // System.out.println(multistatus2.getPrefix()+" "+ // multistatus2.getNamespaceURI()+" " +multistatus2.getLocalName()+" // " +multistatus2.getTagName()); for (Iterator iter = coll.iterator(); iter.hasNext();) { Object element = iter.next(); multistatus.appendChild(makeResponseXml(element, baseUri, doc, df, true)); multistatus.appendChild(makeResponseXml(element, baseUri, doc, df, false)); Element responsedesc = doc.createElementNS(DAV_NAMESPACE, "responsedescription"); responsedesc.setPrefix(DAV_PREFIX); responsedesc.appendChild(doc.createTextNode("welldone")); multistatus.appendChild(responsedesc); } doc.appendChild(multistatus); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(outs); ByteArrayOutputStream baus = new ByteArrayOutputStream(); StreamResult result = new StreamResult(baus); transformer.transform(source, result); System.out.println(new String(baus.toByteArray())); outs.write(baus.toByteArray()); } catch (RuntimeException ioe) { ioe.printStackTrace(System.out); throw ioe; } catch (Exception e) { e.printStackTrace(); throw (IOException) new IOException("parser").initCause(e); } finally { outs.close(); } } private Element makePropXml(final Document doc, final DateFormat df, final Map m) { Element prop = doc.createElementNS(DAV_NAMESPACE, "prop"); prop.setPrefix(DAV_PREFIX); for (Iterator iterator = m.entrySet().iterator(); iterator.hasNext();) { Map.Entry me = (Map.Entry) iterator.next(); Object v = me.getValue(); String name = (String) me.getKey(); int p = name.indexOf(":"); Element ee; if (p >= 0) { ee = doc.createElementNS(name.substring(0, p + 1), name.substring(p + 1)); ee.setPrefix(DAV_PREFIX); } else { ee = doc.createElement(name); } if (v != null) { String txt; if (v instanceof Date) { txt = df.format(v); ee.appendChild(doc.createTextNode(txt)); } else if (v instanceof Node) { ee.appendChild((Node) v); } else { txt = v.toString(); ee.appendChild(doc.createTextNode(txt)); } } prop.appendChild(ee); } return prop; } private Element makeResponseXml(final Object element, final String baseUri, final Document doc, final DateFormat df, final boolean asCollection) { Element response = doc.createElementNS(DAV_NAMESPACE, "response"); response.setPrefix(DAV_PREFIX); { Element href = doc.createElementNS(DAV_NAMESPACE, "href"); href.setPrefix(DAV_PREFIX); String cursor = this.content.getCursor(element); String xcursor = cursor; if (asCollection) { int p = cursor.lastIndexOf("/"); if (p > 0) { xcursor = cursor.substring(0, p + 1) + ".." + cursor.substring(p + 1); } } href.appendChild(doc.createTextNode(baseUri + xcursor)); response.appendChild(href); Element propstat = doc.createElementNS(DAV_NAMESPACE, "propstat"); propstat.setPrefix(DAV_PREFIX); { Map m = getProps(element, doc, asCollection); propstat.appendChild(makePropXml(doc, df, m)); Element st = doc.createElementNS(DAV_NAMESPACE, "status"); st.setPrefix(DAV_PREFIX); st.appendChild(doc.createTextNode("HTTP/1.1 200 OK")); propstat.appendChild(st); } response.appendChild(propstat); } return response; } private String preprocessUri(String path) { if (path.startsWith("/")) { path = path.substring(1); } // all "..xxx" files refer actually to their "xxx" counterpart (due to // webdav collection limitations) path = path.replaceAll("\\.\\.", ""); return path; } public void handle(final Request req, final Response resp) { resp.set("Server", "ZarnckeServer/0.001 (Simple/2.6)"); resp.setDate("Date", System.currentTimeMillis()); /* * Cache-Control ; Section 14.9 */ HttpMethod meth = (HttpMethod) this.methods.get(req.getMethod()); if (meth == null) { meth = this.defaultMethod; } // TODO: remove: this is test/dbeug only Map reqHeaders = new HashMap(); reqHeaders.put("Accept", req.getValue("Accept")); reqHeaders.put("Accept-Charset", req.getValue("Accept-Charset")); reqHeaders.put("Accept-Encoding", req.getValue("Accept-Encoding")); reqHeaders.put("Accept-Language", req.getValue("Accept-Language")); reqHeaders.put("Authorization", req.getValue("Authorization")); reqHeaders.put("Expect", req.getValue("Expect")); reqHeaders.put("From", req.getValue("From")); reqHeaders.put("Host", req.getValue("Host")); reqHeaders.put("If-Match", req.getValue("If-Match")); reqHeaders.put("If-Modified-Since", req.getValue("If-Modified-Since")); reqHeaders.put("If-None-Match", req.getValue("If-None-Match")); reqHeaders.put("If-Range", req.getValue("If-Range")); reqHeaders.put("If-Unmodified-Since", req.getValue("If-Unmodified-Since")); reqHeaders.put("Range", req.getValue("Range")); reqHeaders.put("Referer", req.getValue("Referer")); reqHeaders.put("User-Agent", req.getValue("User-Agent")); reqHeaders.put("DAV", req.getValue("DAV")); reqHeaders.put("If", req.getValue("If")); System.out.println(meth + " " + reqHeaders); try { meth.execute(req, resp); } catch (IOException e) { // TODO suitable error handling! e.printStackTrace(); throw new RuntimeException("what now?", e); } } public void stop() { this.content.stopAll(); } }
package it.binarybrain.hw.i2c.json; import it.binarybrain.hw.Servo; import java.io.IOException; import java.lang.reflect.Type; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class ServoSerializer implements JsonSerializer<Servo> { @Override public JsonElement serialize(Servo src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); //common properties obj.addProperty("id", src.getId()); obj.addProperty("controllerId", src.getController().getId()); try{ obj.addProperty( "channelNumber", src.getController().getPWMControllableChannel(src) ); }catch(IOException e){} //subclass specific properties obj.addProperty("type", "servo"); obj.addProperty("degreePerSecond", src.getDegreePerSecond()); obj.addProperty("minAngle", src.getMinAngle()); obj.addProperty("maxAngle", src.getMaxAngle()); obj.addProperty("minAngleDutyCycle", src.getMinAngleDutyCycle()); obj.addProperty("maxAngleDutyCycle", src.getMaxAngleDutyCycle()); obj.addProperty("clockwiseRotation", src.getClockwiseRotation()); return obj; } }
package com.tencent.mm.plugin.sport.c; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import org.json.JSONObject; public final class k implements SensorEventListener { private static long opc = 0; private static long opd = 0; private static long ope = 0; private static long opf = 0; private static long opg = 0; private static long oph = 0; private static long opi = 0; private static long opj = 0; public c opk; public static long bFO() { return ope; } public static long bFP() { return opg; } public k() { opg = 0; oph = 0; opi = 0; opj = 0; opc = 0; opd = 0; ope = 0; opf = 0; } public final void onSensorChanged(SensorEvent sensorEvent) { JSONObject bFJ = g.bFJ(); if (bFJ.optInt("deviceStepSwitch") != 1) { if (this.opk != null) { this.opk.bFH(); } x.i("MicroMsg.Sport.SportStepDetector", "device step switch off"); return; } int optInt = bFJ.optInt("stepCounterMaxStep5m", 3000); String str; if (sensorEvent != null && sensorEvent.values != null && sensorEvent.values.length > 0) { x.i("MicroMsg.Sport.SportStepDetector", "Step change %f, accuracy %s, %s", new Object[]{Float.valueOf(sensorEvent.values[0]), Integer.valueOf(sensorEvent.accuracy), Long.valueOf(sensorEvent.timestamp)}); long ciZ = bi.ciZ() / 10000; if (opg == 0) { opg = i.xS(202); } if (opd == 0) { opd = i.xS(203); } if (ope == 0) { ope = i.xS(201); } if (opf == 0) { opf = ope; } if (oph == 0) { oph = i.xS(204); } if (opi == 0) { opi = oph; } if (opj == 0) { opj = i.xS(209); } x.i("MicroMsg.Sport.SportStepDetector", "currentVar: beginOfToday %d saveTodayTime %d preSensorStep %d currentTodayStep %d lastSaveSensorStep %d lastSaveStepTime %d preSysStepTime %d preSensorNanoTime %d", new Object[]{Long.valueOf(ciZ), Long.valueOf(opg), Long.valueOf(opd), Long.valueOf(ope), Long.valueOf(opf), Long.valueOf(oph), Long.valueOf(opi), Long.valueOf(opj)}); long j = (long) sensorEvent.values[0]; opc = j; if (j >= 0) { long currentTimeMillis = System.currentTimeMillis(); long j2 = sensorEvent.timestamp; if (opg != ciZ) { x.i("MicroMsg.Sport.SportStepDetector", "new day beginOfToday: %s saveTodayTime: %s, ", new Object[]{n.bx(10000 * ciZ), n.bx(opg * 10000)}); i.N(202, ciZ); i.N(201, 0); i.N(204, currentTimeMillis); i.N(209, sensorEvent.timestamp); i.N(203, (long) ((int) opc)); opd = opc; ope = 0; opf = 0; opg = ciZ; oph = currentTimeMillis; opi = currentTimeMillis; opj = j2; return; } Object obj; boolean z; j = 0; long j3 = ((currentTimeMillis - opi) / 300000) + ((long) ((currentTimeMillis - opi) % 300000 > 0 ? 1 : 0)); long j4 = (((j2 / 1000000) - (opj / 1000000)) / 300000) + ((long) (((j2 / 1000000) - (opj / 1000000)) % 300000 > 0 ? 1 : 0)); x.i("MicroMsg.Sport.SportStepDetector", "timesOf5Minute(%d, %d). rebootTime: %d %s", new Object[]{Long.valueOf(j4), Long.valueOf(j3), Long.valueOf(i.xS(205)), n.bx(i.xS(205))}); boolean z2 = false; str = ""; if (i.xS(205) > oph) { long j5 = opc - opf; if (j5 <= 0 || (j5 >= ((long) optInt) * j4 && j5 >= ((long) optInt) * j3)) { ciZ = 0; } else { str = "rebootIncrease Valid Step diffStep > 0"; ciZ = j5; } if (j5 < 0 && (opc < ((long) optInt) * j4 || opc < ((long) optInt) * j3)) { ciZ = opc; str = "rebootIncrease Valid Step diffStep < 0"; } i.N(205, 0); j = ciZ; obj = str; z = true; } else { if (opc < opd) { x.i("MicroMsg.Sport.SportStepDetector", "invalid currentSensorStep %d preSensorStep %d lastSaveSensorStep %d", new Object[]{Long.valueOf(opc), Long.valueOf(opd), Long.valueOf(opf)}); ciZ = opc; opd = ciZ; opf = ciZ; z2 = true; } String obj2; if (opc - opd < j4 * ((long) optInt) || opc - opd < j3 * ((long) optInt)) { j = opc - opd; obj2 = "normalIncrease Valid Step"; z = z2; } else { obj2 = str; z = z2; } } x.i("MicroMsg.Sport.SportStepDetector", "increase step %s %d %b", new Object[]{obj2, Long.valueOf(j), Boolean.valueOf(z)}); ope += j; if (currentTimeMillis - oph > ((long) bFJ.optInt("stepCounterSaveInterval", 60000)) || opc - opf > ((long) bFJ.optInt("stepCounterSaveStep")) || z) { i.N(201, ope); i.N(203, opc); i.N(204, currentTimeMillis); i.N(209, j2); x.i("MicroMsg.Sport.SportStepDetector", "save to [file] currentTodayStep %d lastSaveSensorStep %d preSysStepTime %d lastSaveStepTime %d preSensorNanoTime %d", new Object[]{Long.valueOf(ope), Long.valueOf(opf), Long.valueOf(opi), Long.valueOf(oph), Long.valueOf(opj)}); oph = currentTimeMillis; opf = opc; } else { x.i("MicroMsg.Sport.SportStepDetector", "save to cache currentTodayStep %d preSysStepTime %d lastSaveStepTime %d preSensorNanoTime %d", new Object[]{Long.valueOf(ope), Long.valueOf(opi), Long.valueOf(oph), Long.valueOf(opj)}); } opd = opc; opi = currentTimeMillis; opj = j2; } } else if (sensorEvent == null || sensorEvent.values == null) { String str2 = "MicroMsg.Sport.SportStepDetector"; str = "[Willen][Step] SensorEvent Exception. event==null:%s , event.values==null:%s"; Object[] objArr = new Object[2]; objArr[0] = Boolean.valueOf(sensorEvent == null); objArr[1] = Boolean.valueOf(sensorEvent != null); x.e(str2, str, objArr); } else { x.e("MicroMsg.Sport.SportStepDetector", "[Willen][Step] SensorEvent Exception accuracy: %d, timestamp: %s", new Object[]{Integer.valueOf(sensorEvent.accuracy), Long.valueOf(sensorEvent.timestamp)}); int i = 0; float[] fArr = sensorEvent.values; int length = fArr.length; int i2 = 0; while (i2 < length) { float f = fArr[i2]; r10 = new Object[2]; int i3 = i + 1; r10[0] = Integer.valueOf(i); r10[1] = Float.valueOf(f); x.e("MicroMsg.Sport.SportStepDetector", "[Willen][Step] SensorEvent Exception event[%d]: %f", r10); i2++; i = i3; } } } public final void onAccuracyChanged(Sensor sensor, int i) { } }
package org.jvnet.jaxb2_commons.xml.bind.model; import javax.xml.namespace.QName; public interface MElementTypeInfo<T, C extends T> extends MTyped<T, C>, MNillable, MDefaultValue { public QName getElementName(); }
package com.sdc.flashcare; import android.Manifest; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { // String response = ""; String attachmentName = "filename"; String crlf = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; String filename = ""; String filepath = ""; String Response =""; static LocationRequest locationRequest; static GoogleApiClient googleApiClient; double lat, lon; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPreferences = getSharedPreferences("Flash", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); editor.putInt("LOGGED_IN", 1); editor.apply(); connectToGoogleApi(); } public void enableBroadcastReceiver() { startService(new Intent(MainActivity.this,MyService.class)); ComponentName receiver = new ComponentName(this, receiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show(); } public void disableBroadcastReceiver() { stopService(new Intent(MainActivity.this,MyService.class)); ComponentName receiver = new ComponentName(this, receiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show(); } public void connectToGoogleApi() { if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) { googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) { googleApiClient.connect(); Log.d("TAG", "connect"); } } else { Log.e("TAG", "unable to connect to google play services."); } } @Override public void onConnected(Bundle bundle) { Log.d("TAG", "connected"); locationRequest = LocationRequest.create(); locationRequest.setInterval(1000); // milliseconds locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 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; } LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest, new LocationListener() { @Override public void onLocationChanged(Location location) { lat = location.getLatitude(); lon = location.getLongitude(); } }); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } public void drive(View view) { if (sharedPreferences.getString("drive", "no").equals("no")) { enableBroadcastReceiver(); editor.putString("drive", "yes"); } else { disableBroadcastReceiver(); editor.putString("drive", "no"); } editor.apply(); } public void picture(View view) { Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, 10); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 10) { if (resultCode == RESULT_OK) { Uri videoUri = data.getData(); filepath = getRealPathFromURI(videoUri); Log.d("testing", filepath); new alertPic().execute(); } } } public String getRealPathFromURI(Uri contentUri) { String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } public class alertPic extends AsyncTask<Void, Void, Void> { ProgressDialog progressDialog; @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); progressDialog.dismiss(); } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(MainActivity.this, "", "Uploading. Please wait...", true); progressDialog.setCancelable(true); } @Override protected Void doInBackground(Void... params) { URL url; try { // HttpURLConnection httpUrlConnection; // URL url = new URL("http://204.152.203.111/ec/upload.php"); // httpUrlConnection = (HttpURLConnection) url.openConnection(); // httpUrlConnection.setUseCaches(false); // httpUrlConnection.setInstanceFollowRedirects(false); // httpUrlConnection.setDoOutput(true); // httpUrlConnection.setDoInput(true); // // httpUrlConnection.setRequestMethod("POST"); // httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); // httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); // httpUrlConnection.setRequestProperty( // "Content-Type", "multipart/form-data;boundary=" + boundary); // // FileInputStream fileInputStream = new FileInputStream(f); // // DataOutputStream request = new DataOutputStream( // httpUrlConnection.getOutputStream()); // // request.writeBytes(twoHyphens + boundary + crlf); //// request.writeBytes("Content-Disposition: form-data; name=\"" + //// "lat\";"+ crlf); //// request.writeBytes(crlf); //// request.writeBytes(""+lat); //// request.writeBytes(crlf); //// request.writeBytes(twoHyphens + boundary + crlf); //// request.writeBytes("Content-Disposition: form-data; name=\"" + //// "long\";"+ crlf); //// request.writeBytes(crlf); //// request.writeBytes(""+lon); //// request.writeBytes(crlf); // request.writeBytes("Content-Disposition: form-data; name=\"" // + "filename" + "\";filename=\"" // + filename + "\"" + crlf); // // Log.d("values", "lat " + lat + " lng " + lon); // // byte[] pixels; // pixels = new byte[Math.min((int) f.length(), 20 * 1024)]; // // int length; // while ((length = fileInputStream.read(pixels)) != -1) { // request.write(pixels, 0, length); // } // // request.write(pixels); // // request.writeBytes(crlf); // request.writeBytes(twoHyphens + boundary + // twoHyphens + crlf); // // request.flush(); // request.close(); // // fileInputStream.close(); // Log.d("responsecode", "" + httpUrlConnection.getResponseCode()); // // DataInputStream dis = new DataInputStream(httpUrlConnection.getInputStream()); // StringBuilder response = new StringBuilder(); File f = new File(filepath); FileInputStream fileInputStream = new FileInputStream(f); byte[] pixels; pixels = new byte[Math.min((int) f.length(), 20 * 1024)]; // pixels = new byte[(int) f.length()]; int length; // String value = "data:image/jpeg;base64,"; String value = ""; // fileInputStream.read(pixels,0,(int)f.length()); while ((length = fileInputStream.read(pixels)) != -1) { // value += Base64.encodeToString(pixels,Base64.DEFAULT); } value = Base64.encodeToString(pixels,Base64.DEFAULT); Log.d("base64",value); url = new URL("http://204.152.203.111/ec/upload.php"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); Uri.Builder builder = new Uri.Builder(); builder.appendQueryParameter("lat",lat+""); builder.appendQueryParameter("long",lon+""); builder.appendQueryParameter("img",value); builder.appendQueryParameter("isimage","1"); String query = builder.build().getEncodedQuery(); OutputStream os = httpURLConnection.getOutputStream(); BufferedWriter mBufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); mBufferedWriter.write(query); mBufferedWriter.flush(); mBufferedWriter.close(); os.close(); httpURLConnection.connect(); BufferedReader mBufferedInputStream = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String inline; while ((inline = mBufferedInputStream.readLine()) != null) { Response += inline; } mBufferedInputStream.close(); Log.d("Response", Response); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
/* * 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 principal.base.entidades.usuarios; public abstract class Usuario { protected long id; protected String nombre; protected String apellido; protected String telefono; protected String email; protected String clave; protected String gcm; protected byte[] imagen; public Usuario() { } public Usuario(String email, String clave) { this.email = email; this.clave = clave; } public Usuario(String nombre, String apellido, String telefono, String email, String clave, byte[] imagen, String gcm) { this.nombre = nombre; this.apellido = apellido; this.telefono = telefono; this.email = email; this.imagen = imagen; this.clave = clave; this.gcm = gcm; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public byte[] getImagen() { return imagen; } public void setImagen(byte[] imagen) { this.imagen = imagen; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public String getGcm() { return gcm; } public void setGcm(String gcm) { this.gcm = gcm; } }
package Presentacion; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import Dominio.Gestor_Borrar_Cliente; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Formulario_Borrar_Cliente { public JFrame frame; private JTextField txtDNI; private Gestor_Borrar_Cliente gestor; private JFrame padre; public Formulario_Borrar_Cliente(JFrame padre) { this.padre = padre; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { gestor = new Gestor_Borrar_Cliente(); frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); frame.getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); JLabel lblDNI = new JLabel("DNI:"); lblDNI.setBounds(108, 93, 56, 16); panel.add(lblDNI); txtDNI = new JTextField(); txtDNI.setBounds(176, 90, 116, 22); panel.add(txtDNI); txtDNI.setColumns(10); JButton btnBorrarCliente = new JButton("Borrar Cliente"); btnBorrarCliente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String dni = txtDNI.getText(); try { gestor.borrar_cliente(dni); padre.setVisible(true); frame.dispose(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnBorrarCliente.setBounds(166, 147, 126, 25); panel.add(btnBorrarCliente); } }
package com.example.postgresdemo.injections; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import org.springframework.beans.factory.serviceloader.ServiceListFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.SpringFactoriesLoader; //@Configuration public class MyConfiguration { @Bean public ServiceListFactoryBean serviceFactory() { ServiceListFactoryBean serviceListFactoryBean = new ServiceListFactoryBean(); serviceListFactoryBean.setServiceType(Foo.class); ServiceLoader<Foo> loader = ServiceLoader.load(Foo.class); loader.iterator(); List<Foo> foos = SpringFactoriesLoader.loadFactories(Foo.class, null); for (Foo foo : foos) { System.out.println(foo.execute()); } return serviceListFactoryBean; } }
package com.example.demo.security.controller; import com.alibaba.fastjson.JSONObject; import com.example.demo.common.JsonResult; import com.example.demo.security.model.Authority; import com.example.demo.security.model.Resource; import com.example.demo.security.model.User; import com.example.demo.security.JwtAuthenticationRequest; import com.example.demo.security.JwtTokenUtil; import com.example.demo.security.JwtUser; import com.example.demo.security.repository.AuthorityRepository; import com.example.demo.security.repository.UserRepository; import com.example.demo.security.service.JwtAuthenticationResponse; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.mobile.device.Device; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.*; @RestController public class AuthenticationRestController { @Value("${jwt.header}") private String tokenHeader; @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @ApiOperation(value = "登录", notes = "") @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户名", dataType = "int", required = true, paramType = "form"), @ApiImplicitParam(name = "password", value = "密码", dataType = "int", required = true, paramType = "form"), }) @RequestMapping(value = "/auth", method = RequestMethod.POST) public JSONObject createAuthenticationToken(@RequestParam String username, @RequestParam String password, Device device) throws AuthenticationException { // Perform the security final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(username, password) ); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(username); final String token = jwtTokenUtil.generateToken(userDetails, device); Map<String, Object> result = new HashMap<>(); result.put("token", token); result.put("user", userDetails); JwtUser jwtUser = (JwtUser) userDetails; User user = userRepository.findByUsername(jwtUser.getUsername()); List<Authority> authorityList = user.getAuthorities(); Set<Resource> r = new HashSet<>(); authorityList.forEach(authority -> { List<Resource> resources = authority.getResources(); r.addAll(resources); }); result.put("resources", r); // Return the token return JsonResult.success(result); } @RequestMapping(value = "/refresh", method = RequestMethod.GET) public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) { String token = request.getHeader(tokenHeader); String username = jwtTokenUtil.getUsernameFromToken(token); JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) { String refreshedToken = jwtTokenUtil.refreshToken(token); return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken)); } else { return ResponseEntity.badRequest().body(null); } } @RequestMapping(value = "/register", method = RequestMethod.GET) public JSONObject login(HttpServletRequest request) { String userName = "wwy121"; String password = "123456"; User user = new User(); user.setUsername(userName); user.setPassword(new BCryptPasswordEncoder().encode(password)); user.setFirstname("wang"); user.setLastname("weiye"); user.setEmail("wwyknight@163.com"); user.setEnabled(true); user.setLastPasswordResetDate(new Date()); Authority authority = authorityRepository.findOne(1L); user.setAuthorities(Arrays.asList(authority)); userRepository.save(user); return JsonResult.success("注册成功", null); } }
package com.shopify.admin.seller; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.shopify.admin.AdminData; import com.shopify.admin.price.PriceData; import com.shopify.api.ShopifyOutApiDataCarrier; import com.shopify.common.SpConstants; import com.shopify.common.util.UtilFunc; /** * 관리자 > Seller Controller * @author : jwh * @since : 2020-01-21 * @desc : Seller 정보 관리 */ @Controller public class AdminSellerController { private Logger LOGGER = LoggerFactory.getLogger(AdminSellerController.class); @Autowired private AdminSellerService sellerService; /** * 관리자 > 셀러 관리 > 리스트 * @return */ @SuppressWarnings("null") @GetMapping(value = "/admin/seller/list") public String adminSeller (Model model, AdminSellerData setting, HttpSession sess , @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage , @RequestParam(value = "searchRankId", required = false, defaultValue = "") String searchRankId , @RequestParam(value = "searchType", required = false, defaultValue = "shopId") String searchType , @RequestParam(value = "searchWord", required = false, defaultValue = "") String searchWord , @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize ) { setting.setCurrentPage(currentPage); setting.setSearchRankId(searchRankId); setting.setSearchType(searchType); setting.setSearchWord(searchWord); setting.setPageSize(pageSize); Map<String, Object> map = sellerService.selectAdminSeller(setting, sess); model.addAttribute("search", setting); model.addAttribute("list", map.get("list")); model.addAttribute("paging", map.get("paging")); return "/admin/seller/admSellerList"; } @GetMapping(value = "/admin/seller/discount") public String adminSellerDiscount(Model model, PriceData priceData, HttpSession sess , @RequestParam(value = "searchType", required = false, defaultValue = "shopId") String searchType , @RequestParam(value = "searchWord", required = false, defaultValue = "") String searchWord ) { AdminData sd = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); priceData.setLocale(sd.getLocale()); // 검색조건 String zoneCodeId = priceData.getZoneCodeId(); if ( zoneCodeId == null ) { zoneCodeId = ""; } String zoneCodeGroup = priceData.getZoneCodeGroup(); if ( zoneCodeGroup == null ) { zoneCodeGroup = ""; } // 검색일자 생성 String nowDate = priceData.getNowDate(); if(nowDate == null || "".equals(nowDate)) { nowDate = UtilFunc.today(); priceData.setNowDate(nowDate); } Map<String, Object> map = sellerService.selectSellerDiscount(priceData); model.addAttribute("courierList", map.get("courierList") ); model.addAttribute("sellerDiscountList", map.get("sellerDiscountList") ); model.addAttribute("nowDate", nowDate); model.addAttribute("partShipCompany", zoneCodeId); model.addAttribute("partDeliveryService", zoneCodeGroup); return "/admin/seller/admSellerDiscount"; } @GetMapping(value = "/admin/seller/discountExcel") public String adminSellerDiscountExcel(Model model, PriceData priceData, HttpSession sess, HttpServletResponse response) { AdminData sd = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); priceData.setLocale(sd.getLocale()); // 검색조건 String zoneCodeId = priceData.getZoneCodeId(); if ( zoneCodeId == null ) { zoneCodeId = ""; } String zoneCodeGroup = priceData.getZoneCodeGroup(); if ( zoneCodeGroup == null ) { zoneCodeGroup = ""; } // 검색일자 생성 String nowDate = priceData.getNowDate(); if(nowDate == null || "".equals(nowDate)) { nowDate = UtilFunc.today(); priceData.setNowDate(nowDate); } Map<String, Object> map = sellerService.selectSellerDiscount(priceData); model.addAttribute("courierList", map.get("courierList") ); model.addAttribute("sellerDiscountList", map.get("sellerDiscountList") ); model.addAttribute("nowDate", nowDate); model.addAttribute("partShipCompany", zoneCodeId); model.addAttribute("partDeliveryService", zoneCodeGroup); UtilFunc.setExcelResponse(response, "셀러별할인율"); return "/admin/seller/admSellerDiscountExcel"; } /** * 관리자 > 셀러 관리 > 셀러 검색 화면 * @return */ @GetMapping(value = {"/admin/seller/sellerSearch", "/admin/statis/sellerSearch", "/admin/common/sellerSearch"}) public String adminSellerSearch (Model model, @ModelAttribute AdminSellerData setting, HttpSession sess) { model.addAttribute("search", setting); return "/admin/seller/admSellerSearch"; } /** * 관리자 > 셀러 관리 > 셀러 검색 리스트 * @return */ @PostMapping(value = {"/admin/seller/sellerSearchProc", "/admin/statis/sellerSearchProc", "/admin/common/sellerSearchProc"}) public ModelAndView adminSellerSearchList (Model model, @RequestBody AdminSellerData setting, HttpSession sess) { ModelAndView mv = new ModelAndView("jsonView"); int currentPage = setting.getCurrentPage(); int pageSize = setting.getPageSize(); if(currentPage == 0) currentPage = 1; if(pageSize == 0) pageSize = 500; setting.setSearchType("total"); setting.setCurrentPage(currentPage); setting.setPageSize(pageSize); Map<String, Object> map = sellerService.selectAdminSeller(setting, sess); model.addAttribute("search", setting); model.addAttribute("list", map.get("list")); model.addAttribute("paging", map.get("paging")); mv.addObject("search", setting); mv.addObject("list", map.get("list")); mv.addObject("paging", map.get("paging")); mv.addObject("errCode", true); mv.addObject("errMsg", "성공"); return mv; } /** * 관리자 > 셀러 관리 > 상세보기 * @return */ @GetMapping(value = "/admin/seller/viewSeller") public String seller(Model model, AdminSellerData setting, AdminShopData settingShop, HttpSession sess , @RequestParam(value = "email", required = false, defaultValue = "") String email , @RequestParam(value = "currentPage", required = false, defaultValue = "") int currentPage , @RequestParam(value = "searchRankId", required = false, defaultValue = "") String searchRankId , @RequestParam(value = "searchType", required = false, defaultValue = "") String searchType , @RequestParam(value = "searchWord", required = false, defaultValue = "") String searchWord , @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize ) { setting.setEmail(email); setting.setCurrentPage(currentPage); setting.setSearchRankId(searchRankId); setting.setSearchType(searchType); setting.setSearchWord(searchWord); setting.setPageSize(pageSize); settingShop.setEmail(email); List<AdminShopData> list = sellerService.selectAdminShop(settingShop, sess); AdminSellerData seller = sellerService.selectAdminSellerDetail(setting, sess); model.addAttribute("search", setting); model.addAttribute("seller", seller); model.addAttribute("list", list); // seller 별 할인율 가져오기 PriceData priceData = new PriceData(); AdminData sd = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); priceData.setLocale(sd.getLocale()); priceData.setNowDate(UtilFunc.today()); priceData.setEmail(email); Map<String, Object> map = sellerService.selectSellerDiscountFullList(priceData, seller); model.addAttribute("nowDate", UtilFunc.today() ); model.addAttribute("courierList", map.get("courierList") ); model.addAttribute("sellerDiscount", map.get("sellerDiscount") ); model.addAttribute("discountListSize", map.get("discountListSize") ); model.addAttribute("discountHistory", map.get("discountHistory") ); return "/admin/seller/admSellerView"; } /** * 관리자 > 셀러 관리 > 등급 update * @param model * @return */ @PostMapping(value = "/admin/seller/updateSellerDiscount") public ModelAndView updateSellerDiscount(Model model, @RequestBody SellerDiscountDateData setting, HttpSession sess) throws Exception { ModelAndView mv = new ModelAndView("jsonView"); String result = sellerService.updateSellerDiscount(setting); // mv.addObject("result", result); if ( result == null ) { mv.addObject("errCode", true); mv.addObject("errMsg", "성공"); } else { mv.addObject("errCode", false); mv.addObject("errMsg", result); } return mv; } /** * 관리자 > 셀러 관리 > 상세보기 * @return */ @GetMapping(value = "/admin/popup/seller/popSellerRankLog") public String popSellerRankLog(Model model, @ModelAttribute AdminSellerData setting, HttpSession sess) { List<AdminSellerData> list = sellerService.selectSellerRankLog(setting); model.addAttribute("list", list); return "/admin/popup/popSellerRankLog"; } /** * 관리자 > 셀러 관리 > 판매 쇼핑몰 결제상태 수정 * @param model * @return */ @PostMapping(value = "/admin/seller/updateShopBilling") public ModelAndView updateShopBilling(@RequestBody AdminShopData setting, HttpSession sess) throws Exception { ModelAndView mv = new ModelAndView("jsonView"); int result = sellerService.updateShopBilling(setting, sess); //mv.addObject("procCode", "button.edit"); mv.addObject("billingYn", setting.getBillingYn()); mv.addObject("result", result); mv.addObject("errCode", true); mv.addObject("errMsg", "성공"); return mv; } /** * 관리자 > 셀러 관리 > 셀러 계약 상태 업데이트 * @param model * @return */ @PostMapping(value = "/admin/seller/updateActive") public ModelAndView updateActive(@RequestBody AdminShopData setting, HttpSession sess) throws Exception { ModelAndView mv = new ModelAndView("jsonView"); int result = sellerService.updateActive(setting, sess); //mv.addObject("procCode", "button.edit"); mv.addObject("activeYn", setting.getActiveYn()); mv.addObject("result", result); mv.addObject("errCode", true); mv.addObject("errMsg", "성공"); return mv; } }
/** * Copyright 2009 Jens Dietrich 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 test.nz.org.take.mvel2; /** * Simple bean for testing. * @author Jens Dietrich */ public class Person { private String name = null; private boolean male = false; public boolean isMale() { return male; } public void setMale(boolean male) { this.male = male; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package Library.Management.dto; import java.io.Serializable; import java.util.List; import Library.Management.domain.Book; public class BookListDto implements Serializable{ private List<Book> books; public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
/* * 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 gerenciador.aula; import gerenciador.conexaoBD.AulaDao; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import static jdk.nashorn.internal.runtime.JSType.isNumber; /** * * @author Raiane */ public class AlteraAulaGUI extends javax.swing.JFrame { private final Aula aula = new Aula(); private final AulaDao con = new AulaDao(); public AlteraAulaGUI() { initComponents(); } private void setLambel() { edtNome.setText(aula.getNome()); edtCodigo.setText("" + aula.getId()); edtValor.setText(("R$ " + aula.getValor()).replace(".", ",")); } /** * 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() { pnlPrincipal = new javax.swing.JPanel(); lblNome = new javax.swing.JLabel(); lblValor = new javax.swing.JLabel(); lblCodigo = new javax.swing.JLabel(); edtCodigo = new javax.swing.JTextField(); edtNome = new javax.swing.JTextField(); edtValor = new javax.swing.JTextField(); pnlBotoes = new javax.swing.JPanel(); boVolta = new javax.swing.JButton(); boAltera = new javax.swing.JButton(); boConfirma = new javax.swing.JButton(); boHome = new javax.swing.JButton(); boNext = new javax.swing.JButton(); btnPesquisar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Pesquisar Autor"); setLocation(new java.awt.Point(300, 200)); setUndecorated(true); setResizable(false); setSize(new java.awt.Dimension(406, 367)); pnlPrincipal.setBackground(new java.awt.Color(102, 102, 102)); pnlPrincipal.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorAdded(javax.swing.event.AncestorEvent evt) { pnlPrincipalAncestorAdded(evt); } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); lblNome.setForeground(new java.awt.Color(51, 255, 0)); lblNome.setText("Nome:"); lblValor.setForeground(new java.awt.Color(51, 255, 0)); lblValor.setText("Valor:"); lblCodigo.setForeground(new java.awt.Color(51, 255, 0)); lblCodigo.setText("Codigo:"); pnlBotoes.setBackground(new java.awt.Color(102, 102, 102)); pnlBotoes.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 153, 0))); boVolta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Icones/055.png"))); // NOI18N boVolta.setToolTipText(""); boVolta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boVoltaActionPerformed(evt); } }); boAltera.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Botoes/pen.png"))); // NOI18N boAltera.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boAlteraActionPerformed(evt); } }); boConfirma.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Icones/023.png"))); // NOI18N boConfirma.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boConfirmaActionPerformed(evt); } }); boHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Icones/046.png"))); // NOI18N boHome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boHomeActionPerformed(evt); } }); boNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Icones/056.png"))); // NOI18N boNext.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boNextActionPerformed(evt); } }); javax.swing.GroupLayout pnlBotoesLayout = new javax.swing.GroupLayout(pnlBotoes); pnlBotoes.setLayout(pnlBotoesLayout); pnlBotoesLayout.setHorizontalGroup( pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBotoesLayout.createSequentialGroup() .addContainerGap() .addComponent(boVolta) .addGap(18, 18, 18) .addComponent(boAltera) .addGap(18, 18, 18) .addComponent(boConfirma) .addGap(18, 18, 18) .addComponent(boHome) .addGap(18, 18, 18) .addComponent(boNext) .addContainerGap(21, Short.MAX_VALUE)) ); pnlBotoesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {boAltera, boVolta}); pnlBotoesLayout.setVerticalGroup( pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBotoesLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(boVolta) .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(boAltera) .addComponent(boConfirma) .addComponent(boHome) .addComponent(boNext))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnlBotoesLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {boAltera, boVolta}); btnPesquisar.setBackground(new java.awt.Color(0, 153, 0)); btnPesquisar.setForeground(new java.awt.Color(255, 255, 255)); btnPesquisar.setText("Pesquisar"); btnPesquisar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnPesquisarMouseClicked(evt); } }); javax.swing.GroupLayout pnlPrincipalLayout = new javax.swing.GroupLayout(pnlPrincipal); pnlPrincipal.setLayout(pnlPrincipalLayout); pnlPrincipalLayout.setHorizontalGroup( pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCodigo) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addComponent(edtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnPesquisar)) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addGroup(pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblNome, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(edtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblValor, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(edtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlPrincipalLayout.createSequentialGroup() .addContainerGap(25, Short.MAX_VALUE) .addComponent(pnlBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); pnlPrincipalLayout.setVerticalGroup( pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addGap(41, 41, 41) .addComponent(lblCodigo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(edtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnPesquisar)) .addGap(8, 8, 8) .addGroup(pnlPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addComponent(lblNome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(pnlPrincipalLayout.createSequentialGroup() .addComponent(lblValor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(42, 42, 42) .addComponent(pnlBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void pnlPrincipalAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_pnlPrincipalAncestorAdded edtNome.setFocusable(true); edtValor.setEditable(false); boAltera.setEnabled(false); boNext.setEnabled(false); boVolta.setEnabled(false); boConfirma.setEnabled(false); }//GEN-LAST:event_pnlPrincipalAncestorAdded private void boAlteraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boAlteraActionPerformed edtValor.setEditable(true); edtNome.setEditable(true); boConfirma.setEnabled(true); }//GEN-LAST:event_boAlteraActionPerformed private void boConfirmaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boConfirmaActionPerformed try { aula.setNome(edtNome.getText()); aula.setValor(Float.parseFloat((edtValor.getText().replace(",", ".")).replace("R$ ", ""))); con.updateAula(aula); dispose(); } catch (SQLException ex) { Logger.getLogger(AlteraAulaGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_boConfirmaActionPerformed private void boHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boHomeActionPerformed dispose(); }//GEN-LAST:event_boHomeActionPerformed private void boNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boNextActionPerformed try { con.consultaNext(aula); setLambel(); } catch (SQLException ex) { dispose(); } }//GEN-LAST:event_boNextActionPerformed private void boVoltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boVoltaActionPerformed try { con.consultaLast(aula); setLambel(); } catch (SQLException ex) { dispose(); } }//GEN-LAST:event_boVoltaActionPerformed private void btnPesquisarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPesquisarMouseClicked if (!edtCodigo.getText().equals("")) { if (isNumber(edtCodigo.getText())) { boAltera.setEnabled(true); boNext.setEnabled(true); boVolta.setEnabled(true); edtCodigo.setEditable(false); edtNome.setEditable(false); btnPesquisar.setEnabled(false); try { int id = Integer.parseInt(edtCodigo.getText()); con.consultaID(aula, id); setLambel(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro na execução:" + ex); edtCodigo.setText(""); System.exit(0); } } else { edtCodigo.setText(""); JOptionPane.showMessageDialog(null, "Aula nâo Cadastrada!"); } } else if (!edtNome.getText().equals("")) { boAltera.setEnabled(true); boNext.setEnabled(true); boVolta.setEnabled(true); edtCodigo.setEditable(false); edtNome.setEditable(false); btnPesquisar.setEnabled(false); con.consultaNome(edtNome.getText(), aula); setLambel(); } else { JOptionPane.showMessageDialog(null, "Insira um Argumento Valido!"); edtCodigo.setText(""); } }//GEN-LAST:event_btnPesquisarMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AlteraAulaGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boAltera; private javax.swing.JButton boConfirma; private javax.swing.JButton boHome; private javax.swing.JButton boNext; private javax.swing.JButton boVolta; private javax.swing.JButton btnPesquisar; private javax.swing.JTextField edtCodigo; private javax.swing.JTextField edtNome; private javax.swing.JTextField edtValor; private javax.swing.JLabel lblCodigo; private javax.swing.JLabel lblNome; private javax.swing.JLabel lblValor; private javax.swing.JPanel pnlBotoes; private javax.swing.JPanel pnlPrincipal; // End of variables declaration//GEN-END:variables }
package com.xjf.wemall.service.crazyjavachapter18.part4; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; import com.xjf.wemall.api.util.DateUtil; public class Test { private Map<String , Integer> score; public static void main(String[] arg) throws Exception { Class<?> clazz = Class.forName("com.xjf.wemall.api.util.DateUtil"); // 反射 静态方法 无变量 System.out.println(clazz.getMethod("getCurrentDateTime", null).invoke(null, null)); // 反射 静态方法 有变量 System.out.println(clazz.getMethod("parseTimeFlag", String.class).invoke(clazz, "1")); // 反射 静态变量 System.out.println(clazz.getField("FORMAT_DATETIME_YYYYMMDDHHMMSSSSS").get(clazz)); // 反射 对象方法 DateUtil ts = (DateUtil)clazz.newInstance(); System.out.println(ts.getCurrentDateTimeNow()); Class<?> cs = Class.forName("com.xjf.wemall.service.crazyjavachapter18.part4.Test"); Field fd = cs.getDeclaredField("score"); Class<?> cs2 = fd.getType(); System.out.println(cs2); // 获得成员变量f的泛型类型 Type gtype = fd.getGenericType(); if(gtype instanceof ParameterizedType) { // 强制类型转换 ParameterizedType tp = (ParameterizedType) gtype; // 获取原始类型 Type rType = tp.getRawType(); System.out.println("原始类型是:" + rType); // 取得泛型类型的泛型参数 Type[] tArgs = tp.getActualTypeArguments(); System.out.println("泛型信息是:"); for (int i = 0; i < tArgs.length; i++) { System.out.println("第" + i + "个泛型类型是:" + tArgs[i]); } } } }
import java.util.LinkedList; public class LinkedListTest { public static void main(String[] agrs) { LinkedList<String> list = new LinkedList<String>(); list.add("A"); list.add("B"); list.add("C"); System.out.println(list); list.add(1, "D"); System.out.println(list); list.removeFirst(); System.out.println(list); for(int i = 0; i < list.size(); i++) { String str = list.get(i); System.out.println(str); } } }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.junit.BeforeClass; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import models.Presentation; import org.apache.commons.lang3.tuple.ImmutablePair; import org.joda.time.DateTime; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import play.Logger; import play.mvc.Result; import javax.persistence.Table; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import static junitparams.JUnitParamsRunner.$; import static org.junit.Assert.assertEquals; import static play.test.Helpers.*; @RunWith(JUnitParamsRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PresentationTest extends BaseTest { public static final String GET_ALL_PRESENTATION_URL = "/getAllPresentation"; public static final String GET_PRESENTATION_URL = "/getPresentation/%d"; public static final String GET_PRESENTATIONS_UPDATED_AFTER_URL = "/getPresentationsUpdatedAfter/%d"; private static final String PRESENTATION_TABLE_NAME = Presentation.class.getAnnotation(Table.class).name(); private static final ImmutableList<Presentation> PRESENTATIONS_FOR_TEST = PresentationTestDataProvider.TEST_PRESENTATIONS; private static final ImmutableList<Presentation> MANY_PRESENTATIONS_FOR_TEST = PresentationTestDataProvider.MANY_TEST_PRESENTATION; private static final Logger.ALogger LOGGER = Logger.of(PresentationTest.class); @BeforeClass public static void beforeClass() { deleteAllTestData(PRESENTATION_TABLE_NAME); } //TODO unaccessible database testcase @SuppressWarnings("unused") private List<String> parametersForTest11WithEmptyDatabase() { return Lists.newArrayList( GET_ALL_PRESENTATION_URL , String.format(GET_PRESENTATION_URL, 1) , String.format(GET_PRESENTATIONS_UPDATED_AFTER_URL, 0) ); } @Test @Parameters public void test11WithEmptyDatabase(String url) { LOGGER.info(String.format("Starting test11: empty database with %s", url)); getAndAssertEmptyResult(url); } @Test @Parameters(method = "parametersForTest11WithEmptyDatabase") public void test12OneRecord(String url) throws IOException { LOGGER.info(String.format("Staring test12: one record with %s", url)); Presentation expected = PRESENTATIONS_FOR_TEST.get(0); save(Lists.newArrayList(expected)); getAndCheckResultAndAssertPresentations(url, expected); } @SuppressWarnings("unused") private List<Long> parametersForTest13OneUpdatedAfterOneRecordTimestamp() { return Lists.newArrayList( 1000L , 0L ); } @Test @Parameters public void test13OneUpdatedAfterOneRecordTimestamp(Long offset) throws IOException { LOGGER.info(String.format("Starting test13: Updated after controller timestamp before: %s millisec", offset)); Presentation expected = PRESENTATIONS_FOR_TEST.get(0); save(Lists.newArrayList(expected)); Long after = expected.lastModified.getTime() / 1000 * 1000 - offset; String url = String.format(GET_PRESENTATIONS_UPDATED_AFTER_URL, after); getAndCheckResultAndAssertPresentations(url, expected); } @Test public void test14UpdatedAfterOneRecordTimestampAfter() throws IOException { LOGGER.info("Starting test14: Updated after controller timestamp after"); Long after = PRESENTATIONS_FOR_TEST.get(0).lastModified.getTime() / 1000 * 1000 + 1000; String url = String.format(GET_PRESENTATIONS_UPDATED_AFTER_URL, after); getAndAssertEmptyResult(url); } @SuppressWarnings("unused") private List<String> parametersForTest15SameDueDate() { return Lists.newArrayList( GET_ALL_PRESENTATION_URL , String.format(GET_PRESENTATIONS_UPDATED_AFTER_URL, 0) ); } @Test @Parameters public void test15SameDueDate(String url) throws IOException { LOGGER.info(String.format("Startint test15: Same dueDate with %s", url)); List<Presentation> expected = Lists.newArrayList(PRESENTATIONS_FOR_TEST.get(0), PRESENTATIONS_FOR_TEST.get(1)); save(expected); getAndCheckResultAndAssertPresentationsList(url, expected); } @Test @Parameters(method = "parametersForTest15SameDueDate") public void test16PresentationWithRecors(String url) throws IOException { LOGGER.info(String.format("Starting test16: get presentation with records with %s", url)); List<Presentation> expected = PRESENTATIONS_FOR_TEST; save(expected); getAndCheckResultAndAssertPresentationsList(url, expected); } @SuppressWarnings("unused") private Object[] parametersForTest17GetPresentationWithRecords() { Object[] arr = new Object[PRESENTATIONS_FOR_TEST.size()]; Integer i = 0; while( i < PRESENTATIONS_FOR_TEST.size() ) { arr[i] = new ImmutablePair<>(i, ++i); } return arr; } @Test @Parameters public void test17GetPresentationWithRecords(ImmutablePair<Integer, Integer> pair) throws IOException { LOGGER.info(String.format("Starting test17: getPresentation with presentation: %d", pair.right)); Presentation expected = PRESENTATIONS_FOR_TEST.get(pair.left); String url = String.format(GET_PRESENTATION_URL, pair.right); getAndCheckResultAndAssertPresentations(url, expected); } @Test public void test18PresentationNotFound() { LOGGER.info("Starting test18: getPresentation with presentation not found with presented id"); getAndAssertEmptyResult(String.format(GET_PRESENTATION_URL, DaeiraTestTools.BIG_ID)); } @Test public void test19AfterControllerWithBigTimestamp() { LOGGER.info("Starting test19: AfterControllerWithBigTimestamp"); getAndAssertEmptyResult(String.format(GET_PRESENTATIONS_UPDATED_AFTER_URL, DaeiraTestTools.BIG_ID)); } @Test @Parameters(method = "parametersForTest15SameDueDate") public void test20ManyPresentationInDb(String url) throws IOException { LOGGER.info(String.format("Starting test20: Many presentation in db with %s", url)); List<Presentation> expected = MANY_PRESENTATIONS_FOR_TEST; save(expected); getAndCheckResultAndAssertPresentationsList(url, expected); } @SuppressWarnings("unused") private Object[] parametersForTest21ManyPresentationWithGetPresentation() { return $( $(new Random().nextInt(DaeiraTestTools.MANY_ELEMENT_IN_DATABASE)) , $(new Random().nextInt(DaeiraTestTools.MANY_ELEMENT_IN_DATABASE)) , $(new Random().nextInt(DaeiraTestTools.MANY_ELEMENT_IN_DATABASE)) ); } @Test @Parameters public void test21ManyPresentationWithGetPresentation(int id) throws IOException { int idForGet = id + 1; LOGGER.info(String.format("Starting test21: Many presentation with getPresentation random id: %d", idForGet)); Presentation expected = MANY_PRESENTATIONS_FOR_TEST.get(id); getAndCheckResultAndAssertPresentations(String.format(GET_PRESENTATION_URL, idForGet), expected); } private static void getAndCheckResultAndAssertPresentationsList(String url, List<Presentation> expected) throws IOException { Result r = getAndCheckResult(url); List<Presentation> actual = buildPresentationListFromResult(r); assertPresentationList(expected, actual); } private static void getAndCheckResultAndAssertPresentations(String url, Presentation expected) throws IOException { Result r = getAndCheckResult(url); List<Presentation> actual = buildPresentationListFromResult(r); assertPresentation(expected, actual); } private static void assertPresentationList(List<Presentation> expected, List<Presentation> actual) { List<Presentation> exp = Lists.newArrayList(expected); DaeiraTestTools.assertSizeEquals("asserting Presentation list", exp, actual); Collections.sort(exp); for (int i = 0; i < exp.size(); i++) { assertPresentation(exp.get(i), actual.get(i)); } } private static void assertPresentation(Presentation expected, Presentation actual) { assertEquals(String.format("Wrong presentation id, maybe a sorting issue"), expected.id, actual.id); assertEquals(expected.title, actual.title); assertEquals(expected.subject, actual.subject); assertEquals(expected.description, actual.description); assertEquals(expected.lenghtInMin, actual.lenghtInMin); DateTime d = new DateTime(expected.dueDate); Date expectedDate = d.minusMillis(d.getMillisOfSecond()).toDate(); assertEquals(expectedDate, actual.dueDate); assertEquals(expected.instructor, actual.instructor); assertEquals(expected.room, actual.room); } private static void assertPresentation(Presentation expected, List<Presentation> actual) { assertEquals(1, actual.size()); assertPresentation(expected, actual.get(0)); } private static List<Presentation> buildPresentationListFromResult(Result r) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(contentAsString(r), new TypeReference<List<Presentation>>() {}); } }
/** * */ /** * @author sameerkhurana10 * */ package VSMFeatureMatrices;
package com.facebook.react.uimanager.layoutanimation; import android.view.View; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import com.facebook.react.uimanager.IllegalViewOperationException; abstract class BaseLayoutAnimation extends AbstractLayoutAnimation { Animation createAnimationImpl(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { if (this.mAnimatedProperty != null) { StringBuilder stringBuilder; float f1; paramInt1 = null.$SwitchMap$com$facebook$react$uimanager$layoutanimation$AnimatedPropertyType[this.mAnimatedProperty.ordinal()]; float f2 = 0.0F; if (paramInt1 != 1) { if (paramInt1 == 2) { if (isReverse()) { f1 = 1.0F; } else { f1 = 0.0F; } if (isReverse()) { f2 = 0.0F; } else { f2 = 1.0F; } return (Animation)new ScaleAnimation(f1, f2, f1, f2, 1, 0.5F, 1, 0.5F); } stringBuilder = new StringBuilder("Missing animation for property : "); stringBuilder.append(this.mAnimatedProperty); throw new IllegalViewOperationException(stringBuilder.toString()); } if (isReverse()) { f1 = stringBuilder.getAlpha(); } else { f1 = 0.0F; } if (!isReverse()) f2 = stringBuilder.getAlpha(); return new OpacityAnimation((View)stringBuilder, f1, f2); } throw new IllegalViewOperationException("Missing animated property from animation config"); } abstract boolean isReverse(); boolean isValid() { return (this.mDurationMs > 0 && this.mAnimatedProperty != null); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\layoutanimation\BaseLayoutAnimation.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package analyzetweets; import twitter4j.*; import twitter4j.auth.OAuth2Token; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Scanner; /** * Program to perform sentiment analysis on twitter tweets by fetching tweets using twitter public apis and latter * doing sentiment analysis over each of them using Stanford CoreNLP library. * * References used: * Twitter: https://developer.twitter.com/en/docs/basics/getting-started * Stanford CoreNLP: https://stanfordnlp.github.io/CoreNLP/ */ public class AnalyzeTweets { public static final String consumerKey = "[***YOUR CONSUMER KEY***]"; public static final String consumerSecret = "[***CONSUMER SECRET***]"; public static Twitter twitter; public static StanfordCoreNLP pipeline; public static OAuth2Token getOAuth2Token() throws TwitterException { ConfigurationBuilder configurationBuilder= new ConfigurationBuilder(); configurationBuilder.setApplicationOnlyAuthEnabled(true); configurationBuilder.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret); Configuration configuration = configurationBuilder.build(); OAuth2Token token = new TwitterFactory(configuration).getInstance().getOAuth2Token(); return token; } public static Twitter getTwitterObject() throws TwitterException { OAuth2Token token = getOAuth2Token(); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setApplicationOnlyAuthEnabled(true); configurationBuilder.setOAuthConsumerKey(consumerKey); configurationBuilder.setOAuthConsumerSecret(consumerSecret); configurationBuilder.setOAuth2TokenType(token.getTokenType()); configurationBuilder.setOAuth2AccessToken(token.getAccessToken()); Configuration configuration = configurationBuilder.build(); Twitter twitter = new TwitterFactory(configuration).getInstance(); return twitter; } public static List<String> getTweets(String query) throws TwitterException{ List<String> list = new LinkedList<String>(); Query q = new Query(query); QueryResult queryResult = twitter.search(q); List<Status> statusList = queryResult.getTweets(); for(Status s : statusList) list.add(s.getText()); return list; } public static int analyzeSentiment(String tweet) { int finalSentimentScore = 0; if (tweet != null && tweet.length() > 0){ int longest = 0; Annotation annotation = pipeline.process(tweet); for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)){ Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentimentScore = RNNCoreAnnotations.getPredictedClass(tree); String partText = sentence.toString(); if (partText.length() > longest) { finalSentimentScore = sentimentScore; longest = partText.length(); } } } return finalSentimentScore; } public static void main( String[] args ) throws Exception { Scanner scanner = new Scanner(System.in); System.out.println("Query: "); String query = scanner.next(); Properties properties = new Properties(); properties.setProperty("annotators", "tokenize, ssplit, pos, parse, sentiment"); pipeline = new StanfordCoreNLP(properties); twitter = getTwitterObject(); List<String> tweetList = getTweets(query); for(String tweet : tweetList){ System.out.println(tweet + ":" + analyzeSentiment(tweet)); } } }
package com.example.demo; public class IntroToOOP { public IntroToOOP() { System.out.println("This is a no args constructor"); } public IntroToOOP(String classname){ System.out.println("This is args constructor"); } String carModel; String carColor; String engineType; public IntroToOOP(String model, String color, String engine){ carModel = model; carColor = color; engineType = engine; } public static void main(String[] args){ IntroToOOP constOne = new IntroToOOP("test"); } }
package com.nhatdear.sademo.helpers.chart; import com.github.mikephil.charting.charts.BarLineChartBase; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.nhatdear.sademo.activities.SA_MainActivity; import java.text.SimpleDateFormat; import java.util.Calendar; public class LineDayAxisValueFormatter implements IAxisValueFormatter { protected String[] mMonths = new String[]{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private int currentSearchYear = 2017; private SA_MainActivity.MODE mode; public LineDayAxisValueFormatter(int currentSearchYear, SA_MainActivity.MODE mode) { this.currentSearchYear = currentSearchYear; this.mode = mode; } @Override public String getFormattedValue(float value, AxisBase axis) { value = value + 1; //increase value by 1 switch (mode) { case DAILY: Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, currentSearchYear); cal.set(Calendar.DAY_OF_YEAR, (int)value); SimpleDateFormat sdf; sdf = new SimpleDateFormat("MMM dd"); return sdf.format(cal.getTime()); case MONTHLY: return mMonths[(int)value - 1]; case QUARTERLY: return String.format("Q%d",(int)value); default: return String.valueOf(value); } } }
package lesson37.LyThuyet; import java.util.ArrayList; public class Bai37 { public static void main(String[] args) { //tạo danh sách bạn bè kiểu String ArrayList<String> friends = new ArrayList<>(); friends.add("Cường"); friends.add("Hoàng"); friends.add("Huy"); friends.add("Đức"); friends.add("Hưng"); //tạo danh sách những con số kiểu Integer ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(3); numbers.add(2); numbers.add(7); numbers.add(5); System.out.println("danh sách những người bạn: "); showArrayList(friends); System.out.println("Danh sách những con số: "); System.out.println(numbers); System.out.println("================================================="); Bai37 obj = new Bai37(); System.out.println("phần tử ở giữa trong danh sách những người bạn là: " + obj.getMid(friends)); System.out.println("Phần tử ở giữa trong danh sách những con số là: " + obj.getMid(numbers)); System.out.println("==================================================="); System.out.println("Người có tên cuối cùng trong danh sách theo bảng chữ cái là: " + obj.findMax(friends)); System.out.println("Số lớn nhất trong danh sách là: " + obj.findMax(numbers)); //bây giờ tạo ra một danh sách Student mới // ArrayList<Student> students = new ArrayList<>(); // students.add(new Student("a")); // students.add(new Student("b")); // students.add(new Student("c")); // // //thì dòng này bị lỗi vì Student chưa được implement Comparable // System.out.println("Học sinh có tên sau cùng theo bảng chữ cái là: " + obj.findMax(students)); } /** * phương thức dùng để hiển thị danh sách các phần tử của một kiểu bất kì nào đó */ private static <T> void showArrayList(ArrayList<T> list) { for (var e : list) { System.out.print(e + " "); } System.out.println(); //xuống dòng } /** * phương thức tìm ra phần tử chính giữa của một list bất kì * @param list * @param <T> * @return */ private <T> T getMid(ArrayList<T> list) { int mid = list.size() / 2; return list.get(mid); } /** * phương thức tìm giá trị lớn nhất trong một danh sách * hoặc một tên có bảng chữ cái đứng sau cùng * @param list * @param <T> * @return */ public <T extends Comparable> T findMax(ArrayList<T> list) { if (list == null || list.size() == 0) { return null; } var max = list.get(0); for (var e : list) { if (e.compareTo(max) > 0) { max = e; } } return max; } }
/** * © Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.watson.developer_cloud.android.speech_to_text.v1.audio; import com.ibm.watson.developer_cloud.android.speech_to_text.v1.dto.SpeechConfiguration; import com.ibm.watson.developer_cloud.android.speech_to_text.v1.opus.JNAOpus; import com.ibm.watson.developer_cloud.android.speech_to_text.v1.opus.OpusWriter; import com.sun.jna.ptr.PointerByReference; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; /** * Ogg Opus Encoder */ public class OggOpusEnc extends OpusWriter implements ISpeechEncoder { // Use PROPRIETARY notice if class contains a main() method, otherwise use COPYRIGHT notice. public static final String COPYRIGHT_NOTICE = "(c) Copyright IBM Corp. 2015"; /** Data writer */ private OpusWriter writer = null; /** Opus encoder reference */ private PointerByReference opusEncoder; /** * Constructor */ public OggOpusEnc() {} /** * For WebSocketClient * @param uploader * @throws IOException */ public void initEncoderWithUploader(IChunkUploader uploader) throws IOException{ writer = new OpusWriter(uploader); IntBuffer error = IntBuffer.allocate(4); this.opusEncoder = JNAOpus.INSTANCE.opus_encoder_create( SpeechConfiguration.SAMPLE_RATE, SpeechConfiguration.AUDIO_CHANNELS, JNAOpus.OPUS_APPLICATION_VOIP, error); } /** * When the encode begins */ @Override public void onStart() { writer.writeHeader("encoder=Lavc56.20.100 libopus"); } /** * Encode raw audio data into Opus format then call OpusWriter to write the Ogg packet * * @param rawAudio * @return * @throws IOException */ public int encodeAndWrite(byte[] rawAudio) throws IOException { int uploadedAudioSize = 0; ByteArrayInputStream ios = new ByteArrayInputStream(rawAudio); byte[] data = new byte[SpeechConfiguration.FRAME_SIZE*2]; int bufferSize, read; while((read = ios.read(data)) > 0){ bufferSize = read; byte[] pcmBuffer = new byte[read]; System.arraycopy(data, 0, pcmBuffer, 0, read); ShortBuffer shortBuffer = ShortBuffer.allocate(bufferSize); for (int i = 0; i < read; i += 2) { int b1 = pcmBuffer[i] & 0xff; int b2 = pcmBuffer[i+1] << 8; shortBuffer.put((short) (b1 | b2)); } shortBuffer.flip(); ByteBuffer opusBuffer = ByteBuffer.allocate(bufferSize); int opus_encoded = JNAOpus.INSTANCE.opus_encode(this.opusEncoder, shortBuffer, SpeechConfiguration.FRAME_SIZE, opusBuffer, bufferSize); opusBuffer.position(opus_encoded); opusBuffer.flip(); byte[] opusData = new byte[opusBuffer.remaining()]; opusBuffer.get(opusData, 0, opusData.length); if (opus_encoded > 0) { uploadedAudioSize += opusData.length; writer.writePacket(opusData, 0, opusData.length); } } ios.close(); return uploadedAudioSize; } /** * Close writer */ public void close() { try { writer.close(); JNAOpus.INSTANCE.opus_encoder_destroy(this.opusEncoder); } catch (IOException e) { e.printStackTrace(); } } }
package cn.chinaunicom.monitor.viewholders; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.github.mikephil.charting.charts.PieChart; import java.util.ArrayList; import java.util.List; import cn.chinaunicom.monitor.R; import cn.chinaunicom.monitor.chart.BarChartStyle; import cn.chinaunicom.monitor.chart.PieChartStyle; /** * Created by yfyang on 2017/8/7. */ public class SixPieChartViewHolder extends BaseViewHolder { private PieChart pieChart_1; private PieChart pieChart_2; private PieChart pieChart_3; private PieChart pieChart_4; private PieChart pieChart_5; private PieChart pieChart_6; private TextView title_1; private TextView title_2; private TextView title_3; private TextView title_4; private TextView title_5; private TextView title_6; public LinearLayout firstRowChart; public LinearLayout firstRowTitle; public LinearLayout secondRowChart; public LinearLayout secondRowTitle; public FrameLayout loading; public List<PieChart> pieCharts = new ArrayList<>(); public List<TextView> chartTitles = new ArrayList<>(); public SixPieChartViewHolder(View view) { super(view); this.pieChart_1 = (PieChart)view.findViewById(R.id.pieChart_1); this.pieChart_2 = (PieChart)view.findViewById(R.id.pieChart_2); this.pieChart_3 = (PieChart)view.findViewById(R.id.pieChart_3); this.pieChart_4 = (PieChart)view.findViewById(R.id.pieChart_4); this.pieChart_5 = (PieChart)view.findViewById(R.id.pieChart_5); this.pieChart_6 = (PieChart)view.findViewById(R.id.pieChart_6); this.title_1 = (TextView) view.findViewById(R.id.chart1Title); this.title_2 = (TextView) view.findViewById(R.id.chart2Title); this.title_3 = (TextView) view.findViewById(R.id.chart3Title); this.title_4 = (TextView) view.findViewById(R.id.chart4Title); this.title_5 = (TextView) view.findViewById(R.id.chart5Title); this.title_6 = (TextView) view.findViewById(R.id.chart6Title); this.firstRowChart = (LinearLayout) view.findViewById(R.id.firstRowChart); this.firstRowTitle = (LinearLayout) view.findViewById(R.id.firstRowTitle); this.secondRowChart = (LinearLayout) view.findViewById(R.id.secondRowChart); this.secondRowTitle = (LinearLayout) view.findViewById(R.id.secondRowTitle); this.loading = (FrameLayout) view.findViewById(R.id.loadingIndicator); pieCharts.add(this.pieChart_1); pieCharts.add(this.pieChart_2); pieCharts.add(this.pieChart_3); pieCharts.add(this.pieChart_4); pieCharts.add(this.pieChart_5); pieCharts.add(this.pieChart_6); chartTitles.add(this.title_1); chartTitles.add(this.title_2); chartTitles.add(this.title_3); chartTitles.add(this.title_4); chartTitles.add(this.title_5); chartTitles.add(this.title_6); for (int num = 0; num < pieCharts.size(); num++) { pieCharts.get(num).setNoDataText(new PieChartStyle().chartNoDataText); } } }
package com.Strings; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class subS { public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching."; public static void main(String[] args) { String s = "000.12"; // Write your code here. String[] x = s.split("[0-2]?"); System.out.println(x.length); for(String el : x){ System.out.println(el); } } }
package org.generationcp.browser.germplasm.pedigree; import java.io.File; import java.io.FileNotFoundException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import org.generationcp.browser.germplasm.GermplasmDetail; import org.generationcp.browser.germplasm.GermplasmQueries; import org.generationcp.middleware.exceptions.MiddlewareQueryException; import org.generationcp.middleware.pojos.GermplasmPedigreeTree; import org.generationcp.middleware.pojos.GermplasmPedigreeTreeNode; import com.vaadin.ui.Window; public class CreatePedigreeGraph { /** * */ private GermplasmQueries qQuery; private GraphVizUtility gv; private int gid; private int level; private Window window; public CreatePedigreeGraph(int gid, int level,Window window,GermplasmQueries qQuery){ this.qQuery=qQuery; this.gid=gid; this.level=level; this.window=window; } /** * Construct a DOT graph in memory, convert it * to image and store the image in the file system. * @throws MalformedURLException * @throws URISyntaxException * @throws FileNotFoundException * @throws MiddlewareQueryException */ public void create(String graphName) throws FileNotFoundException, URISyntaxException, MiddlewareQueryException { gv = new GraphVizUtility(); gv.initialize(); gv.setImageOutputPath(GraphVizUtility.createImageOutputPathForWindow(window)); gv.addln(gv.start_graph()); // used for testing /* gv.addln("50544 [shape=box];"); gv.addln("50547 [shape=box];"); gv.addln("50547 [URL=\"http://www.google.com\"];"); gv.addln("50544 [label=\"A 64(50544)\"];"); gv.addln("50547 [label=\"A 87(50594)\"];"); gv.addln("50544->50547;"); gv.addln("50566 [shape=box];"); gv.addln("50566 [label=\"A 89(50594)\",URL=\"http://www.google.com\"];"); gv.addln("50544->50566;"); gv.addln("nodeB [shape=none];"); gv.addln("nodeB [label=\"\"];"); gv.addln("50566->nodeB [style=\"dashed\"];"); */ createDiGraphNode(); gv.addln(gv.end_graph()); System.out.println(gv.toString()); // System.out.println(gv.getDotSource()); // String type = "gif"; // String type = "dot"; // String type = "fig"; // open with xfig // String type = "pdf"; // String type = "ps"; // String type = "svg"; // open with inkscape String type = "png"; // Load the directory as a resource File out = new File(gv.graphVizOutputPath(graphName+"."+type)); // Windows //create graph gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out ); } private void createDiGraphNode() throws MiddlewareQueryException { GermplasmPedigreeTree germplasmPedigreeTree = this.qQuery.generatePedigreeTree(Integer.valueOf(gid), level); if(level==1){ String leafNodeGIDRoot=germplasmPedigreeTree.getRoot().getGermplasm().getGid().toString(); String leafNodeLabelRoot=germplasmPedigreeTree.getRoot().getGermplasm().getPreferredName().getNval()+ "("+germplasmPedigreeTree.getRoot().getGermplasm().getGid().toString()+")"; gv.addln(leafNodeGIDRoot+" [shape=box];"); gv.addln(leafNodeGIDRoot+" [label=\""+leafNodeLabelRoot+"\"];"); gv.addln(leafNodeGIDRoot+";"); }else{ addNode(germplasmPedigreeTree.getRoot(), 1); } } private void addNode(GermplasmPedigreeTreeNode node, int level) { for (GermplasmPedigreeTreeNode parent : node.getLinkedNodes()) { try{ if(!parent.getGermplasm().getGid().toString().equals("0")){ String leafNodeGID=parent.getGermplasm().getGid().toString(); String leafNodeLabel=parent.getGermplasm().getPreferredName().getNval()+ "("+parent.getGermplasm().getGid().toString()+")"; gv.addln(leafNodeGID+" [shape=box];"); gv.addln(leafNodeGID+" [label=\""+leafNodeLabel+"\"];"); // gv.addln(leafNodeGID+" [URL=http://google.com];"); String parentNodeGID=node.getGermplasm().getGid().toString(); String parentNodeLabel=node.getGermplasm().getPreferredName().getNval()+"("+node.getGermplasm().getGid().toString()+")"; gv.addln(parentNodeGID+" [shape=box];"); gv.addln(parentNodeGID+" [label=\""+parentNodeLabel+"\"];"); if(level==1){ String leafNodeGIDRoot=node.getGermplasm().getGid().toString(); String leafNodeLabelRoot=node.getGermplasm().getPreferredName().getNval()+ "("+node.getGermplasm().getGid().toString()+")"; gv.addln(leafNodeGIDRoot+" [shape=box];"); gv.addln(leafNodeGIDRoot+" [label=\""+leafNodeLabelRoot+"\"];"); // gv.addln(leafNodeGIDRoot+" [URL=http://google.com];"); gv.addln(leafNodeGIDRoot+"->"+leafNodeGID+";"); } gv.addln(parentNodeGID+"->"+leafNodeGID+";"); // if(parent.getLinkedNodes().isEmpty()){ // // gv.addln(leafNodeGID+level+"[shape=none];"); // gv.addln(leafNodeGID+level+"[label=\"\"];"); //// gv.addln(leafNodeGID+level+"[URL=\"http://google.com\"];"); // gv.addln(leafNodeGID+"->"+leafNodeGID+level +" [style=\"dashed\"];"); // } } addNode(parent, level + 1); }catch(Exception e){ System.out.println("Error Graph"); addNode(parent, level + 1); } } } }
package com.tencent.mm.plugin.setting.ui.setting; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.tencent.mm.plugin.setting.a.f; import com.tencent.mm.plugin.setting.a.g; import com.tencent.mm.protocal.c.bwy; import java.util.List; class SettingsManageAuthUI$a extends BaseAdapter { final /* synthetic */ SettingsManageAuthUI mSw; List<bwy> mSx; private class a { Button eOQ; TextView hJd; TextView mSB; TextView mSC; private a() { } /* synthetic */ a(SettingsManageAuthUI$a settingsManageAuthUI$a, byte b) { this(); } } private SettingsManageAuthUI$a(SettingsManageAuthUI settingsManageAuthUI) { this.mSw = settingsManageAuthUI; } /* synthetic */ SettingsManageAuthUI$a(SettingsManageAuthUI settingsManageAuthUI, byte b) { this(settingsManageAuthUI); } public final int getCount() { if (this.mSx == null || this.mSx.isEmpty()) { return 0; } return this.mSx.size(); } /* renamed from: vN */ public final bwy getItem(int i) { if (i < 0 || i >= getCount()) { return null; } return (bwy) this.mSx.get(i); } public final long getItemId(int i) { return (long) i; } public final View getView(int i, View view, ViewGroup viewGroup) { a aVar; if (view == null) { view = this.mSw.getLayoutInflater().inflate(g.settings_auth_list_item, null); a aVar2 = new a(this, (byte) 0); view.setTag(aVar2); aVar = aVar2; } else { aVar = (a) view.getTag(); } aVar.hJd = (TextView) view.findViewById(f.settings_auth_item_name); aVar.mSB = (TextView) view.findViewById(f.settings_auth_item_type); aVar.mSC = (TextView) view.findViewById(f.settings_auth_item_auth_list); aVar.eOQ = (Button) view.findViewById(f.settings_auth_del_btn); aVar.eOQ.setOnClickListener(new 1(this, i)); if (SettingsManageAuthUI.c(this.mSw)) { aVar.eOQ.setVisibility(0); } else { aVar.eOQ.setVisibility(8); } if (getItem(i) != null) { aVar.hJd.setText(getItem(i).dxK); aVar.mSB.setText(getItem(i).stn); aVar.mSC.setText(SettingsManageAuthUI.ca(getItem(i).stm)); } return view; } }
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.stage.Stage; import java.awt.*; public class TheGameOfMorra extends Application { //for server title private HBox serverTitleBox; private Text serverTitle; //for entering in the port number private HBox portBox; private TextField portNum; private Text portNumTxt; private Button portBtn; //for controlling the server to turn on or off private HBox serverOnOffBox; private Text serverOnOffTxt; private Button turnServerOn; private Button turnServerOff; //for number of clients online private HBox numOfClientsBox; private Text numOfClientsTxt; //player 1 things private VBox player1Box; private Text player1Played; private Text player1Score; //player 2 things private VBox player2Box; private Text player2Played; private Text player2Score; //status of the game things private VBox statusOfGameBox; private Text statusOfGameTitle; private Text statusOfGameTxt; //play again things private HBox playAgainBox; private Text playAgainTxt; private Button y_playAgain; private Button n_playAgain; //other private BorderPane rootPane; static javafx.scene.text.Font currentFont = new javafx.scene.text.Font("Comic Sans MC", 20); //just for consistent static javafx.scene.text.Font buttonFont = new Font("Comic Sans MC", 12); public static void main(String[] args) { // TODO Auto-generated method stub launch(args); } //feel free to remove the starter code from this method @Override public void start(Stage primaryStage) throws Exception { // TODO Auto-generated method stub primaryStage.setTitle("(Server) Let's Play Morra!!!"); final int textFieldWidth = 100; final int textFieldHeight = 50; final int buttonSizeWidth = 70; final int buttonSizeHeight = 50; //things for the GUI //server title serverTitle = new Text(); serverTitle.setFont(currentFont); serverTitle.setText("Game of Morra (Server)"); serverTitleBox = new HBox(serverTitle); serverTitleBox.setLayoutX(50); serverTitleBox.setLayoutY(10); //port num portNumTxt = new Text(); portNumTxt.setFont(currentFont); portNumTxt.setText("Enter port number:"); portNum = new TextField(); portNum.setMinSize(textFieldWidth, textFieldHeight); portBtn = new Button("Enter"); portBtn.setMinSize(buttonSizeWidth, buttonSizeHeight); portBtn.setFont(buttonFont); portBox = new HBox(20,portNumTxt, portNum, portBtn); portBox.setLayoutX(10); portBox.setLayoutY(50); //controls for on/off serverOnOffTxt = new Text(); serverOnOffTxt.setFont(currentFont); serverOnOffTxt.setText("Turn sever on/off:"); turnServerOn = new Button("On"); turnServerOn.setMinSize(buttonSizeWidth, buttonSizeHeight); turnServerOn.setFont(buttonFont); turnServerOff = new Button("Off"); turnServerOff.setMinSize(buttonSizeWidth, buttonSizeHeight); turnServerOff.setFont(buttonFont); serverOnOffBox = new HBox(20, serverOnOffTxt, turnServerOn, turnServerOff); serverOnOffBox.setLayoutX(10); serverOnOffBox.setLayoutY(110); //number of clients numOfClientsTxt = new Text(); numOfClientsTxt.setFont(currentFont); numOfClientsTxt.setText("No. of clients: TBD :)"); //will continuously be updated so not set in stone yet numOfClientsBox = new HBox(numOfClientsTxt); numOfClientsBox.setLayoutX(10); numOfClientsBox.setLayoutY(170); //player 1 box and things player1Played = new Text(); player1Played.setFont(currentFont); player1Played.setText("Player 1 played: #"); //will continuously be updated so not set in stone yet player1Score = new Text(); player1Score.setFont(currentFont); player1Score.setText("Player 1 score: #"); //will continuously be updated so not set in stone yet player1Box = new VBox(20, player1Played, player1Score); player1Box.setLayoutX(10); player1Box.setLayoutY(230); //player 2 box and things player2Played = new Text(); player2Played.setFont(currentFont); player2Played.setText("Player 2 played: #"); //will continuously be updated so not set in stone yet player2Score = new Text(); player2Score.setFont(currentFont); player2Score.setText("Player 2 score: #"); //will continuously be updated so not set in stone yet player2Box = new VBox(20, player2Played, player2Score); player2Box.setLayoutX(180); player2Box.setLayoutY(230); //status of game stuff statusOfGameTitle = new Text(); statusOfGameTitle.setFont(currentFont); statusOfGameTitle.setText("Status of Game:"); statusOfGameTxt = new Text(); statusOfGameTxt.setFont(currentFont); statusOfGameTxt.setText("Player 1 vs Player 2 "); statusOfGameBox = new VBox(20, statusOfGameTitle, statusOfGameTxt); statusOfGameBox.setLayoutX(10); statusOfGameBox.setLayoutY(330); //play again things playAgainTxt = new Text(); playAgainTxt.setFont(currentFont); playAgainTxt.setText("Play again?: "); y_playAgain = new Button("Yes"); y_playAgain.setMinSize(buttonSizeWidth, buttonSizeHeight); y_playAgain.setFont(buttonFont); n_playAgain = new Button("No"); n_playAgain.setMinSize(buttonSizeWidth, buttonSizeHeight); n_playAgain.setFont(buttonFont); playAgainBox = new HBox(20, playAgainTxt, y_playAgain, n_playAgain); playAgainBox.setLayoutX(10); playAgainBox.setLayoutY(450); //things for the scene rootPane = new BorderPane(); rootPane.getChildren().addAll(serverTitleBox, portBox, serverOnOffBox, numOfClientsBox, player1Box, player2Box, statusOfGameBox, playAgainBox); rootPane.setStyle("-fx-background-color: seagreen"); Scene scene = new Scene(rootPane,400,600); primaryStage.setScene(scene); primaryStage.show(); } }
package hu.webhejj.pdb.mobi; public class MobiBookInfo { private String drmServerId; private String drmCommerceId; private String drmEbookBaseBookId; private String author; private String publisher; private String imprint; private String description; private String isbn; private String subject; private String publishingDate; private String review; private String contributor; private String rights; private String subjectCode; private String type; private String source; private String asin; private String versionNumber; private String sample; private int startReading; private boolean isAdult; private String retailPrice; private String retailPriceCurrency; private int coverImageIndex = -1; private int thumImageIndex = -1; private boolean hasFakecover; private int creatorSoftware; private int creatorMajorVersion; private int creatorMinorVersion; private int creatorBuildNumber; private String watermark; private String tamperProofKeys; private String fontSignature; private int clippingLimit; private int publisherLimit; private boolean textToSpeechEnabled; private String cdeType; private String lastUpdatetime; private String updatedTitle; public String getDrmServerId() { return drmServerId; } public void setDrmServerId(String drmServerId) { this.drmServerId = drmServerId; } public String getDrmCommerceId() { return drmCommerceId; } public void setDrmCommerceId(String drmCommerceId) { this.drmCommerceId = drmCommerceId; } public String getDrmEbookBaseBookId() { return drmEbookBaseBookId; } public void setDrmEbookBaseBookId(String drmEbookBaseBookId) { this.drmEbookBaseBookId = drmEbookBaseBookId; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getImprint() { return imprint; } public void setImprint(String imprint) { this.imprint = imprint; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getPublishingDate() { return publishingDate; } public void setPublishingDate(String publishingDate) { this.publishingDate = publishingDate; } public String getReview() { return review; } public void setReview(String review) { this.review = review; } public String getContributor() { return contributor; } public void setContributor(String contributor) { this.contributor = contributor; } public String getRights() { return rights; } public void setRights(String rights) { this.rights = rights; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getAsin() { return asin; } public void setAsin(String asin) { this.asin = asin; } public String getVersionNumber() { return versionNumber; } public void setVersionNumber(String versionNumber) { this.versionNumber = versionNumber; } public String getSample() { return sample; } public void setSample(String sample) { this.sample = sample; } public int getStartReading() { return startReading; } public void setStartReading(int startReading) { this.startReading = startReading; } public boolean isAdult() { return isAdult; } public void setAdult(boolean isAdult) { this.isAdult = isAdult; } public String getRetailPrice() { return retailPrice; } public void setRetailPrice(String retailPrice) { this.retailPrice = retailPrice; } public String getRetailPriceCurrency() { return retailPriceCurrency; } public void setRetailPriceCurrency(String retailPriceCurrency) { this.retailPriceCurrency = retailPriceCurrency; } public int getCoverImageIndex() { return coverImageIndex; } public void setCoverImageIndex(int coverImageIndex) { this.coverImageIndex = coverImageIndex; } public int getThumImageIndex() { return thumImageIndex; } public void setThumImageIndex(int thumImageIndex) { this.thumImageIndex = thumImageIndex; } public boolean isHasFakecover() { return hasFakecover; } public void setHasFakecover(boolean hasFakecover) { this.hasFakecover = hasFakecover; } public int getCreatorSoftware() { return creatorSoftware; } public void setCreatorSoftware(int creatorSoftware) { this.creatorSoftware = creatorSoftware; } public int getCreatorMajorVersion() { return creatorMajorVersion; } public void setCreatorMajorVersion(int creatorMajorVersion) { this.creatorMajorVersion = creatorMajorVersion; } public int getCreatorMinorVersion() { return creatorMinorVersion; } public void setCreatorMinorVersion(int creatorMinorVersion) { this.creatorMinorVersion = creatorMinorVersion; } public int getCreatorBuildNumber() { return creatorBuildNumber; } public void setCreatorBuildNumber(int creatorBuildNumber) { this.creatorBuildNumber = creatorBuildNumber; } public String getWatermark() { return watermark; } public void setWatermark(String watermark) { this.watermark = watermark; } public String getTamperProofKeys() { return tamperProofKeys; } public void setTamperProofKeys(String tamperProofKeys) { this.tamperProofKeys = tamperProofKeys; } public String getFontSignature() { return fontSignature; } public void setFontSignature(String fontSignature) { this.fontSignature = fontSignature; } public int getClippingLimit() { return clippingLimit; } public void setClippingLimit(int clippingLimit) { this.clippingLimit = clippingLimit; } public int getPublisherLimit() { return publisherLimit; } public void setPublisherLimit(int publisherLimit) { this.publisherLimit = publisherLimit; } public boolean isTextToSpeechEnabled() { return textToSpeechEnabled; } public void setTextToSpeechEnabled(boolean textToSpeechEnabled) { this.textToSpeechEnabled = textToSpeechEnabled; } public String getCdeType() { return cdeType; } public void setCdeType(String cdeType) { this.cdeType = cdeType; } public String getLastUpdatetime() { return lastUpdatetime; } public void setLastUpdatetime(String lastUpdatetime) { this.lastUpdatetime = lastUpdatetime; } public String getUpdatedTitle() { return updatedTitle; } public void setUpdatedTitle(String updatedTitle) { this.updatedTitle = updatedTitle; } }
package com.linkedbook.controller; import com.linkedbook.response.PageResponse; import com.linkedbook.response.Response; import com.linkedbook.service.DealService; import com.linkedbook.dto.deal.createDeal.CreateDealInput; import com.linkedbook.dto.deal.createDeal.CreateDealOutput; import com.linkedbook.dto.deal.selectDeal.SelectDealInput; import com.linkedbook.dto.deal.selectDeal.SelectDealOutput; import com.linkedbook.dto.deal.selectDealDetail.SelectDealDetailOutput; import com.linkedbook.dto.deal.updateDeal.UpdateDealInput; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/deals") @RequiredArgsConstructor @Slf4j public class DealController { private final DealService dealService; /** * 거래 생성 API [POST] /deals * * @return Response<Object> */ // Body @PostMapping public Response<CreateDealOutput> createDeal(@RequestBody CreateDealInput createDealInput) { log.info("[POST] /deals"); return dealService.createDeal(createDealInput); } /** * 거래 조회 API [GET]] /deals * * @return Response<List<SelectDealOutput>> */ // Params @GetMapping public PageResponse<SelectDealOutput> selectDealList(@RequestParam(required = false) String search, @RequestParam(required = false) String filter, @RequestParam(required = false) Integer userId, @RequestParam(required = false) String bookId, @RequestParam(required = false) Integer areaId, @RequestParam int page, @RequestParam int size) { log.info("[GET] /deals"); SelectDealInput selectDealInput = SelectDealInput.builder().search(search).filter(filter).userId(userId) .bookId(bookId).areaId(areaId).page(page).size(size).build(); Pageable pageable; if (filter.equals("NEW")) { pageable = PageRequest.of(selectDealInput.getPage(), selectDealInput.getSize(), Sort.Direction.DESC, "created_at"); } else if (filter.equals("PRICE")) { pageable = PageRequest.of(selectDealInput.getPage(), selectDealInput.getSize(), Sort.Direction.ASC, "price"); } else { pageable = PageRequest.of(selectDealInput.getPage(), selectDealInput.getSize(), Sort.by("quality").and(Sort.by("created_at").descending())); } return dealService.selectDealList(selectDealInput, pageable); } /** * 거래 수정 API [PATCH] /deals/{id} * * @return Response<Object> */ // Body @PatchMapping("/{id}") public Response<Object> updateDeal(@RequestBody UpdateDealInput updateDealInput, @PathVariable("id") int dealId) { log.info("[PATCH] /deals/" + dealId); return dealService.updateDeal(updateDealInput, dealId); } /** * 거래 상세 조회 API [GET]] /deals/{id} * * @return Response<Object> */ // Params @GetMapping("/{id}") public Response<SelectDealDetailOutput> selectDeal(@PathVariable("id") int dealId) { log.info("[GET] /deals/" + dealId); return dealService.selectDeal(dealId); } }
package unocerounocero; /************************************** * * @author jbobi * */ public class EstadoDelJuego { private int[][] tableroJuego; private int puntuacion; private Modelo modelo; public EstadoDelJuego(Modelo modelo) { this.modelo = modelo; tableroJuego = new int[Tablero.TAMANIO][Tablero.TAMANIO]; } public String toStream() { load(); String aux=""; aux=aux+puntuacion+" "; // puntuacion for (int y=0;y<Tablero.TAMANIO;y++) // tablero for (int x=0;x<Tablero.TAMANIO;x++) aux=aux+tableroJuego[x][y]+" "; return aux; } public void fromStream(String s) { String aux[] = s.split(" "); int pos=0; puntuacion = Integer.parseInt(aux[pos]); // puntuacion for (int y=0;y<Tablero.TAMANIO;y++) // tablero for (int x=0;x<Tablero.TAMANIO;x++) { pos++; tableroJuego[x][y] = Integer.parseInt(aux[pos]); } save(); } private void load() { tableroJuego = modelo.getTableroJuego().getTablero(); puntuacion = modelo.getPuntuacion().get(); } private void save() { modelo.getTableroJuego().setTablero(tableroJuego); modelo.getPuntuacion().set(puntuacion); } }
package lp2.interfaces; import javax.swing.*; import javax.swing.table.DefaultTableModel; import org.netbeans.lib.awtextra.AbsoluteConstraints; import org.netbeans.lib.awtextra.AbsoluteLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import lp2.lerDados.Estabelecimento; import lp2.lerDados.ReadData; import lp2.lerDados.Usuario; /** * Classe que cria e executa a interface grafica do menu ver todos para * interacao com o usuario do sistema. Essa classe disponibiliza para * o usuario uma lista de todos os estabelecimentos cadastrados * no sistema, dando a opcao de se escolher um e ter mais informacoes * sobre o mesmo. * * @author Flavia Gangorra<br> * Irvile Rodrigues Lavor<br> * Jordao Ezequiel Serafim de Araujo<br> * */ @SuppressWarnings("serial") public class MenuVerTodos extends JPanel implements ActionListener{ private JScrollPane scrollPaneTabelaOpinioes; private JScrollPane scrollPaneTabelaResultado; private JButton botaoVoltar; private JTable tabela; private JTable tabelaResultado; private JLabel selecioneEstabelecimento; private JLabel detalhamentoDeNotas; private JComboBox listaSuspensaDeEstabelecimentos; private String estabelecimentosCadastrados[]; /** * Metodo que cria e inicia a interface grafica do menu ver todos * os estabelecimentos, e ter outras informacoes sobre o mesmo * para interacao com o usuario. */ public MenuVerTodos(){ setSize(800,600); setVisible(true); setLayout(new AbsoluteLayout()); setBackground(new Color(253, 245, 230)); instanciaTodosComponentes(); iniciaComboBoxEstabelecimentos(); iniciaTabelas(); addNoContainer(); botaoVoltar.addActionListener(this); listaSuspensaDeEstabelecimentos.addActionListener(this); } private void instanciaTodosComponentes(){ //tabelas tabela = new JTable(); tabelaResultado = new JTable(); tabela.setEnabled(false); tabelaResultado.setEnabled(false); //ScroollPanes scrollPaneTabelaOpinioes = new JScrollPane(); scrollPaneTabelaResultado = new JScrollPane(); scrollPaneTabelaOpinioes.setViewportView(tabela); scrollPaneTabelaResultado.setViewportView(tabelaResultado); //Labels selecioneEstabelecimento = new JLabel("Selecione o Estabelecimento:"); detalhamentoDeNotas = new JLabel("Quantidade de votos por tipo de avaliação"); //Botoes botaoVoltar = new JButton("Voltar"); } private void addNoContainer(){ add(scrollPaneTabelaOpinioes, new AbsoluteConstraints(10,100,776,210)); add(scrollPaneTabelaResultado, new AbsoluteConstraints(10,350,776,146)); add(detalhamentoDeNotas, new AbsoluteConstraints(50, 320, 320, 23)); add(botaoVoltar, new AbsoluteConstraints(600,500,120,23)); add(selecioneEstabelecimento, new AbsoluteConstraints(50,50,220,23)); add(listaSuspensaDeEstabelecimentos, new AbsoluteConstraints(270,50,320,23)); } private void iniciaTabelas() { tabela.setModel(new DefaultTableModel(new Object[][]{}, new String[] { "Usuario", "Nota" })); tabelaResultado.setModel(new DefaultTableModel(new Object[][]{}, new String[] { "Avaliação", "Quantidade de Votos" })); } private void iniciaComboBoxEstabelecimentos() { //tamanho da lista de estabelecimentos + 1,pq logo abaixo eh adicionado um espaco vazio. estabelecimentosCadastrados = new String[ReadData.getEstabelecimentos().size()+1]; // so pra deixar vazio o primeiro campo, pra nao ficar como se ja tivesse um usuarios selecionado estabelecimentosCadastrados[0] = ""; int i = 1; for(Estabelecimento estabelecimento : ReadData.getEstabelecimentos()){ estabelecimentosCadastrados[i] = estabelecimento.getNome(); i ++; } listaSuspensaDeEstabelecimentos = new JComboBox(estabelecimentosCadastrados); //texto quando mouse fica sobre o botao. listaSuspensaDeEstabelecimentos.setToolTipText("Nome de todos os estabelecimentos"); botaoVoltar.setToolTipText("Clique para volta ao menu anterior"); } //Metodo que trata todos os eventos /** * Metodo responsavel por verificar e capturar eventos do usuario * com a interface grafica. */ @Override public void actionPerformed(ActionEvent event) { if(event.getSource() == listaSuspensaDeEstabelecimentos){ if(listaSuspensaDeEstabelecimentos.getSelectedIndex() != 0){ preencheTabela(); preencheTabelaResultado(); }else iniciaTabelas(); } if(event.getSource() == botaoVoltar){ MenuInicial.panelCorpo.removeAll(); MenuInicial.panelCorpo.add(new MenuPrincipal()); MenuInicial.panelCorpo.updateUI(); } } private void preencheTabela(){ Object table[][] = new Object[ReadData.getUsuarios().size()][2]; for(int i=0; i<ReadData.getUsuarios().size(); i++){ table[i][1] = ReadData.getUsuarios().get(i).getOpinioes().get(listaSuspensaDeEstabelecimentos.getSelectedIndex()-1); table[i][0] = ReadData.getUsuarios().get(i).getNome(); } tabela.setModel(new DefaultTableModel(table, new String[] { "Usuario", "Nota" })); } private void preencheTabelaResultado() { Object table[][] = new Object[11][2]; String avaliacao[] = {"5: Incrível. sensacional. impressionante","4: Muito bom", "3: Bastante bom", "2: É bonzinho", "1: Não é ruim", "0: Não conheço","-1: Acho um pouco ruim", "-2: Acho ruim","-3: Acho bastante ruim", "-4: Acho muito ruim","-5: Detesto" }; int notas[] = new int[11]; for(Usuario user : ReadData.getUsuarios()){ int opiniao = user.getOpinioes().get(listaSuspensaDeEstabelecimentos.getSelectedIndex()-1); if(opiniao == 5){ notas[0] += 1; }else if(opiniao == 4){ notas[1] += 1; }else if(opiniao == 3){ notas[2] += 1; }else if(opiniao == 2){ notas[3] += 1; }else if(opiniao == 1){ notas[4] += 1; }else if(opiniao == 0){ notas[5] += 1; }else if(opiniao == -1){ notas[6] += 1; }else if(opiniao == -2){ notas[7] += 1; }else if(opiniao == -3){ notas[8] += 1; }else if(opiniao == -4){ notas[9] += 1; }else if(opiniao == -5){ notas[10] += 1; } } for(int i=0; i<11; i++){ table[i][0] = avaliacao[i]; table[i][1] = notas[i]; } tabelaResultado.setModel(new DefaultTableModel(table, new String[] { "Avaliação", "Quantidade de Votos" })); } }
package cn.com.ykse.santa.repository.dao; import cn.com.ykse.santa.repository.entity.AssessmentFileCfgDO; import cn.com.ykse.santa.repository.entity.FileDO; import org.apache.ibatis.annotations.Param; import java.util.List; public interface AssessmentFileCfgDOMapper { int deleteByPrimaryKey(Integer cfgId); int insert(AssessmentFileCfgDO record); int insertSelective(AssessmentFileCfgDO record); AssessmentFileCfgDO selectByPrimaryKey(Integer cfgId); int updateByPrimaryKeySelective(AssessmentFileCfgDO record); int updateByPrimaryKey(AssessmentFileCfgDO record); List<FileDO> selectFilesByAssessmentId(Integer assessmentId); int deleteByAssessmentId(Integer assessmentId); }
package beans; import beans.interfaces.IColor; public class LockerFurniture extends Furniture implements IColor{//наследуемся от класса Furniture public final static double COST = 300; public LockerFurniture(String name) { super(name); } @Override public double getCostWithDiscount(){ return COST - (COST * 0.3); } @Override public String getColor() { return "yellow"; } }
package com.ssgl.mapper; import com.ssgl.bean.AuthPrivilege; import com.ssgl.bean.AuthPrivilegeExample; import org.apache.ibatis.annotations.Param; import java.util.List; public interface AuthPrivilegeMapper { int countByExample(AuthPrivilegeExample example); int deleteByExample(AuthPrivilegeExample example); int deleteByPrimaryKey(String id); int insert(AuthPrivilege record); int insertSelective(AuthPrivilege record); List<AuthPrivilege> selectByExample(AuthPrivilegeExample example); AuthPrivilege selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") AuthPrivilege record, @Param("example") AuthPrivilegeExample example); int updateByExample(@Param("record") AuthPrivilege record, @Param("example") AuthPrivilegeExample example); int updateByPrimaryKeySelective(AuthPrivilege record); int updateByPrimaryKey(AuthPrivilege record); }
public class noargsConst { String name; int age; noargsConst(){ System.out.println("Hello, my name is " + name + " and I am " + age + " years old "); } public static void main(String[] args) { noargsConst obj = new noargsConst(); } }
package lowOfDeteter.demo; import java.util.ArrayList; import java.util.List; /** * @Author:Jack * @Date: 2021/8/21 - 22:17 * @Description: lowOfDeteter * @Version: 1.0 */ public class Client { public static void main(String[] args) { Teacher teacher = new Teacher(); List<Girl> girls = new ArrayList<>(); for (int i = 0; i < 20; i++){ girls.add(new Girl()); } final GroupLeader groupLeader = new GroupLeader(girls); teacher.command(groupLeader); } }
package edu.bu.met622.lambdaexample; public class FindMatchingAnimal { private static void myprint(Animal animal, CheckTrait trait) { if(trait.test(animal)) System.out.println(animal); } public static void main(String[] args) { myprint(new Animal("fish", false, true), a -> a.canHop()); // set canhop flag to true false to see the result myprint(new Animal("kangaroo:", true, false), a -> a.canHop()); } }
package com.musical_structure.musicalstructre; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class MySongsFragment extends Fragment { public MySongsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.song_list, container, false); final ArrayList<Song> songs = new ArrayList<Song>(); songs.add(new Song("song1" , "artist1" , "album1")) ; songs.add(new Song("song2" , "artist2" , "album2")) ; songs.add(new Song("song3" , "artist3" , "album3")) ; songs.add(new Song("song4" , "artist4" , "album4")) ; songAdapter adapter = new songAdapter(getActivity(),songs); ListView listView = (ListView) rootView.findViewById(R.id.list); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Song song = songs.get(i) ; Intent intent = new Intent(getActivity(), songDetails.class); intent.putExtra("artist" , song.getArtist()) ; intent.putExtra("album" , song.getAlbum()) ; getActivity().startActivity(intent) ; } }); return rootView ; } }
package com.tencent.mm.plugin.game.wepkg.model; import com.tencent.mm.ab.b; import com.tencent.mm.plugin.game.wepkg.model.WepkgVersionManager.WepkgNetSceneProcessTask; import com.tencent.mm.plugin.game.wepkg.utils.WepkgRunCgi.a; import com.tencent.mm.plugin.game.wepkg.utils.d; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.oz; import com.tencent.mm.sdk.platformtools.x; class WepkgVersionManager$WepkgNetSceneProcessTask$1 implements a { final /* synthetic */ WepkgNetSceneProcessTask kgf; WepkgVersionManager$WepkgNetSceneProcessTask$1(WepkgNetSceneProcessTask wepkgNetSceneProcessTask) { this.kgf = wepkgNetSceneProcessTask; } public final void a(int i, int i2, String str, b bVar) { if (i == 0 && i2 == 0 && bVar.dIE.dIL != null) { try { d.Em().H(new 1(this, (oz) bVar.dIE.dIL)); return; } catch (Exception e) { x.e("MicroMsg.Wepkg.WepkgVersionManager", "get checkwepkgversion error"); return; } } x.e("MicroMsg.Wepkg.WepkgVersionManager", "check wepkg version, cgi failed, errType = %d, errCode = %d, errMsg = %s, rr.resp = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str, bVar.dIE.dIL}); h.mEJ.a(859, 16, 1, false); } }
package com.foxcreations.springtest.app.DTO; public class DTOConsulta { private Integer id ; private String nombre; private String funcion; private String jefe; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getFuncion() { return funcion; } public void setFuncion(String funcion) { this.funcion = funcion; } public String getJefe() { return jefe; } public void setJefe(String jefe) { this.jefe = jefe; } public DTOConsulta(Integer id, String nombre, String funcion, String jefe) { this.id = id; this.nombre = nombre; this.funcion = funcion; this.jefe = jefe; } public DTOConsulta() { } }
package com.tencent.mm.ui.chatting.viewitems; import android.content.Intent; import com.tencent.mm.bg.d.a; import com.tencent.mm.g.a.ch; import com.tencent.mm.pluginsdk.model.e; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.chatting.viewitems.aa.c; class aa$c$1 implements a { final /* synthetic */ c udq; aa$c$1(c cVar) { this.udq = cVar; } public final void onActivityResult(int i, int i2, Intent intent) { switch (i) { case 2002: if (intent == null) { x.e("MicroMsg.LocationClickListener", "[onActivityResult] null == data, requestCode:%s resultCode:%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); return; } else if (intent.getBooleanExtra("kfavorite", false)) { ch chVar = new ch(); e.a(chVar, intent); chVar.bJF.nd = c.a(this.udq).tTq; chVar.bJF.bJM = 42; com.tencent.mm.sdk.b.a.sFg.m(chVar); return; } else { return; } default: return; } } }
package com.bluemingo.bluemingo.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.bluemingo.bluemingo.domain.SearchVO; import com.bluemingo.bluemingo.domain.UserVO; import com.bluemingo.bluemingo.generic.GenericDAO; import com.bluemingo.bluemingo.generic.GenericServiceImpl; import com.bluemingo.bluemingo.persistence.UserDAO; @Service("userService") public class UserServiceImpl extends GenericServiceImpl<UserVO, Integer> implements UserService, UserDetailsService{ private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserDAO userDao; public UserServiceImpl() { } @Autowired public UserServiceImpl(@Qualifier("userDao") GenericDAO<UserVO, Integer> genericDao) { super(genericDao); this.userDao = (UserDAO) genericDao; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.info("load user by username(ID) : " + username); SearchVO svo = new SearchVO(); svo.setSearch_key(username); return userDao.search(svo).get(0); } }
package com.axis.database; import android.content.ContentResolver; import android.content.Context; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by Jason on 2016/1/23. */ public class SongListDatabase { private Context context= null; private List<Map<String, String>> mediaMaps = null; private Map<String, String> media = null; public SongListDatabase(Context context) { this.context = context; mediaMaps = new ArrayList<Map<String, String>>(); media = new HashMap<String, String>(); fun1(); } private void fun1(){ ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.TITLE}, null, null, MediaStore.Audio.Media.TITLE); if(cursor.moveToFirst()){ while (cursor.moveToNext()){ media.put(cursor.getColumnName(0), cursor.getString(0)); mediaMaps.add(media); } } } }
package com.tencent.mm.ui.base; import android.os.Looper; import android.os.Message; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.tmassistantsdk.logreport.BaseReportManager; class MMFalseProgressBar$1 extends ag { final /* synthetic */ MMFalseProgressBar tug; MMFalseProgressBar$1(MMFalseProgressBar mMFalseProgressBar, Looper looper) { this.tug = mMFalseProgressBar; super(looper); } public final void handleMessage(Message message) { switch (message.what) { case BaseReportManager.MAX_READ_COUNT /*1000*/: MMFalseProgressBar.a(this.tug); return; case 1001: MMFalseProgressBar.b(this.tug); return; case 1002: MMFalseProgressBar.c(this.tug); return; case 1003: MMFalseProgressBar.d(this.tug); return; default: return; } } }
/** * 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.util; import java.lang.reflect.InvocationTargetException; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.core.DatabaseException; import com.openkm.dao.DatabaseMetadataDAO; import com.openkm.dao.bean.DatabaseMetadataType; import com.openkm.dao.bean.DatabaseMetadataValue; import com.openkm.frontend.client.util.metadata.DatabaseMetadataMap; /** * DatabaseMetadataUtils * * @author pavila */ public class DatabaseMetadataUtils { private static Logger log = LoggerFactory.getLogger(DatabaseMetadataUtils.class); /** * Build a query */ public static String buildQuery(String table, String filter, String order) throws DatabaseException { log.debug("buildQuery({}, {}, {})", new Object[] { table, filter, order }); StringBuilder sb = new StringBuilder(); String ret = null; sb.append("from DatabaseMetadataValue dmv where dmv.table='" + table + "'"); if (filter != null && filter.length() > 0) { sb.append(" and ").append(replaceVirtual(table, filter)); } if (order != null && order.length() > 0) { sb.append(" order by ").append(replaceVirtual(table, order)); } ret = sb.toString(); log.debug("buildQuery: {}", ret); return ret; } /** * Build a query */ public static String buildQuery(String table, String filter) throws DatabaseException { log.debug("buildQuery({}, {})", new Object[] { table, filter }); StringBuilder sb = new StringBuilder(); String ret = null; sb.append("from DatabaseMetadataValue dmv where dmv.table='" + table + "'"); if (filter != null && filter.length() > 0) { sb.append(" and ").append(replaceVirtual(table, filter)); } ret = sb.toString(); log.debug("buildQuery: {}", ret); return ret; } /** * Build a query */ public static String buildUpdate(String table, String values, String filter) throws DatabaseException { log.debug("buildUpdate({}, {}, {})", new Object[] { table, values, filter }); StringBuilder sb = new StringBuilder(); String ret = null; sb.append("update DatabaseMetadataValue dmv set"); if (values != null && values.length() > 0) { sb.append(" ").append(replaceVirtual(table, values)); } sb.append(" where dmv.table='" + table + "'"); if (filter != null && filter.length() > 0) { sb.append(" and ").append(replaceVirtual(table, filter)); } ret = sb.toString(); log.debug("buildUpdate: {}", ret); return ret; } /** * Build a query */ public static String buildDelete(String table, String filter) throws DatabaseException { log.debug("buildDelete({}, {})", new Object[] { table, filter }); StringBuilder sb = new StringBuilder(); String ret = null; sb.append("delete from DatabaseMetadataValue dmv where dmv.table='" + table + "'"); if (filter != null && filter.length() > 0) { sb.append(" and ").append(replaceVirtual(table, filter)); } ret = sb.toString(); log.debug("buildDelete: {}", ret); return ret; } /** * Get virtual column string value */ public static String getString(DatabaseMetadataValue value, String column) throws DatabaseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(value.getTable()); for (DatabaseMetadataType emt : types) { if (emt.getVirtualColumn().equals(column)) { return BeanUtils.getProperty(value, emt.getRealColumn()); } } return null; } /** * Get value from id. This is a shortcut method. */ public static String getString(String table, String filter, String column) throws DatabaseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String query = DatabaseMetadataUtils.buildQuery(table, filter); DatabaseMetadataValue dmv = DatabaseMetadataDAO.executeValueQueryUnique(query); return DatabaseMetadataUtils.getString(dmv, column); } /** * Get virtual column date value */ public static Calendar getDate(DatabaseMetadataValue value, String column) throws DatabaseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(value.getTable()); for (DatabaseMetadataType emt : types) { if (emt.getVirtualColumn().equals(column)) { return ISO8601.parseBasic(BeanUtils.getProperty(value, emt.getRealColumn())); } } return null; } /** * Obtain a Map from a DatabaseMetadataValue. */ public static Map<String, String> getDatabaseMetadataValueMap(DatabaseMetadataValue value) throws DatabaseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Map<String, String> map = new HashMap<String, String>(); List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(value.getTable()); for (DatabaseMetadataType emt : types) { if (emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_ID) || emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_TABLE)) { throw new DatabaseException("Virtual column name restriction violated " + DatabaseMetadataMap.MV_NAME_ID + " or " + DatabaseMetadataMap.MV_NAME_TABLE); } map.put(emt.getVirtualColumn(), BeanUtils.getProperty(value, emt.getRealColumn())); } map.put(DatabaseMetadataMap.MV_NAME_TABLE, value.getTable()); map.put(DatabaseMetadataMap.MV_NAME_ID, String.valueOf(value.getId())); return map; } /** * Obtain a DatabaseMetadataValue from a Map */ public static DatabaseMetadataValue getDatabaseMetadataValueByMap(Map<String, String> map) throws DatabaseException, IllegalAccessException, InvocationTargetException { DatabaseMetadataValue dmv = new DatabaseMetadataValue(); if (!map.isEmpty() && map.containsKey(DatabaseMetadataMap.MV_NAME_TABLE)) { dmv.setTable(map.get(DatabaseMetadataMap.MV_NAME_TABLE)); if (map.containsKey(DatabaseMetadataMap.MV_NAME_ID)) { dmv.setId(new Double(map.get(DatabaseMetadataMap.MV_NAME_ID)).longValue()); } List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(dmv.getTable()); for (DatabaseMetadataType emt : types) { if (!emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_ID) && !emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_TABLE)) { if (map.keySet().contains(emt.getVirtualColumn())) { BeanUtils.setProperty(dmv, emt.getRealColumn(), map.get(emt.getVirtualColumn())); } } } } return dmv; } /** * Replace virtual columns by real ones */ public static String replaceVirtual(List<String> tables, String query) throws DatabaseException { String ret = query; for (String table : tables) { ret = replaceVirtual(table, ret); } return ret; } /** * Replace virtual columns by real ones */ private static String replaceVirtual(String table, String query) throws DatabaseException { log.debug("replaceVirtual({}, {})", new Object[] { table, query }); String ret = ""; if (query != null && query.length() > 0) { List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(table); // avoid the case in which one of the virtual columns is a substring of another (ex. id and admin_id) Collections.sort(types, LenComparator.getInstance()); for (DatabaseMetadataType emt : types) { String vcol = "\\$" + emt.getVirtualColumn().toLowerCase(); query = query.replaceAll(vcol, emt.getRealColumn().toLowerCase()); } ret = query; } log.debug("replaceVirtual: {}", ret); return ret; } /** * custom comparator for sorting strings by length (in descending order) * * @author danilo */ public static class LenComparator implements Comparator<DatabaseMetadataType> { public static LenComparator getInstance() { return new LenComparator(); } public int compare(DatabaseMetadataType s1, DatabaseMetadataType s2) { return s2.getVirtualColumn().length() - s1.getVirtualColumn().length(); } } }
package DPI.entity; import java.util.Date; public class Sport { private Integer id; private String exercisePlan; private Integer waterNum; private Byte isFinish; private String exerciseDate; private Byte isRun; private String openid; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getExercisePlan() { return exercisePlan; } public void setExercisePlan(String exercisePlan) { this.exercisePlan = exercisePlan == null ? null : exercisePlan.trim(); } public Integer getWaterNum() { return waterNum; } public void setWaterNum(Integer waterNum) { this.waterNum = waterNum; } public Byte getIsFinish() { return isFinish; } public void setIsFinish(Byte isFinish) { this.isFinish = isFinish; } public String getExerciseDate() { return exerciseDate; } public void setExerciseDate(String exerciseDate) { this.exerciseDate = exerciseDate; } public Byte getIsRun() { return isRun; } public void setIsRun(Byte isRun) { this.isRun = isRun; } }
package com.dazhi.authdemo.modules.auth.dao; import com.dazhi.authdemo.modules.auth.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface UserRepository extends JpaRepository<UserEntity, Integer> { UserEntity findByAccount(String account); UserEntity findByToken(String token); UserEntity findByAccountAndRoleId(String account,Integer roleId); List<UserEntity> findAllByRoleIdAndCenterId(Integer roleId,Integer centerId); List<UserEntity> findAllByRoleIdAndJxsId(Integer roleId,Long jxsId); @Query(value="SELECT center_id as centerId ,center_name as centerName ,count(center_id) as jxsNum from user_entity WHERE if(?1 !='',center_name like %?1% ,1=1) and role_id =2 GROUP BY center_id,center_name" ,nativeQuery = true) List<Object[]> getCenterList(String center_name); @Query(value="SELECT center_id,center_name,account,jxs FROM user_entity WHERE if(?1 !='',center_id=?1,1=1) and role_id =2 and if(?2 !='',account like %?2%,1=1)" ,nativeQuery = true) List<Object[]> getJxsList(String center_id,String account); @Query(value="SELECT center_id,center_name,jxs_id,jxs,account,telephone,create_time,username FROM user_entity WHERE if(?1 !='',jxs_id=?1,1=1) and role_id =3 and if(?2 !='',username like %?2%,1=1)" ,nativeQuery = true) List<Object[]> getHhrList(String jxs_id,String username); }
/** * <copyright> * </copyright> * * $Id$ */ package LanguageWorkbenchCompetition.impl; import LanguageWorkbenchCompetition.LWCModelElement; import LanguageWorkbenchCompetition.LWCPipe; import LanguageWorkbenchCompetition.LanguageWorkbenchCompetitionPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>LWC Pipe</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link LanguageWorkbenchCompetition.impl.LWCPipeImpl#getFromElement <em>From Element</em>}</li> * <li>{@link LanguageWorkbenchCompetition.impl.LWCPipeImpl#getToElement <em>To Element</em>}</li> * </ul> * </p> * * @generated */ public class LWCPipeImpl extends LWCModelElementImpl implements LWCPipe { /** * The cached value of the '{@link #getFromElement() <em>From Element</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFromElement() * @generated * @ordered */ protected LWCModelElement fromElement; /** * The cached value of the '{@link #getToElement() <em>To Element</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getToElement() * @generated * @ordered */ protected LWCModelElement toElement; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LWCPipeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EClass eStaticClass() { return LanguageWorkbenchCompetitionPackage.Literals.LWC_PIPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LWCModelElement getFromElement() { if (fromElement != null && fromElement.eIsProxy()) { InternalEObject oldFromElement = (InternalEObject)fromElement; fromElement = (LWCModelElement)eResolveProxy(oldFromElement); if (fromElement != oldFromElement) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT, oldFromElement, fromElement)); } } return fromElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LWCModelElement basicGetFromElement() { return fromElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFromElement(LWCModelElement newFromElement) { LWCModelElement oldFromElement = fromElement; fromElement = newFromElement; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT, oldFromElement, fromElement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LWCModelElement getToElement() { if (toElement != null && toElement.eIsProxy()) { InternalEObject oldToElement = (InternalEObject)toElement; toElement = (LWCModelElement)eResolveProxy(oldToElement); if (toElement != oldToElement) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT, oldToElement, toElement)); } } return toElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LWCModelElement basicGetToElement() { return toElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setToElement(LWCModelElement newToElement) { LWCModelElement oldToElement = toElement; toElement = newToElement; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT, oldToElement, toElement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT: if (resolve) return getFromElement(); return basicGetFromElement(); case LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT: if (resolve) return getToElement(); return basicGetToElement(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eSet(int featureID, Object newValue) { switch (featureID) { case LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT: setFromElement((LWCModelElement)newValue); return; case LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT: setToElement((LWCModelElement)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eUnset(int featureID) { switch (featureID) { case LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT: setFromElement((LWCModelElement)null); return; case LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT: setToElement((LWCModelElement)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean eIsSet(int featureID) { switch (featureID) { case LanguageWorkbenchCompetitionPackage.LWC_PIPE__FROM_ELEMENT: return fromElement != null; case LanguageWorkbenchCompetitionPackage.LWC_PIPE__TO_ELEMENT: return toElement != null; } return super.eIsSet(featureID); } } //LWCPipeImpl
package com.aprendoz_test.data; /** * aprendoz_test.PadresVistaPersonas * 01/19/2015 07:58:52 * */ public class PadresVistaPersonas { private PadresVistaPersonasId id; public PadresVistaPersonasId getId() { return id; } public void setId(PadresVistaPersonasId id) { this.id = id; } }
package com.sarf.web; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sarf.service.Qna_BoardService; import com.sarf.service.Qna_ReplyService; import com.sarf.vo.MemberVO; import com.sarf.vo.PageMaker; import com.sarf.vo.Qna_BoardVO; import com.sarf.vo.Qna_ReplyVO; import com.sarf.vo.SearchCriteria; @Controller @RequestMapping("/qna_board/*") public class Qna_BoardController { private static final Logger logger = LoggerFactory.getLogger(BoardController.class); @Inject Qna_BoardService service; @Inject Qna_ReplyService replyService; // 게시판 목록 조회 @RequestMapping(value = "/faq", method = RequestMethod.GET) public String list() throws Exception{ logger.info("박수빈"); return "/qna_board/faq"; } // 게시판 목록 조회 @RequestMapping(value = "/qna_list", method = RequestMethod.GET) public String list(Qna_BoardVO boardVO, Model model, @ModelAttribute("scri") SearchCriteria scri) throws Exception{ logger.info("박수빈"); model.addAttribute("list",service.list(scri)); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(scri); model.addAttribute("pageMaker", pageMaker); return "/qna_board/qna_list"; } // 게시판 글 작성 화면 @RequestMapping(value = "/qna_board/qna_writeView", method = RequestMethod.GET) public void writeView() throws Exception{ logger.info("작성화면"); } // 게시판 글 작성 @RequestMapping(value="/qna_board/qna_write", method = RequestMethod.POST) public String write(Qna_BoardVO boardVO, HttpSession session) throws Exception { logger.info("작성완료"); MemberVO memberVO = (MemberVO) session.getAttribute("member"); String boardId = memberVO.getId(); boardVO.setName(boardId); service.write(boardVO); return "redirect:/qna_board/qna_list"; } // 게시물 조회 @RequestMapping(value = "/qna_view", method = RequestMethod.GET) public String read(Qna_BoardVO boardVO, Qna_ReplyVO replyVO, @ModelAttribute("scri") SearchCriteria scri, Model model, RedirectAttributes rttr) throws Exception{ logger.info("뷰"); model.addAttribute("read", service.read(boardVO.getBno())); if (replyVO.getAns() == 1) { rttr.addAttribute("anwser", true); } else if(replyVO.getAns() == 0) { rttr.addAttribute("anwser", false); } List<Qna_ReplyVO> replyList = replyService.readReply(boardVO.getBno()); model.addAttribute("replyList", replyList); return "qna_board/qna_view"; } // 게시물 수정뷰 @RequestMapping(value = "/qna_updateView", method = RequestMethod.GET) public String updateView(Qna_BoardVO boardVO, Model model) throws Exception{ logger.info("없데이트뷰"); model.addAttribute("update", service.read(boardVO.getBno())); return "qna_board/qna_updateView"; } }
package com.medic.quotesbook.services; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.util.Log; import com.medic.quotesbook.receivers.QuoteTimeReceiver; import com.medic.quotesbook.utils.DevUtils; import com.medic.quotesbook.utils.TodayQuoteManager; /** * Created by capi on 15/05/15. */ public class GlueQuotesService extends IntentService{ public final String TAG = "GlueQuoteService"; public static final String QUOTES_QUEUE_FILE = "quotes_queue"; public GlueQuotesService() { super("GlueQuotesService"); } @Override protected void onHandleIntent(Intent intent) { //DevUtils.showNotification("Llegaron citas", this.getBaseContext()); Log.d(TAG, "Se activa el servicio de recepción de citas."); Bundle extras = intent.getExtras(); String rawQuotes = extras.getString("quotes"); if ( rawQuotes != null){ TodayQuoteManager qManager = new TodayQuoteManager(getBaseContext()); qManager.changeQuotesList(rawQuotes); Log.d(TAG, "Se actualizó el listado de citas."); } // TODO: Test for remove QuoteTimeReceiver.setQuoteTimeAlarm(getBaseContext()); } }
package com.example.didiorder.presenter; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Environment; import com.example.didiorder.biz.DishesBiz; import com.example.didiorder.biz.IDishesBiz; import com.example.didiorder.event.UserEvent; import com.example.didiorder.tools.UtilityTool; import com.example.didiorder.view.IUploadView; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import de.greenrobot.event.EventBus; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by qqq34 on 2016/1/19. */ public class UploadActivityPresenter { private IDishesBiz iDishesBiz; private IUploadView iUploadView; private File tempFile; public UploadActivityPresenter(IUploadView iUploadView) { this.iDishesBiz =new DishesBiz(); this.iUploadView = iUploadView; } public void setImageUri(){ iUploadView.setImageUri(Uri.fromFile(tempFile)); } public void setImageUri(Uri uri){ iUploadView.setImageUri(uri); } public String getPhotoFileName() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat( "'IMG'_yyyyMMdd_HHmmss"); return dateFormat.format(date) + ".jpg"; } public void startPhotoZoom(Uri uri) { tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName()); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("output", Uri.fromFile(tempFile)); intent.putExtra("outputX", 100); intent.putExtra("outputY", 100); intent.putExtra("return-data", true); intent.putExtra("noFaceDetection", true); System.out.println("22================"); iUploadView.startCutActivity(intent); } public void updata(Context context, String name , Integer price){ if (!UtilityTool.fileIsExists(tempFile)){ tempFile=null; } iUploadView.setViewEnable(false); iUploadView.showLoading(); iDishesBiz.updata(context,name,price,tempFile) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(dishes -> { iUploadView.setViewEnable(true); iUploadView.hideLoading(); iUploadView.toMainActivity(dishes); },throwable -> { iUploadView.setViewEnable(true); iUploadView.showFailedError(throwable.getLocalizedMessage()); iUploadView.hideLoading(); }); } }
package com.github.jangalinski.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.IOException; @EnableConfigServer @EnableEurekaClient @SpringBootApplication public class ConfigServiceApplication { public static void main(String[] args) { SpringApplication.run(ConfigServiceApplication.class, args); } @Bean InfoContributor infoContributor() { return builder -> { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { for (Resource r : resolver.getResources("classpath:configuration/*.yml")) { builder.withDetail(r.getFilename(), "/" + r.getFilename().replaceAll("\\.yml","") + "/native"); } } catch (IOException e) { throw new RuntimeException(e); } }; } }
package com.app.artclass.fragments; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.app.artclass.Logger; import com.app.artclass.R; import com.app.artclass.database.entity.GroupType; import com.app.artclass.database.entity.Student; import com.app.artclass.fragments.dialog.AddToGroupDialog; import com.app.artclass.fragments.dialog.DialogCreationHandler; import com.app.artclass.recycler_adapters.GroupRedactorAdapter; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.time.LocalDate; import java.util.List; /** * A simple {@link Fragment} subclass. */ @RequiresApi(api = Build.VERSION_CODES.O) public class GroupRedactorFragment extends Fragment { private GroupType mGroupType; private final List<Student> mStudentsList; public GroupRedactorFragment(@NonNull GroupType groupType, List<Student> students) { this.mGroupType = groupType; mStudentsList = students; Logger.getInstance().appendLog(getClass(),"init fragment"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_group_redactor, container, false); // set date and time TextView groupNameText = view.findViewById(R.id.group_name_view); Button checkAbsentBtn = view.findViewById(R.id.check_absent_btn); TextView studentsAmountTextView = view.findViewById(R.id.students_count_view); groupNameText.setText(mGroupType.getName()); GroupRedactorAdapter groupRedactorAdapter = new GroupRedactorAdapter( this, R.layout.item_all_students_list, R.id.name_view, R.id.balance_view, studentsAmountTextView, mGroupType, mStudentsList); RecyclerView groupLessonsListView = view.findViewById(R.id.group_redactor_list); groupLessonsListView.setLayoutManager(new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false)); groupLessonsListView.setAdapter(groupRedactorAdapter); checkAbsentBtn.setOnClickListener(v -> getFragmentManager().beginTransaction().replace(R.id.main_content_id, new StudentsPresentList(LocalDate.now(), mGroupType, mStudentsList)).addToBackStack(null).commit()); FloatingActionButton btn_add_dialog = view.findViewById(R.id.fab_add_students); btn_add_dialog.setOnClickListener(v ->{ AddToGroupDialog addToGroupDialog = new AddToGroupDialog(groupRedactorAdapter, mGroupType, groupRedactorAdapter.getStudents()); addToGroupDialog.show(getFragmentManager(), "AddToGroupDialog"); }); FloatingActionButton btn_delete_selected = view.findViewById(R.id.fab_delete_selected); btn_delete_selected.setOnClickListener(v -> groupRedactorAdapter.deleteCheckedItems()); return view; } }
import java.io.*; import java.util.ArrayList; /** * Main Execution of the Comparator starts at this Class. */ public class RunComparator{ public static final String DEFAULT_CONFIG_FILE_PATH = "./target/comparator.config"; /** * Runs the Comparator on the Given paths * @param pathOriginalFile Path to the folder of original files convered by V0 (generated folder) * @param pathRoundtrippedFile Path to the folder of Roundtripped files convered by V0 (generated folder) * @param outputPath Path to generate the Reports and Diffs at */ public static void runComparator(String pathOriginalFile, String pathRoundtrippedFile, String outputPath) { DiffGenerator diffGenerator = new DiffGenerator(pathOriginalFile, pathRoundtrippedFile, outputPath); try { diffGenerator.prepareFolderRequired(); diffGenerator.prepareFolderAndRun(); } catch (Exception e) { StatusLogger.addRecordWarningExec(e.getMessage()); } } /** * The Main execution of the comparator starts here. * @param args Pass in the path of Config File. */ public static void main(String[] args) { try{ File fileConfigPath; if(args.length==0) { fileConfigPath = new File(DEFAULT_CONFIG_FILE_PATH); }else{ fileConfigPath = new File(args[0]); } FileReader fileReader=new FileReader(fileConfigPath); BufferedReader bufferedReader=new BufferedReader(fileReader); ArrayList<String> Contents = new ArrayList<>(); String lineData; while((lineData=bufferedReader.readLine())!=null){ Contents.add(lineData); } fileReader.close(); runComparator(Contents.get(0),Contents.get(1),Contents.get(2)); }catch(IOException e) { StatusLogger.addRecordWarningExec(e.getMessage()); } } }
package com.sds.chocomuffin.molly.domain.category; public enum ItemType { CATEGORY, QUESTION, NONE }
/** * original(c) zhuoyan company * projectName: java-design-pattern * fileName: Control.java * packageName: cn.zy.pattern.observer * date: 2018-12-27 20:25 * history: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package cn.zy.pattern.observer; import java.util.ArrayList; import java.util.List; /** * @version: V1.0 * @author: ending * @className: Control * @packageName: cn.zy.pattern.observer * @description: * @data: 2018-12-27 20:25 **/ public abstract class Control { protected List<Observer> list = new ArrayList<>(); public void add(Observer observer){ list.add(observer); } public void remove(Observer observer){ list.remove(observer); } public abstract void startNotify(); }
import java.util.Scanner; public class LandTractDemo { public static void main(String[] args) { double length; double width; Scanner key = new Scanner(System.in); System.out.print("Enter the length of tract 1: "); length = key.nextDouble(); System.out.print("Enter the width of tract 1: "); width = key.nextDouble(); LandTract tractOne = new LandTract(length, width); System.out.print("Enter the length of tract 2: "); length = key.nextDouble(); System.out.print("Enter the width of tract 2: "); width = key.nextDouble(); LandTract tractTwo = new LandTract(length, width); System.out.println("Tract One"); System.out.println(tractOne); System.out.println("Tract Two"); System.out.println(tractTwo); if(tractOne.getArea() == tractTwo.getArea()) System.out.println("Tract One and Tract Two are equal in area" ); else System.out.println("Tract one and two are NOT the same size"); } }