text
stringlengths 10
2.72M
|
|---|
package Utility;
public class BasePage extends DriverFactory {
}
|
package cn.bs.zjzc.presenter;
import cn.bs.zjzc.model.IWithdrawDetailModel;
import cn.bs.zjzc.model.callback.HttpTaskCallback;
import cn.bs.zjzc.model.impl.WithdrawDetailModel;
import cn.bs.zjzc.model.response.WithdrawDetailResponse;
import cn.bs.zjzc.ui.view.IWithdrawDetailView;
/**
* Created by Ming on 2016/6/16.
*/
public class WithdrawDetailPresenter {
private IWithdrawDetailView mWithdrawDetailView;
private IWithdrawDetailModel mWithdrawDetailModel;
public WithdrawDetailPresenter(IWithdrawDetailView rechargeView) {
mWithdrawDetailView = rechargeView;
mWithdrawDetailModel = new WithdrawDetailModel();
}
public void getWithdrawDetail(String p) {
mWithdrawDetailModel.getWithdrawDetail(p, new HttpTaskCallback<WithdrawDetailResponse.DataBean>() {
@Override
public void onTaskFailed(String errorInfo) {
mWithdrawDetailView.showMsg(errorInfo);
}
@Override
public void onTaskSuccess(WithdrawDetailResponse.DataBean data) {
mWithdrawDetailView.showWithdrawDetail(data);
}
});
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.internal.collector.jbossas;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.transaction.TransactionManager;
import org.overlord.commons.services.ServiceInit;
import org.overlord.rtgov.activity.collector.CollectorContext;
/**
* This class provides context information regarding the
* JBossAS7 environment for the activity collector.
*
*/
public class JBossASCollectorContext implements CollectorContext {
private static final String TRANSACTION_MANAGER = "java:jboss/TransactionManager";
private static final Logger LOG=Logger.getLogger(JBossASCollectorContext.class.getName());
private TransactionManager _transactionManager=null;
/**
* This method initializes the collector context.
*/
@ServiceInit
public void init() {
try {
InitialContext ctx=new InitialContext();
_transactionManager = (TransactionManager)ctx.lookup(TRANSACTION_MANAGER);
} catch (Exception e) {
LOG.log(Level.SEVERE, java.util.PropertyResourceBundle.getBundle(
"rtgov-jbossas.Messages").getString("RTGOV-JBOSSAS-1"), e);
}
}
/**
* {@inheritDoc}
*/
public String getHost() {
return (System.getProperty("jboss.qualified.host.name","Unknown-Host"));
}
/**
* {@inheritDoc}
*/
public String getNode() {
return (System.getProperty("jboss.node.name","Unknown-Node"));
}
/**
* {@inheritDoc}
*/
public TransactionManager getTransactionManager() {
return (_transactionManager);
}
}
|
/*
*Find the greatest common divisor of number
*and the least common multiple of number
*/
package Lab06D7;
/**
*
* @author Aliaksiej Protas
*/
public class Lab06D7 {
public static void main(String[] args) {
while (true) {
long numberfirst = UserInput.input("Input a 1 number :");
long numbersecond = UserInput.input("Input a 2 number :");
View.print("This is the greatest common divisor of number: "
+CommonDiviserCommonMultiple.findGCD(numberfirst,numbersecond));
View.print("This is the least common multiple of number: "
+CommonDiviserCommonMultiple.findLCM(numberfirst,numbersecond));
if (!Complete.complete("Do you want to continue?")) {
break;
}
}
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.modules.scripting;
import vanadis.core.lang.EqHc;
import vanadis.core.lang.ToString;
import vanadis.osgi.Reference;
import vanadis.services.scripting.ScriptingException;
import vanadis.services.scripting.ScriptingSession;
import javax.script.*;
class ScriptingSessionImpl implements ScriptingSession {
static ScriptingSessionImpl create(String name, String language, String serviceBinding,
ScriptEngineManager scriptEngineManager,
Reference<?> reference,
ScriptingSessionsImpl host) {
return new ScriptingSessionImpl(name, language,
serviceBinding, scriptEngineManager,
reference, host);
}
private final String name;
private final ScriptingSessionsImpl host;
private final String language;
private final Reference<?> reference;
private final String serviceBinding;
private final ScriptEngine scriptEngine;
private final Bindings bindings;
private ScriptingSessionImpl(String name, String language, String serviceBinding,
ScriptEngineManager scriptEngineManager,
Reference<?> reference,
ScriptingSessionsImpl host) {
this.reference = reference;
this.name = name;
this.language = language;
this.bindings = new SimpleBindings();
this.scriptEngine = scriptEngineManager.getEngineByName(language);
this.serviceBinding = bindService(serviceBinding);
this.host = host;
}
@Override
public String getName() {
return name;
}
@Override
public String getLanguage() {
return language;
}
@Override
public Object eval(String script) {
try {
return scriptEngine.eval(script, bindings);
} catch (ScriptException e) {
throw new ScriptingException("Failed to evaluate " + script, e);
}
}
@Override
public void close() {
try {
host.clearSession(name);
} finally {
if (reference != null) {
reference.unget();
}
}
}
boolean is(String name, String language) {
return this.name.equals(name) && this.language.equals(language);
}
private String bindService(String serviceBinding) {
if (this.reference == null) {
return null;
}
Object service = this.reference.getRawService();
this.bindings.put(serviceBinding, service);
this.scriptEngine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
return serviceBinding;
}
@Override
public boolean equals(Object obj) {
ScriptingSessionImpl session = EqHc.retyped(this, obj);
return session != null && EqHc.eq(name, session.name,
language, session.language);
}
@Override
public int hashCode() {
return EqHc.hc(name, language);
}
@Override
public String toString() {
return ToString.of(this, "name", name, "lang", language,
"reference", reference,
"bound to", serviceBinding);
}
}
|
package com.tencent.mm.ui.conversation;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.profile.a.c;
import com.tencent.mm.ui.conversation.EnterpriseConversationUI.a.6;
class EnterpriseConversationUI$a$6$1 implements OnCancelListener {
final /* synthetic */ c hpy;
final /* synthetic */ 6 uqB;
EnterpriseConversationUI$a$6$1(6 6, c cVar) {
this.uqB = 6;
this.hpy = cVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.hpy);
au.DF().b(1394, this.uqB.uqA);
}
}
|
package cn.canlnac.onlinecourse.data.repository.datasource;
import android.support.annotation.Nullable;
import java.util.Map;
import cn.canlnac.onlinecourse.data.entity.AnswerEntity;
import cn.canlnac.onlinecourse.data.entity.CatalogEntity;
import cn.canlnac.onlinecourse.data.entity.DocumentListEntity;
import cn.canlnac.onlinecourse.data.entity.LearnRecordEntity;
import cn.canlnac.onlinecourse.data.entity.QuestionListEntity;
import rx.Observable;
/**
* 目录数据储存.
*/
public interface CatalogDataStore {
/** 获取目录 */
Observable<CatalogEntity> getCatalog(int catalogId);
/** 修改目录 */
Observable<Void> updateCatalog(int catalogId, Map<String,Object> catalog);
/** 删除目录 */
Observable<Void> deleteCatalog(int catalogId);
/** 创建小测 */
Observable<Integer> createQuestion(int catalogId, Map<String,Object> question);
/** 更新小测 */
Observable<Void> updateQuestion(int catalogId, Map<String,Object> question);
/** 删除小测 */
Observable<Void> deleteQuestion(int catalogId);
/** 获取小测 */
Observable<QuestionListEntity> getQuestion(int catalogId);
/** 获取学习记录 */
Observable<LearnRecordEntity> getLearnRecord(int catalogId);
/** 创建学习记录 */
Observable<Integer> createLearnRecord(int catalogId, Map<String,Object> learnRecord);
/** 更新学习记录 */
Observable<Void> updateLearnRecord(int catalogId, Map<String,Object> learnRecord);
/** 创建文档 */
Observable<Integer> createDocumentInCatalog(int catalogId, Map<String,Object> document);
/** 文档列表 */
Observable<DocumentListEntity> getDocumentsInCatalog(int catalogId, @Nullable Integer start, @Nullable Integer count, @Nullable String sort);
/** 获取章节下的回答 */
Observable<AnswerEntity> getAnswer(int catalogId);
/** 创建回答 */
Observable<Integer> createAnser(int catalogId, Map<String,Object> answer);
}
|
/*
* @author 作者: qugang
* @E-mail 邮箱: qgass@163.com
* @date 创建时间:2018/8/25
* 类说明 数据以MD5算摘要,以免伪造数据
*/
package com.yada.su.epay.ApmPayTest.util;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class SignUtils {
// private static final Logger logger = LoggerFactory.getLogger(SignUtils.class);
/**
* 签名
*
* @param text 签名的数据
* @param key 签名的Key
* @return 签名值
*/
public static String sign(String text, String key) {
return DigestUtils.md5Hex(text + key);
}
/**
* 验签
*
* @param text 原数据
* @param md5 需要验签的数据
* @return 是否验证成功
*/
public static Boolean verify(String text, String md5) {
if (text.equalsIgnoreCase(md5)) {
return true;
}
return false;
}
/**
* 交易签名
*/
public static String signPay( String projectId,
String configId,
String deviceInfo,
String body,
String detail,
String attach,
String outTradeNo,
String totalFee,
String timeStart,
String timeExpire,
String goodsTag,
String productId,
String limitPay,
String openid,
String sub_mch_id,
String key) {
StringBuffer sb = new StringBuffer();
sb.append(projectId);
sb.append(configId);
sb.append(deviceInfo);
sb.append(body);
sb.append(detail);
sb.append(attach);
sb.append(outTradeNo);
sb.append(totalFee);
sb.append(timeStart);
sb.append(timeExpire);
sb.append(goodsTag);
sb.append(productId);
sb.append(limitPay);
sb.append(openid);
sb.append(sub_mch_id);
// logger.info("sign value:" + sb.toString());
// logger.info("sign key:" + key);
return sign(sb.toString(), key);
}
/**
* 查询签名
*/
public static String signQuery( String transactionId,
String outTradeNo,
String sub_mch_id,
String configId,
String projectId,
String key) {
StringBuffer sb = new StringBuffer();
sb.append(transactionId);
sb.append(configId);
sb.append(outTradeNo);
sb.append(sub_mch_id);
sb.append(projectId);
return sign(sb.toString(), key);
}
/**
* map 签名
* @param map 需要验证的数据域
* @param key 密钥
* @return 签名
*/
public static String signMap(Map<String,String> map,String key){
Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
@Override
public boolean equals(Object obj) {
return false;
}
});
sortMap.putAll(map);
StringBuffer sb = new StringBuffer();
for(Map.Entry<String,String> entry : sortMap.entrySet()) {
String value = entry.getValue();
sb.append(value);
}
return sign(sb.toString(),key);
}
/***
* map 签名验证
* @param map 需要验证的数据域
* @param md5 原签名
* @param key MD5key
* @return 验签成功失败
*/
public static Boolean verifyMap(Map<String,String> map,String md5,String key){
return verify(signMap(map,key),md5);
}
}
|
package com.liyinghua.service;
import com.github.pagehelper.PageInfo;
import com.liyinghua.entity.Collect;
public interface CollectService {
Integer addCollect(Collect col);
PageInfo<Collect> getUserCollectByUserId(Integer userId, Integer fy);
Integer del(Integer id);
}
|
package com.yoeki.kalpnay.hrporatal.Notification;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.yoeki.kalpnay.hrporatal.Login.Api;
import com.yoeki.kalpnay.hrporatal.Login.ApiInterface;
import com.yoeki.kalpnay.hrporatal.R;
import com.yoeki.kalpnay.hrporatal.setting.preferance;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class EventPastFragment extends Fragment {
RecyclerView ryc_pastevent;
List<NotificationEventModel.ListSearchCircular> arraycircularlist;
ApiInterface apiInterface;
public static EventPastFragment newInstance() {
EventPastFragment fragment = new EventPastFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pastevent, container, false);
ryc_pastevent=view.findViewById(R.id.ryc_pastevent);
arraycircularlist=new ArrayList<>();
String user_id=null;
user_id = preferance.getInstance(getActivity()).getUserId();
pastnotification(user_id,"P");
return view;
}
public void pastnotification(String UserId,String flag){
arraycircularlist.clear();
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(false); // set cancelable to false
progressDialog.setMessage("Please Wait"); // set message
progressDialog.show(); // show progress dialogTitle
apiInterface= Api.getClient().create(ApiInterface.class);
NotificationEventModel user = new NotificationEventModel(UserId,flag);
Call<NotificationEventModel> call1 = apiInterface.notificationevent(user);
call1.enqueue(new Callback<NotificationEventModel>() {
@Override
public void onResponse(Call<NotificationEventModel> call, Response<NotificationEventModel> response) {
NotificationEventModel user1 = response.body();
progressDialog.dismiss();
String str=user1.getMessage();
String status=user1.getStatus();
arraycircularlist=user1.getListSearchCircular();
if (status.equals("Success")){
ryc_pastevent.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
// rec_leavereqattachment.setLayoutManager(new Hori);
ryc_pastevent.setItemAnimator(new DefaultItemAnimator());
EventAdapter adapter=new EventAdapter(getActivity(),arraycircularlist);
ryc_pastevent.setAdapter(adapter);
}else {
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<NotificationEventModel> call, Throwable t) {
call.cancel();
Toast.makeText(getActivity(), "somthing went wrong", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
|
package com.h86355.tastyrecipe.requests;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.h86355.tastyrecipe.models.FeedCollection;
import com.h86355.tastyrecipe.models.RecipeCollection;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.h86355.tastyrecipe.utils.Constants.BASE_URL;
public class ServiceGenerator {
private static OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
private static OkHttpClient okHttpClient = okHttpClientBuilder
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder()
.addHeader("x-rapidapi-key", "43c215aa23mshce137b8289cf71bp1f3b10jsn972963aad7f4")
.addHeader("x-rapidapi-host", "tasty.p.rapidapi.com");
return chain.proceed(newRequest.build());
}
}).build();
private static Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = retrofitBuilder.build();
private static RequestAPI requestAPI = retrofit.create(RequestAPI.class);
public static RequestAPI getRequestAPI() {
return requestAPI;
}
}
|
package com.geekhelp.entity;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* Created by V.Odahovskiy.
* Date 09.02.2015
* Time 17:24
* Package com.geekhelp.entity
*/
@Entity
public class Comment {
@Id @GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
private User author;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
private Question question;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
private Answer answer;
@Temporal(TemporalType.TIMESTAMP)
private Date addedAt;
@NotBlank @Length(min=5)
private String text;
public Comment() {
addedAt = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
public Answer getAnswer() {
return answer;
}
public void setAnswer(Answer answer) {
this.answer = answer;
}
public Date getAddedAt() {
return addedAt;
}
public void setAddedAt(Date addedAt) {
this.addedAt = addedAt;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package com.zadu.nightout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
public class WalkthroughNamePlanActivity extends ActionBarActivity {
private Button mButton;
private EditText mEditText;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_new_plan);
mEditText = (EditText) findViewById(R.id.new_name);
mButton = (Button) findViewById(R.id.finish_button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyOpenHelper sqlHelper = MyOpenHelper.getInstance(getApplication());
sqlHelper.insertNewPlan(mEditText.getText().toString());
sqlHelper.deletePlan("My First Plan");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(WalkthroughNamePlanActivity.this);
preferences.edit().putString("first_time", "false").apply();
Intent intent = new Intent(WalkthroughNamePlanActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (charSequence.length() > 0) {
mButton.setEnabled(true);
} else {
mButton.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
|
package br.com.pcmaker.service;
import java.util.List;
import javax.transaction.Transactional;
import br.com.pcmaker.entity.AcompanhamentoOrdemServico;
public interface AcompanhamentoOrdemServicoService extends CrudService<AcompanhamentoOrdemServico>{
@Transactional
AcompanhamentoOrdemServico salvar(Integer idOrdemServico, String texto);
List<AcompanhamentoOrdemServico> query(Integer idOrdemServico);
}
|
package com.qd.mystudy.tools;
import com.taobao.common.tfs.DefaultTfsManager;
import com.taobao.tair.impl.DefaultTairManager;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liqingdong911 on 2015/3/9.
*/
public class TairTool {
static class ComplexObject implements Serializable{
// private static final long serialVersionUID = -2174256850832836137L;
// private static final long serialVersionUID = 1;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
public String getS2() {
return s2;
}
public void setS2(String s2) {
this.s2 = s2;
}
public void print(){
System.out.print(toString());
}
@Override
public String toString() {
return "ComplexObject{" +
"s1='" + s1 + '\'' +
", s2='" + s2 + '\'' +
", a=" + a +
'}';
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
private String s1;
private String s2;
private int a;
}
public static void main(String[] args){
InputStream is = TairTool.class.getClassLoader().getResourceAsStream("tools.properties");
try {
System.out.println(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
List<String> confServers = new ArrayList<String>();
confServers.add("10.0.128.118:5198");
//confServers.add("CONFIG_SERVER_ADDREEE_2:PORT");
DefaultTairManager tairManager = new DefaultTairManager();
tairManager.setConfigServerList(confServers);
tairManager.setGroupName("p_group1");
tairManager.setTimeout(5000);
tairManager.init();
int ns = 0;
ComplexObject complexObject = new ComplexObject();
complexObject.setS1("s1");
complexObject.setS2("s2");
complexObject.setA(100);
System.out.println(tairManager.put(ns, "123", complexObject, 0));
System.out.println(tairManager.get(ns, "123"));
tairManager.close();
System.exit(0);
}
}
|
package at.porscheinformatik.sonarqube.licensecheck.webservice.configuration;
public final class ProjectLicenseConfiguration
{
public static final String PARAM_PROJECT_KEY = "projectKey";
public static final String PARAM_LICENSE = "license";
public static final String PARAM_STATUS = "status";
public static final String CONTROLLER = "api/projectLicenses";
public static final String SHOW_ACTION = "show";
public static final String DELETE_ACTION = "delete";
public static final String ADD_ACTION = "add";
public static final String EDIT_ACTION = "edit";
public static final String SHOW_ACTION_DESCRIPTION = "Show Project Licenses";
public static final String DELETE_ACTION_DESCRIPTION = "Delete Project Licenses";
public static final String ADD_ACTION_DESCRIPTION = "Add Project Licenses";
public static final String EDIT_ACTION_DESCRIPTION = "Edit Project Licenses";
public static final String PROPERTY_NEW_LICENSE = "newLicense";
public static final String PROPERTY_NEW_STATUS = "newStatus";
public static final String PROPERTY_NEW_PROJECT_KEY = "newProjectKey";
public static final String PROPERTY_OLD_LICENSE = "oldLicense";
public static final String PROPERTY_OLD_STATUS = "oldStatus";
public static final String PROPERTY_OLD_PROJECT_KEY = "oldProjectKey";
public static final String PROPERTY_LICENSE = "license";
public static final String PROPERTY_STATUS = "status";
public static final String PROPERTY_PROJECT_KEY = "projectKey";
public static final String ERROR_EDIT_ALREADY_EXISTS =
"Edit Project License aborted. Project license already exists!";
public static final String ERROR_EDIT_INVALID_INPUT = "Failed to edit project license , due to invalid input: ";
public static final String INFO_EDIT_SUCCESS = "Project license edited";
public static final String ERROR_ADD_ALREADY_EXISTS =
"Add Project license aborted. Project license already exists!";
public static final String ERROR_ADD_INVALID_INPUT = "Failed to add project license , due to invalid input: ";
public static final String INFO_ADD_SUCCESS = "Project license added: ";
public static final String ERROR_DELETE_INVALID_INPUT =
"Failed to delete project license, due to invalid identifier: ";
public static final String INFO_DELETE_SUCCESS = "Project license deleted: ";
}
|
package com.yida.design.decorator.abs;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年3月19日 下午5:39:55
***********************
*/
public abstract class AbstractSchoolReport {
// 成绩单主要展示的就是你的成绩情况
public abstract void report();
// 成绩单要家长签字,这个是最要命的
public abstract void sign(String name);
}
|
package com.example.smn_arggregator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button hastags_btn = findViewById(R.id.hastagBtn);
Button posts_btn = findViewById(R.id.postBtn);
Button story_btn = findViewById(R.id.storyBtn);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Button buttonClicked = (Button)view;
String BtnText = (String) buttonClicked.getText();
if(BtnText.equals("Trending Hastags")){
Log.d("Bull",BtnText);
Intent intent = new Intent(MainActivity.this,Hashtags_Activity.class);
startActivity(intent);
}
else if(BtnText.equals("Post")){
Intent intent = new Intent(MainActivity.this,Post_Activity.class);
startActivity(intent);
}else if(BtnText.equals("Story")){
Intent intent = new Intent(MainActivity.this,Story_Activity.class);
startActivity(intent);
}
}
};
hastags_btn.setOnClickListener(listener);
posts_btn.setOnClickListener(listener);
story_btn.setOnClickListener(listener);
}
}
|
package com.coalesce;
import com.coalesce.plugin.CoPlugin;
import static org.bukkit.plugin.ServicePriority.Normal;
public class Core extends CoPlugin {
private static Core instance;
private CoreConfig config;
@Override
public void onPluginEnable() {
getServer().getServicesManager().register(Core.class, this, this, Normal);
this.config = new CoreConfig(this);
//TODO: Remove this
updateCheck("Project-Coalesce", "Core", true); //This is an example, this will be changed back once we get the updater working
}
@Override
public void onPluginDisable() {
instance = null;
}
/**
* Grabs the instance of the core.
* Make sure you don't call this before nor after {@link #onPluginDisable()}.
*
* @return The core instance.
*/
public static Core getInstance() {
return instance;
}
/**
* Gets the core configuration.
*
* @return The core config.
*/
public CoreConfig getCoreConfig() {
return config;
}
private <M> M checkCoreEnabled(M instance) {
if (!isEnabled()) {
throw new IllegalStateException("Core plugin is not enabled");
}
return instance;
}
}
|
package com.chaturvediji.customer;
public class CustomerAddition {
String id;
String name;
String age;
String gender;
String contact;
String address;
public CustomerAddition() {
}
public CustomerAddition(String id, String name, String age, String gender, String contact, String address) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.contact = contact;
this.address = address;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getContact() {
return contact;
}
public String getAddress() {
return address;
}
}
|
/*
* 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 eldershop;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
/**
*
* @author Admin
*/
public class Customer extends User{
private String address,district;
private Timestamp regDate;
private String IP;
private Timestamp lastLogin;
private int activate;
public Customer(int ID,String firstName, String lastName, String email, String city, Date dob, int phoneNumber, int zipCode, String gender,String address, String district,Timestamp regDate,Timestamp lastLogin,String IP,int activate) {
super(ID,firstName, lastName, email, city, dob, phoneNumber, zipCode, gender);
this.address=address;
this.district=district;
this.regDate=regDate;
this.IP=IP;
this.lastLogin=lastLogin;
this.activate=activate;
}
public String getAddress(){
return address;
}
public String getDistrict(){
return district;
}
public String getIP(){
return IP;
}
public Timestamp getRegDate(){
return regDate;
}
public Timestamp getLastLogin(){
return lastLogin;
}
public int getActivate(){
return activate;
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import processing.sound.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Sample extends PApplet {
/*
This is a sound file player.
*/
SoundFile soundfile;
public void setup() {
background(255);
//Load a soundfile
soundfile = new SoundFile(this, "vibraphon.aiff");
// These methods return useful infos about the file
println("SFSampleRate= " + soundfile.sampleRate() + " Hz");
println("SFSamples= " + soundfile.frames() + " samples");
println("SFDuration= " + soundfile.duration() + " seconds");
// Play the file in a loop
soundfile.loop();
}
public void draw() {
// Map mouseX from 0.25 to 4.0 for playback rate. 1 equals original playback
// speed 2 is an octave up 0.5 is an octave down.
soundfile.rate(map(mouseX, 0, width, 0.25f, 4.0f));
// Map mouseY from 0.2 to 1.0 for amplitude
soundfile.amp(map(mouseY, 0, width, 0.2f, 1.0f));
// Map mouseY from -1.0 to 1.0 for left to right
soundfile.pan(map(mouseY, 0, width, -1.0f, 1.0f));
}
public void settings() { size(640,360); }
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "--present", "--window-color=#666666", "--stop-color=#cccccc", "Sample" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
package com.personal.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.personal.model.MemberDTO;
@Repository
public class MemberDAO {
@Autowired
private SqlSession sqlSession;
private String ns = "Member."; // namespace
public boolean addMember(MemberDTO member) throws Exception {
sqlSession.insert(ns + "addMember", member);
return true;
}
public int sameCheckId(MemberDTO member) throws Exception {
return sqlSession.selectOne(ns + "sameCheckId", member);
}
public MemberDTO selectMemberLogin(MemberDTO member) throws Exception {
return sqlSession.selectOne(ns + "selectMemberLogin", member);
}
public MemberDTO selectMemberActive(MemberDTO member) throws Exception {
return sqlSession.selectOne(ns + "selectMemberActive", member);
}
public void updateMemberActive(String memberId) throws Exception {
sqlSession.update(ns + "updateMemberActive", memberId);
}
public MemberDTO selectMemberLoginInfo(String memberId) throws Exception {
return sqlSession.selectOne(ns + "selectMemberLoginInfo", memberId);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package talaash.preprocessing;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
*
* @author asheesh
*/
public class PreProcess {
public String path;
public PreProcess(String indexingpath)
{
path=indexingpath;
}
public void starthistogramcal() throws ClassNotFoundException
{
try{
Colorprocessing cpobj=new Colorprocessing(path);
cpobj.ComputeHistogram();
System.out.println("1");
FileOutputStream fos=new FileOutputStream(new File("C:/Users/asheesh/Documents/NetBeansProjects/Talaash/abcd.txt"));
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(cpobj.histogram());
cpobj.setnull("rgb");
fos.close();
oos.close();
FileOutputStream foss=new FileOutputStream(new File("C:/Users/asheesh/Documents/NetBeansProjects/Talaash/gray.txt"));
ObjectOutputStream ooss=new ObjectOutputStream(foss);
ooss.writeObject(cpobj.getgray());
cpobj.setnull("pixelgray");
foss.close();
ooss.close();
System.out.println("2");
}
catch (IOException ioe)
{
System.out.println(ioe);
}
finally
{
// System.out.println("saale");
}
}
public void setpath(String indexingpath) throws FileNotFoundException, IOException
{
String pathsent=indexingpath;
FileOutputStream fos=new FileOutputStream(new File("C:/Users/asheesh/Documents/NetBeansProjects/Talaash/indexingpath.txt"));
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(pathsent);
fos.close();
oos.close();
}
}
|
package com.neuedu.util;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;
public class CookieUtil {
public static Map<String,Cookie> getCookie(Cookie[] cookies){
Map<String,Cookie> map = new HashMap<>();
if (cookies != null){
for (Cookie c:cookies
) {
map.put(c.getName(),c);
}
}
return map;
}
}
|
package desigpattern.observer;
public class Sms implements NotifyObserve {
@Override
public boolean sendMsg() {
System.out.println("send sms");
return true;
}
}
|
package com.sysh.service.impl;
import com.sysh.mapper.SubmitMapper;
import com.sysh.service.SubmitService;
import com.sysh.util.ResultData;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by sjy Cotter on 2018/8/23.
*/
@Service
public class SubmitServiceImpl implements SubmitService {
@Autowired
private SubmitMapper submitMapper;
@Override
public ResultData submitData(Map<String,String> map) {
if(map.get("helpNumber")==null || map.get("year")==null)
{
return ResultData.returnResultData(ResultData.DATA_MISS,"参数错误");
}
List<Map> list=submitMapper.submitData(map);
if(list==null )
{
return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"暂无数据");
}
return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",list);
}
@Override
public ResultData submitEight(String helpNumber) {
if(helpNumber==null)
{
return ResultData.returnResultData(ResultData.DATA_MISS,"参数不足");
}
//查找到主要的东西
List<Map> list=submitMapper.submitEight(helpNumber);
for(int i=0;i<list.size();i++)
{
Map map=list.get(i);
Map mapUpdate=new HashMap();
mapUpdate.put("table",map.get("TABLE_NAME"));
mapUpdate.put("id",map.get("EIGHT_ID"));
Map mapName=submitMapper.eightName(mapUpdate);
//得到每一个的信息
if("tbl_bottom_disabled".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("NAME"));
}
else if("tbl_bottom_guarantee_civil".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("POVERTY_NAME"));
}
else if("tbl_ecological_poverty".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("POVERTY_NAME"));
}
else if("tbl_education".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("NAME"));
}
else if("tbl_employment".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("EMPLOY_NAME"));
}
else if("tbl_finance".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("NAME"));
}
else if("tbl_health".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("NAME"));
}
else if("tbl_idst_projway".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("HOLDER_NAME"));
}
else if("tbl_immigrant_relocation".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("POVERTY_NAME"));
}
else if("tbl_reconst_danger".equals(map.get("TABLE_NAME")))
{
map.put("name",mapName.get("POVERTY_NAME"));
}
}
return ResultData.returnResultData(ResultData.RESULT_SUCCESS,"ok",list);
}
}
|
package capturescreenshot;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import library.Utility;
public class Facebookscreenshot
{
@Test
public void captureScreenshot() throws Exception
{
WebDriver driver=new FirefoxDriver();
driver.get("http://facebook.com");
Utility.capturescreenshot(driver, "Browserstarted");
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys("manishmishralive");
Utility.capturescreenshot(driver, "TypeUname");
System.out.println("Screenshot taken successfully");
driver.quit();
}
}
|
package Concurrency.ToastMake;/**
* Created by pc on 2018/2/27.
*/
/**
* describe:
*
* @author xxx
* @date4 {YEAR}/02/27
*/
public class Jammer implements Runnable {
private ToastQueue butterqueue,finishqueue;
public Jammer(ToastQueue butterqueue, ToastQueue finishqueue) {
this.butterqueue = butterqueue;
this.finishqueue = finishqueue;
}
public void run() {
try{
while(!Thread.interrupted()){
Toast t = butterqueue.take();
t.jam();
System.out.println(t);
finishqueue.put(t);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("jam off");
}
}
|
/**
* create two pointer, travel the two list. if their tails are different,
* return false.
* else, compute the how many nodes that the longer list more than shorter list.
* set two pointer at the start of two list
* make the longer pointer advance by different length
* the two pointer travel their own list together until they meet.
*/
public class Solution07 {
public linkedNode findintersection(linkedNode list1, linkedNode list2) {
// TODO Auto-generated method stub
if (list1 == null || list2 == null)
return null;
int size1 = 1;
int size2 = 1;
linkedNode tail1 = list1;
linkedNode tail2 = list2;
while (tail1.next != null) {
tail1 = tail1.next;
size1++;
}
while (tail2.next != null) {
tail2 = tail2.next;
size2++;
}
// if their tails are different, return null
if(tail1 != tail2)
return null;
linkedNode longer = size1 < size2 ? list2 : list1;
linkedNode shorter = size1 < size2 ? list1 : list2;
// longer advance move
int k = Math.abs(size1 - size2);
while (k > 0 && longer != null) {
longer = longer.next;
k--;
}
// find the intersecting
while (longer != shorter) {
longer = longer.next;
shorter = shorter.next;
}
return longer;
}
}
|
package com.bytedance.sandboxapp.c.a.b.a.a;
import com.bytedance.sandboxapp.a.a.c.s;
import com.bytedance.sandboxapp.a.a.d.a;
import com.bytedance.sandboxapp.c.a.a.a;
import com.bytedance.sandboxapp.c.a.b;
import com.bytedance.sandboxapp.protocol.service.a.a.a;
import com.bytedance.sandboxapp.protocol.service.a.a.a.a;
import com.bytedance.sandboxapp.protocol.service.a.a.a.b;
import com.bytedance.sandboxapp.protocol.service.api.entity.a;
public final class d extends s {
public d(b paramb, a parama) {
super(paramb, parama);
}
public final void a(s.a parama, a parama1) {
a a1 = (a)((a)this).context.getService(a.class);
if (a1 == null || !a1.isSupportDxppManager()) {
a();
return;
}
b b1 = new b();
b1.a = parama.b.longValue();
b1.b = parama.c;
b1.c = parama.d;
b1.d = parama.e;
b1.e = parama.f;
b1.f = parama.g;
b1.g = parama.h;
b1.h = parama.i;
b1.i = parama.j;
Integer integer = parama.k;
byte b = 0;
if (integer != null) {
i = parama.k.intValue();
} else {
i = 0;
}
b1.j = i;
int i = b;
if (parama.l != null)
i = parama.l.intValue();
b1.k = i;
if (parama.m != null) {
String str = parama.m.toString();
} else {
parama = null;
}
b1.l = (String)parama;
a1.subscribeAppAd(b1, new a(this, parama1) {
});
callbackOk(null);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\c\a\b\a\a\d.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package voting;
import java.util.List;
@SuppressWarnings("checkstyle:typename")
public interface DB_VotingManagement extends VotingObserver {
/**
* Adds a new, already finished, {@link Voting} to the database.
*
* @param v The {@link Voting} to be added.
*
* @return True, iff the {@link Voting} was successfully added.
*/
boolean addVoting(Voting v);
/**
* Reconstructs a given {@link Voting} from the database.
*
* @param ID The ID of the {@link Voting}.
*
* @return the reconstructed {@link Voting}.
*/
Voting getVoting(int ID);
/**
* @return a list of all reconstructed {@link Voting}s from the database.
*/
List<Voting> getVotings();
}
|
package spoofax.core.cmd.command;
import org.metaborg.core.MetaborgException;
public interface ICommand {
boolean validate();
int run() throws MetaborgException;
}
|
package com.mcf.service;
import java.util.Map;
import com.mcf.base.common.page.Pager;
import com.mcf.base.common.service.IBaseService;
import com.mcf.base.exception.BaseException;
import com.mcf.base.pojo.Copartner;
/**
* Title. <br>
* Description.
* <p>
* Copyright: Copyright (c) 2016年12月17日 下午2:46:31
* <p>
* Author: 10003/sunaiqiang saq691@126.com
* <p>
* Version: 1.0
* <p>
*/
public interface ICopartnerService extends IBaseService<Copartner> {
/**
* 根据对象id修改是否已经联系客户
*
* @param id
* @param isContact
* @return
*/
public boolean updateIsContact(String id, Byte isContact);
/**
* 获取所有合伙人信息列表
*
* @param parameter
* @param pager
* @return
* @throws BaseException
*/
public Map<String, Object> getCopartnerList(Map<String, Object> parameter,
Pager pager) throws BaseException;
/**
* 根据对象id添加备注
*
* @param id
* @param remark
* @return
*/
public boolean updateRemark(String id, String remark);
/**
* 申请合伙人
*
* @param copartner
* 合伙人对象
* @return
*/
public boolean addCopartner(Copartner copartner);
}
|
package com;
import java.sql.*;
public class Hospital {
Connection conn = null;
public Hospital() {
String url = "jdbc:mysql://localhost:3306/pafhospitalmanagementdb2020?autoReconnect=true&useSSL=false";
String userName = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
System.out.println("DB Connected..");
}
catch(Exception e) {
System.out.println(e);
System.out.println("Faild DB..");
}
}
public String getHospitals() {
String returnString = "";
if ( conn == null)
{
return "Can not connect with database";
}
returnString = "<table class='table table-dark'> " +
" <tr> <th> Hospital ID </th> " +
" <th> Hospital Name </th> " +
" <th> Address </th> " +
" <th> Contact Num </th> " +
" <th> Charges </th> " +
" <th> Update </th> " +
" <th> Remove </th> </tr>";
String QUERY = "SELECT * FROM Hospitals";
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(QUERY);
while( rs.next() ) {
String hospitalID = Integer.toString( rs.getInt(1) );
String hospitalName = rs.getString(2);
String address = rs.getString(3);
String contNum = Integer.toString( rs.getInt(4) );
String hosCharges = Double.toString( rs.getDouble(5) );
//Adding a line
returnString += " <tr> " +
" <td> <input id='hidItemIDUpdate' name='hidItemIDUpdate' type='hidden' value='" + hospitalID + "'/>" + hospitalID + " </td> " +
" <td id='hName'> " + hospitalName + " </td> " +
" <td id='addr'> " + address + " </td> " +
" <td id='cNo'> " + contNum + " </td> " +
" <td id='hCharge'> " + hosCharges + " </td> " ;
// Adding update and remove buttons
returnString += "<td> <input name='btnUpdate' type='button' value='Update' class='btnUpdate btn btn-secondary'> </td>" +
"<td><input name='btnRemove' type='button' value='Remove' class='btnRemove btn btn-danger' data-itemid='" + hospitalID + "'/>" + "</td> </tr>";
}
returnString += "</table>";
}
catch(Exception e) {
returnString = "Error occured while reading DB";
System.err.println(e.getMessage());
}
return returnString;
}
public String insertHospital(String hosId, String hosName, String address, String contNum, String hosCharges) {
String returnString = "";
if ( conn == null)
{
return "Can not connect with database";
}
String QUERY = "INSERT INTO Hospitals VALUES ( ? , ? , ? , ? , ? )";
try {
PreparedStatement preparedStmt = conn.prepareStatement(QUERY);
preparedStmt.setInt(1, Integer.parseInt(hosId) );
preparedStmt.setString(2, hosName);
preparedStmt.setString(3, address);
preparedStmt.setInt(4, Integer.parseInt(contNum));
preparedStmt.setDouble(5, Double.parseDouble(hosCharges) );
preparedStmt.execute();
String hospitals = getHospitals();
returnString = "{\"status\":\"success\", \"data\": \"" +
hospitals + "\"}";
System.out.println("This line got executed" + hospitals);
}
catch(Exception e) {
returnString = "{\"status\":\"error\", \"data\": + \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return returnString;
}
public String updateHospital(String hosId, String hosName, String address, String contNum, String hosCharges) {
String returnString = "";
if ( conn == null)
{
return "Can not connect with database";
}
String QUERY = "UPDATE Hospitals SET hosName = ?, address = ?, contNum = ?, hosCharges = ? where hostId = ?";
try {
PreparedStatement st = conn.prepareStatement(QUERY);
st.setInt(1, Integer.parseInt(hosId));
st.setString(2, hosName);
st.setString(3, address);
st.setInt(4, Integer.parseInt(contNum));
st.setDouble(5, Double.parseDouble(hosCharges));
st.executeUpdate();
String hospitals = getHospitals();
returnString = "{\"status\":\"success\", \"data\": \"" +
hospitals + "\"}";
}
catch(Exception e) {
returnString = "{\"status\":\"error\", \"data\":\"Error while updating the item.\"}";
System.err.println(e.getMessage());
}
return returnString;
}
public String deleteHospital(String hosId) {
String returnString = "";
if ( conn == null)
{
return "Can not connect with database";
}
String QUERY = "DELETE FROM Hospitals WHERE hostId =?";
try {
PreparedStatement st = conn.prepareStatement(QUERY);
st.setInt(1, Integer.parseInt(hosId));
st.executeUpdate();
conn.close();
String details = getHospitals();
returnString = "{\"status\":\"success\", \"data\": \"" +
details + "\"}";
}
catch(Exception e) {
returnString = "{\"status\":\"error\", \"data\":\"Error while deleting the item.\"}";
System.err.println(e.getMessage());
}
return returnString;
}
}
|
package com.train.route;
import com.train.route.actions.DistanceAction;
import junit.framework.TestCase;
/**
* @author abhishek.ghosh
*/
public class DistanceActionTest extends TestCase {
public void testExecute() {
TrainNetwork g1 = new TrainNetwork("AB2, BA3, BD5, BE7, DB11, EB13, CE17, EC19, DE23, ED29, CF31 " +
"FC37, EF41, FE43, FA53, AF59, DA61, AD67, EA71, AE73");
DistanceAction a1 = new DistanceAction();
a1.setParameters(new String[]{"distance?", "EDBEF"});
assertEquals(a1.execute(g1), "88");
DistanceAction a2 = new DistanceAction();
a2.setParameters(new String[]{"schmarrn", "EDBEF"});
assertEquals(a2.execute(g1), "88");
try {
DistanceAction a3 = new DistanceAction();
a3.setParameters(new String[]{"distance?"});
a3.execute(g1);
fail("accepted incomplete action");
} catch (IllegalArgumentException e) {
}
}
}
|
/*
* 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 Aula7.Exercicio4;
/**
*
* @author mauricio.moreira
*/
public class ContaBancariaEspecial extends ContaBancaria{
public ContaBancariaEspecial(String nome) {
super(nome);
}
public ContaBancariaEspecial(String nome, double montante) {
super(nome, montante);
}
@Override
public void sacar(double quantia) {
double taxa = 0.001*quantia;
if (quantia + taxa > montante) {
System.out.println("Não possui dinheiro suficiente");
} else {
montante = montante - quantia - taxa;
}
}
}
|
package com.ajay.cloning;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("Pune", 1424);
Person person = new Person(101,"ajay",address);
Person person2 = (Person) person.clone();
person2.getAddress().setCity("Solapur");
System.out.println("person>>>>"+person);
System.out.println("person2>>>>"+person2);
}
}
|
/*
* @Author : fengzhi
* @date : 2019 - 04 - 28 21 : 36
* @Description :
*/
package nowcoder_leetcode;
import java.util.ArrayList;
/*
* 如果要求输出所有可能的解,往往都是要用深度优先搜索。
* 如果是要求找出最优的解,或者解的数量,往往可以使用动态规划。
*/
public class p_19 {
private ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
public ArrayList<ArrayList<String>> partition(String s) {
huisu(s);
return arrayLists;
}
private void huisu(String s) {
if (s.equals("")) {
// 注意这里不要直接传入arrayList
arrayLists.add(new ArrayList<>(arrayList));
return;
}
for (int i = 1; i <= s.length(); i ++) {
String sub = s.substring(0, i);
if (isPalindromed(sub)) {
arrayList.add(sub);
huisu(s.substring(i));
arrayList.remove(arrayList.size() - 1);
}
}
}
private boolean isPalindromed(String s) {
if (s == null || s.length() == 0)
return false;
if (s.length() == 1)
return true;
for (int i = 0,j = s.length() - 1; i<j ; i++, j--){
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static void main(String[] args) {
p_19 p = new p_19();
System.out.println(p.partition("abcba"));
}
}
|
package io.github.cepr0.authservice.model;
import lombok.Value;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
import java.util.Set;
import java.util.UUID;
@Value
@KeySpace("customers")
public class Customer {
@Id
UUID id;
String phoneNumber;
String name;
Set<String> roles = Set.of("USER");
}
|
/**
*
*/
package pt.mleiria.nonlinear.numeric;
import pt.mleiria.mlalgo.functions.OneVarFunction;
/**
* @author manuel
*
* Condição suficiente de convergência do método:<br>
* - f continua em [a, b] <br>
* - f(a)f(b) < 0
*
*/
public class Bissection {
private double x;
private double x0;
private double a0;
private double a;
private double b0;
private double b;
private double epsilon = 0.0001;
private int maxIter = 100;
private OneVarFunction<Double, Double> f;
/**
*
* @param a
* @param b
*/
public Bissection(final double a, final double b, OneVarFunction<Double, Double> f) {
this.a0 = a;
this.b0 = b;
this.x0 = a;
this.f = f;
}
public void iterate() {
int currentCount = 0;
while (true) {
x = (a0 + b0) / 2;
if (hasconverged() || currentCount == maxIter) {
break;
}
currentCount++;
System.out.println(currentCount + " : " + x + " : " + f.value(x));
}
System.out.println(currentCount + " : " + x + " : " + f.value(x));
}
public boolean hasconverged() {
if (Math.abs(x - x0) <= epsilon || Math.abs(f.value(x)) <= epsilon) {
return true;
} else {
if (x * f.value(a0) < 0) {
a = a0;
b = x;
} else {
a = x;
b = b0;
}
return false;
}
}
/**
* @param args
*/
public static void main(String[] args) {
OneVarFunction<Double, Double> func = x -> Math.pow(10, 6) * Math.exp(x) + (281000 / x) * (Math.exp(x) - 1) - 178000000;
System.out.println(func.value(0.36));
Bissection b = new Bissection(0.1, 1., func);
// OneVarFunction<Double, Double> func = x -> Math.pow(x, 2) - 4;
// Bissection b = new Bissection(1., 3., func);
b.iterate();
}
}
|
package soumyavn.java.CheckoutSimulation;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class CustomerTest extends TestCase {
public CustomerTest( String testName )
{
super( testName );
}
public static Test suite()
{
return new TestSuite( CustomerTest.class );
}
public void testfindRegister() {
//Assume 2 registers in the store
Store.registers.add(new Register(false));
Store.registers.add(new Register(true));
Store.registerCount=2;
//Assume both registers are empty
Customer c=new Customer('A',1,2);
c.findRegister();
assertEquals(0,c.regIndex); //index of register to which the customer will be assigned
//Assume Register1 has 1 customer in line and Register2 is empty
c=new Customer('B',2,1);
c.findRegister();
assertEquals(1,c.regIndex);
//Assume the last customer of Register1 has 2 items and that of Register2 has 1 item left to check out
c=new Customer('B',3,1);
c.findRegister();
assertEquals(1,c.regIndex);
//Assume RegisterI has 1 and Register2 has 2 customers in line
c=new Customer('A',4,1);
c.findRegister();
assertEquals(0,c.regIndex);
}
public void testCompareTo() {
Customer c=new Customer('A',1,2);
int result=c.compareTo(new Customer('A',2,1));
assertEquals(-1,result);
c=new Customer('A',1,3);
result=c.compareTo(new Customer('A',1,2));
assertEquals(1,result);
c=new Customer('A',1,3);
result=c.compareTo(new Customer('B',1,3));
assertEquals(-1,result);
}
}
|
package com.tencent.mm.plugin.order.ui;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import com.tencent.mm.plugin.wxpay.a$i;
import com.tencent.mm.ui.base.h;
class MallOrderRecordListUI$2 implements OnItemLongClickListener {
final /* synthetic */ MallOrderRecordListUI lPQ;
MallOrderRecordListUI$2(MallOrderRecordListUI mallOrderRecordListUI) {
this.lPQ = mallOrderRecordListUI;
}
public final boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long j) {
if (i < this.lPQ.lPM.size()) {
h.a(this.lPQ, this.lPQ.getResources().getString(a$i.wallet_order_list_delete_order), null, this.lPQ.getResources().getString(a$i.app_delete), new 1(this, i));
}
return true;
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ix extends g {
public c$ix() {
super("startMonitoringBeacons", "startMonitoringBeacons", 151, true);
}
}
|
public class PigLatinTester extends PigLatin {
public static void main(String[] args) {
System.out.println(pigLatinSimple("mock"));
System.out.println(pigLatinSimple("pie"));
System.out.println(pigLatinSimple("david"));
System.out.println(pigLatinSimple("aaron"));
System.out.println(pigLatinSimple("a"));
System.out.println(pigLatinSimple("t"));
System.out.println(pigLatinSimple("A"));
System.out.println(pigLatinSimple("T"));
System.out.println();
System.out.println(pigLatin("the"));
System.out.println(pigLatin("check"));
System.out.println(pigLatin("skee"));
System.out.println(pigLatin("emu"));
System.out.println(pigLatin("grade"));
System.out.println(pigLatin("a"));
System.out.println(pigLatin("t"));
System.out.println(pigLatin("A"));
System.out.println(pigLatin("T"));
System.out.println();
System.out.println(pigLatinBest("*emu"));
System.out.println(pigLatinBest("4chan"));
System.out.println(pigLatinBest("fish!"));
System.out.println(pigLatinBest("fish"));
System.out.println(pigLatinBest("the."));
System.out.println(pigLatinBest("cat!"));
System.out.println(pigLatinBest("amazing?"));
System.out.println(pigLatinBest("apple%"));
System.out.println(pigLatinBest("a"));
System.out.println(pigLatinBest("t"));
System.out.println(pigLatinBest("A"));
System.out.println(pigLatinBest("T"));
}
}
|
package app0527.network.basic.echo.cmd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
// 에코서버를 콘솔(cmd)기반으로 제작해본다.
public class EchoServer {
ServerSocket server; // 대화용이 아닌, 접속자 감지용 소켓
int port = 7979;
InputStream is = null;
OutputStream os = null;
// 지금 제작하려는 프로그램은 복사 등이 아니다. 인간의 육안으로 데이터를 해석가능한 즉 문자를 해서갛ㄹ 수 있는 스트림을 다루는 프로그램이다.
// 따라서 문자기반의 스트림이 필요한 시점이다.
InputStreamReader reader = null; // 문자기반의 입력스트림
OutputStreamWriter writer = null; // 문자기반의 출력스트림
// 한 문자씩 데이터를 주고받으면 너무 불편하므로, 문장화 시키려면 버퍼처리된 즉 문자열화 시킬 수 있는 스트림을 이요해보자.
BufferedReader buffr = null;
BufferedWriter buffw = null;
public EchoServer() {
try {
server = new ServerSocket(port);
System.out.println("서버 생성");
// 접속자가 있는지 기다리는 메서드
Socket socket = server.accept(); // 접속자가 있을 때까지 지연상태에 머무른다.
// 접속이 발생하면, 이 접속에 의한 소켓을 반환받을 수 있다. ( 이때의 소켓은 대화를 나누기 위한 소켓)
System.out.println("접속자 발견");
is = socket.getInputStream(); // 이소켓과 연관된 입력스트림을 얻어, 클라이언트의 메시지를 청취하자.
// 즉 입력 받자.
os = socket.getOutputStream(); // 이소켓과 연관된 출력스트림을 얻어, 클라이언트에게 메시지를 보내자
// 문자 기반으로 업그레이드
reader = new InputStreamReader(is,"UTF-8");
writer = new OutputStreamWriter(os,"UTF-8");
// 문자열을 처리하는 버퍼기반으로 업그레이드
buffr = new BufferedReader(reader);
buffw = new BufferedWriter(writer);
// 서버는 듣고 말한다.
String data =null;
// 적어도 대화를 하려면, 문자를 이해해야하고, 문장을 모아서 처리해야한다.
// 문자기반스트림 + 버퍼처리된스트림
while(true) {
data = buffr.readLine(); //1줄씩 읽기
System.out.println(data);
buffw.write(data+"\n"); // 1줄씩 보내기 : 말하기
buffw.flush(); // 버퍼기반의 출력스트림을 확 비워버린다 flush는 변기물을 확 내려버린다는의미 비워버리는다는 의미
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(buffw != null) {
try {
buffw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(buffr != null) {
try {
buffr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new EchoServer();
}
}
|
package manager.editmenu;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class EditMenuMain extends Application {
public static void main(String[] args) {
Application.launch(EditMenuMain.class, args);
}
@Override
public void start(Stage mainStage) throws Exception {
Pane mainPane = (Pane) FXMLLoader.load(getClass().getResource("EditMenuView.fxml"));
Scene scene = new Scene(mainPane);
mainStage.setTitle("Edit Menu");
mainStage.setScene(scene);
mainStage.show();
}
}
|
package com.example.lookie;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Currency;
import java.util.Locale;
public class PrintCart extends AppCompatActivity {
public void printMenu(MenuNum menuNum,SharedPreferences sp,TextView tv,TextView orderPrice,TextView priceAll)
{
BurgerSetData burgerSet;
BurgerCartData burger;
DrinkCartData drink;
DessertCartData dessert;
Gson gson;
int sum=0;
gson=new GsonBuilder().create();//버거 단품 = menu, 버거세트 = bmenu, 음료 = dmenu, 디저트 = demenu
int bnum=menuNum.getBnum();
int dnum=menuNum.getDnum();
int denum=menuNum.getDenum();
int num=menuNum.getNum();
for(int i=1;i<num;i++)
{
String menu = sp.getString("menu" + String.valueOf(i), "");
burger = gson.fromJson(menu, BurgerCartData.class);
tv.append("burger : " + burger.getBurger() + "\nprice : " + burger.getPrice() + "\namount : " + burger.getAmount()+"\n");
sum+=burger.getPrice()*burger.getAmount();
}
for(int i=1;i<bnum;i++)
{
String menu = sp.getString("bmenu" + String.valueOf(i), "");
burgerSet = gson.fromJson(menu, BurgerSetData.class);
tv.append("burger : " + burgerSet.getBurger() + "\ndessert : " + burgerSet.getDessert() +
"\ndrink : " + burgerSet.getDrink() + "\nprice : " + burgerSet.getPrice() + "\namount : " + burgerSet.getAmount()+"\n");
sum+=burgerSet.getPrice()*burgerSet.getAmount();
}
for(int i=1;i<dnum;i++)
{
String menu = sp.getString("dmenu" + String.valueOf(i), "");
drink = gson.fromJson(menu, DrinkCartData.class);
tv.append("drink : " + drink.getDrink() + "\nsize : " + drink.getSize() +
"\nprice : " + drink.getPrice() + "\namount : " + drink.getAmount()+"\n");
sum+=drink.getPrice()*drink.getAmount();
}
for(int i=1;i<denum;i++)
{
String menu = sp.getString("demenu" + String.valueOf(i), "");
dessert = gson.fromJson(menu, DessertCartData.class);
tv.append("dessert : " + dessert.getDessert() + "\nsize : " + dessert.getSize() +
"\nprice : " + dessert.getPrice() + "\namount : " + dessert.getAmount()+"\n");
sum+=dessert.getPrice()*dessert.getAmount();
}
orderPrice.setText(Currency.getInstance(Locale.KOREA).getSymbol()+" "+String.valueOf(sum));
priceAll.setText(Currency.getInstance(Locale.KOREA).getSymbol()+" "+String.valueOf(sum));
}
public void cancelAll(ImageView iv,MenuNum menuNum,SharedPreferences sp,TextView tv,TextView orderPrice,TextView priceAll)
{
iv.setImageResource(R.drawable.cancel_all_check);
Handler h=new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
iv.setImageResource(R.drawable.cancel_all);
}
},200);
SharedPreferences.Editor editor=sp.edit();
editor.clear();
editor.commit();
menuNum.setBnum(1);
menuNum.setDnum(1);
menuNum.setDenum(1);
menuNum.setNum(1);
tv.setText("");
orderPrice.setText(Currency.getInstance(Locale.KOREA).getSymbol()+" "+String.valueOf(0));
priceAll.setText(Currency.getInstance(Locale.KOREA).getSymbol()+" "+String.valueOf(0));
}
}
|
package versuch_2;
import java.io.*;
/**
* Created by Marvin Kirsch on 09.11.2016.
* Matrikelnr.: 11118687
* Aufgabenblatt 2 - "Kontrollstrukturen und Algorithmen"
*/
public class Portnummern {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int portnummer;
boolean nochmal = false;
do {
do {
System.out.println("Geben sie eine Portnummer ein: ");
portnummer = Integer.parseInt(in.readLine());
} while (portnummer < 0 || portnummer >= 65535);
//Port Art
String artDesPorts;
if (portnummer < 1024) {
artDesPorts = "well-known ports";
} else if (portnummer < 49152) {
artDesPorts = "registered ports";
} else {
artDesPorts = "dynamic ports";
}
System.out.println("Die Art des Ports: \n" + artDesPorts);
switch (portnummer) {
case 21:
artDesPorts = "FTP (File Transfer Protocol, Uebertragung von Dateien)";
break;
case 23:
artDesPorts = "Telnet (Einloggen in entfernte Rechner)";
break;
case 25:
artDesPorts = "SMTP (Simple Mail Transfer Protocol, Mailversand)";
break;
case 80:
artDesPorts = "HTTP (HyperText Transfer Protocol, Zugriff auf Web-Server)";
break;
case 143:
artDesPorts = "IMAP (Internet Message Access Protocol, Zugriff auf Mail-Server)";
break;
default:
artDesPorts = "Sonstiger Dienst";
break;
}
System.out.println(artDesPorts);
System.out.println("\nWollen sie das Programm von vorne starten ?(y or n");
String antwort = "a";
while(!(antwort.equalsIgnoreCase("y") || antwort.equalsIgnoreCase("n"))) {
System.out.println("Geben sie y für Ja ein oder n für nein: ");
antwort = in.readLine();
}
if(antwort.equalsIgnoreCase("y")) {
System.out.println("Wird neu gestarted!");
nochmal = true;
} else if(antwort.equalsIgnoreCase("n")) {
System.out.println("Wuensche einen schoenen Tag :)");
nochmal = false;
}
} while(nochmal);
}
}
|
import java.util.*;
public class AtaqueIntercalado implements Estrategia
{
private ArrayList<Elfo> exercitoOrdenado = new ArrayList<>();
public ArrayList<Elfo> getOrdemDoUltimoAtaque()
{
return this.exercitoOrdenado;
}
public void atacar(ArrayList<Elfo> exercito, ArrayList<Dwarf> hordaDeDwarfs) throws NaoPodeAtacarException
{
if(exercito == null)
throw new NaoPodeAtacarException("Você não pode atacar sem um exercito!");
this.manterCom(Status.VIVO, exercito);
int somaElfosVerdes = this.filtrarElfosPorTipo(exercito, ElfoVerde.class).size();
int somaElfosNoturnos = this.filtrarElfosPorTipo(exercito, ElfoNoturno.class).size();
if(somaElfosVerdes != somaElfosNoturnos)
throw new NaoPodeAtacarException("Você não pode atacar com essa estrategia se o exercito não estiver parelho!");
this.organizarExercito(exercito);
this.exercitoOrdenado.clear();
for(Elfo elfo : exercito)
{
this.exercitoOrdenado.add(elfo);
this.elfoAtacarDwarfs(elfo, hordaDeDwarfs);
}
}
private void organizarExercito(ArrayList<Elfo> exercito)
{
ArrayList<Elfo> elfos = new ArrayList<>();
elfos.addAll(this.filtrarElfosPorTipo(exercito, ElfoVerde.class));
elfos.addAll(this.filtrarElfosPorTipo(exercito, ElfoNoturno.class));
boolean elfoVerdeAtacou = false;
exercito.clear();
for(int i = 0, c = 0; i < elfos.size(); i++)
{
if(!elfoVerdeAtacou)
{
exercito.add(elfos.get(c));
elfoVerdeAtacou = true;
} else {
exercito.add(elfos.get(c + (elfos.size()/2)));
elfoVerdeAtacou = false;
c++;
}
}
}
private void elfoAtacarDwarfs(Elfo elfo, ArrayList<Dwarf> hordaDeDwarfs)
{
for(Dwarf dwarf : hordaDeDwarfs)
{
elfo.atirarFlecha(dwarf);
}
}
private ArrayList<Elfo> filtrarElfosPorTipo(ArrayList<Elfo> exercito, Class elfoClass)
{
ArrayList<Elfo> elfosDoTipo = new ArrayList<>();
for(Elfo elfo : exercito)
{
if(elfo.getClass() == elfoClass)
elfosDoTipo.add(elfo);
}
return elfosDoTipo;
}
private void manterCom(Status status, ArrayList<Elfo> exercito)
{
for(int i = 0; i < exercito.size(); i++)
{
if(exercito.get(i).getStatus() != status)
exercito.remove(i);
}
}
}
|
package de.hse.swa.dbmodel;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the company database table.
*
*/
@Entity
@NamedQuery(name="Company.findAll", query="SELECT c FROM Company c")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int companyID;
private String address;
private String department;
private String name;
//bi-directional many-to-one association to Servicecontract
@OneToMany(mappedBy="company")
private List<Servicecontract> servicecontracts;
//bi-directional many-to-one association to User
@OneToMany(mappedBy="company")
private List<User> users;
public Company() {
}
public int getCompanyID() {
return this.companyID;
}
public void setCompanyID(int companyID) {
this.companyID = companyID;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDepartment() {
return this.department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<Servicecontract> getServicecontracts() {
return this.servicecontracts;
}
public void setServicecontracts(List<Servicecontract> servicecontracts) {
this.servicecontracts = servicecontracts;
}
public Servicecontract addServicecontract(Servicecontract servicecontract) {
getServicecontracts().add(servicecontract);
servicecontract.setCompany(this);
return servicecontract;
}
public Servicecontract removeServicecontract(Servicecontract servicecontract) {
getServicecontracts().remove(servicecontract);
servicecontract.setCompany(null);
return servicecontract;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setCompany(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setCompany(null);
return user;
}
}
|
/**
* Clase que implementa la excepcion que se lanza cuando
* se solicita realizar un ciclo de una reparacion y la
* misma ya no tiene ciclos pendientes (esta concluida)
*/
package excepciones;
/**
* @author agonzalez
*
*/
@SuppressWarnings("serial")
public class ErrorReparacionYaConcluida extends Exception {
/**
*
*/
public ErrorReparacionYaConcluida() {}
/**
* @param message
*/
public ErrorReparacionYaConcluida(String message) {
super(message);
}
/**
* @param cause
*/
public ErrorReparacionYaConcluida(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public ErrorReparacionYaConcluida(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.gtfs.dao.interfaces;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.gtfs.bean.DesignationMst;
import com.gtfs.dao.impl.HibernateUtil;
public interface DesignationMstDao {
List<DesignationMst> findAllActiveFromDesignationMst();
DesignationMst findById(Long designationId);
}
|
package com.jk.jkproject.net.okhttp;
public class HttpConstants {
public static final int DEFAULT_CONNECT_TIME_OUT = 30;
public static final String DEFAULT_ERROR = "error";
public static final int DEFAULT_READ_TIME_OUT = 30;
public static final int DEFAULT_WRITE_TIME_OUT = 30;
public static final int FAILURE_CODE_DEFAULT = 1000;
public static final int FAILURE_CODE_NETWORK_NO = 1001;
public static final int FAILURE_CODE_PARSE_ERR = 1002;
}
|
package bootcamp.testng;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
/**
* Unit test for simple App.
*/
public class AppTest {
@BeforeClass
public void beforeClass() {
System.out.println("Executing Test Class - AppTest.");
}
@AfterClass
public void afterClass() {
System.out.println("***Finished Executing Test Class - AppTest.");
}
@BeforeMethod
public void beforeTest() {
System.out.println("Starting a new Test.");
}
@AfterMethod
public void afterTest() {
System.out.println("Finished Executing new Test.");
}
/**
* Rigorous Test :-)
*/
@org.testng.annotations.Test
public void app1Test1() {
System.out.println("Test App1Test1 is in progress.");
}
@org.testng.annotations.Test
public void app1Test2() {
System.out.println("Test App1Test2 is in progress.");
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.devtools_bridge.gcd;
/**
* Information needed for registration in GCD.
* Instance secret will be bound to oAuthClientId.
* gcmChannelId will be used for delivering commands.
* displayName is a human readable name on the client side.
*/
public final class InstanceDescription {
public final String oAuthClientId;
public final String gcmChannelId;
public final String displayName;
private InstanceDescription(String oAuthClientId, String gcmChannelId, String displayName) {
assert oAuthClientId != null;
assert gcmChannelId != null;
assert displayName != null;
this.oAuthClientId = oAuthClientId;
this.gcmChannelId = gcmChannelId;
this.displayName = displayName;
}
/**
* Builder for InstanceDescription.
*/
public static final class Builder {
private String mOAuthClientId;
private String mGCMChannelId;
private String mDisplayName;
public Builder setOAuthClientId(String value) {
mOAuthClientId = value;
return this;
}
public Builder setGCMChannelId(String value) {
mGCMChannelId = value;
return this;
}
public Builder setDisplayName(String value) {
mDisplayName = value;
return this;
}
public InstanceDescription build() {
return new InstanceDescription(mOAuthClientId, mGCMChannelId, mDisplayName);
}
}
}
|
/* */ package com.ketonix.ketonixpro;
/* */
/* */ import java.io.File;
/* */ import java.io.FileNotFoundException;
/* */ import java.io.FileOutputStream;
/* */ import java.io.IOException;
/* */ import java.io.InputStream;
/* */ import java.io.OutputStream;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class NativeUtils
/* */ {
/* */ private NativeUtils() {}
/* */
/* */ public static void loadLibraryFromJar(String path)
/* */ throws IOException
/* */ {
/* 44 */ if (!path.startsWith("/")) {
/* 45 */ throw new IllegalArgumentException("The path has to be absolute (start with '/').");
/* */ }
/* */
/* */
/* 49 */ String[] parts = path.split("/");
/* 50 */ String filename = parts.length > 1 ? parts[(parts.length - 1)] : null;
/* */
/* */
/* 53 */ String prefix = "";
/* 54 */ String suffix = null;
/* 55 */ if (filename != null) {
/* 56 */ parts = filename.split("\\.", 2);
/* 57 */ prefix = parts[0];
/* 58 */ suffix = parts.length > 1 ? "." + parts[(parts.length - 1)] : null;
/* */ }
/* */
/* */
/* 62 */ if ((filename == null) || (prefix.length() < 3)) {
/* 63 */ throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
/* */ }
/* */
/* */
/* 67 */ File temp = File.createTempFile(prefix, suffix);
/* 68 */ temp.deleteOnExit();
/* */
/* 70 */ if (!temp.exists()) {
/* 71 */ throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist.");
/* */ }
/* */
/* */
/* 75 */ byte[] buffer = new byte['Ѐ'];
/* */
/* */
/* */
/* 79 */ InputStream is = NativeUtils.class.getResourceAsStream(path);
/* 80 */ if (is == null) {
/* 81 */ throw new FileNotFoundException("File " + path + " was not found inside JAR.");
/* */ }
/* */
/* */
/* 85 */ OutputStream os = new FileOutputStream(temp);
/* */ try { int readBytes;
/* 87 */ while ((readBytes = is.read(buffer)) != -1) {
/* 88 */ os.write(buffer, 0, readBytes);
/* */ }
/* */ }
/* */ finally {
/* 92 */ os.close();
/* 93 */ is.close();
/* */ }
/* */
/* */ int readBytes;
/* 97 */ System.load(temp.getAbsolutePath());
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/com/ketonix/ketonixpro/NativeUtils.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
|
package com.wds.spring.batch.ch03.next;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
/**
* Created by wds on 2015/9/29.
*/
public class PrintLogTasklet implements Tasklet {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("PrintLogTasklet is executing");
return null;
}
}
|
package com.flutterwave.raveandroid.rave_presentation.mpesa;
import androidx.annotation.Nullable;
public interface MpesaPaymentCallback {
/**
* Called to indicate that a background task is running, e.g. a network call.
* This should typically show or hide a progress bar.
*
* @param active If true, background task is running. If false, background task has stopped
*/
void showProgressIndicator(boolean active);
/**
* Called when an error occurs with the payment. The error message can be displayed to the users.
*
* @param errorMessage A message describing the error
* @param flwRef The Flutterwave reference to the transaction.
*/
void onError(String errorMessage, @Nullable String flwRef);
/**
* Called when the transaction has been completed successfully.
*
* @param flwRef The Flutterwave reference to the transaction.
*/
void onSuccessful(String flwRef);
}
|
import java.util.Scanner;
public class Problem4_20 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Prompt the user to enter a string
System.out.print(" Enter a string :");
String s = input.nextLine();
//Display string length and its first character
System.out.println( s +" has a length of " +s.length() + "and its first character is " +s.charAt(0));
}
}
|
/* 1: */ package com.kaldin.common.utility;
/* 2: */
/* 3: */ import com.kaldin.common.db.QueryHelper;
/* 4: */ import com.kaldin.common.formatter.Formatter;
/* 5: */ import java.sql.ResultSet;
/* 6: */ import java.util.GregorianCalendar;
/* 7: */
/* 8: */ public class Activity
/* 9: */ {
/* 10: */ public void updateActivity(String event, String value)
/* 11: */ {
/* 12:21 */ QueryHelper qh = new QueryHelper();
/* 13: */ try
/* 14: */ {
/* 15:23 */ GregorianCalendar calendar = new GregorianCalendar();
/* 16: */
/* 17:25 */ java.util.Date currentDay = calendar.getTime();
/* 18:26 */ String currentDate = Formatter.dateFormat("MM-dd-yyyy", currentDay);
/* 19: */
/* 20:28 */ java.sql.Date currentSqlDate = Formatter.parseSQLDate(currentDate, "MM-dd-yyyy");
/* 21: */
/* 22: */
/* 23:31 */ boolean isAvil = false;
/* 24: */
/* 25:33 */ String sql = "select * from ACTIVITY where CURRENTDATE = ?";
/* 26:34 */ String subsql = "";
/* 27:35 */ qh.addParam(currentSqlDate);
/* 28:36 */ ResultSet rs = qh.runQueryStreamResults(sql);
/* 29:37 */ if (rs.next()) {
/* 30:38 */ isAvil = true;
/* 31: */ }
/* 32:40 */ rs.close();
/* 33:42 */ if (isAvil)
/* 34: */ {
/* 35:43 */ sql = "update ACTIVITY set ";
/* 36:45 */ if (event.equals("NEWTRANSACTION")) {
/* 37:46 */ subsql = " NEWTRANSACTION = ( NEWTRANSACTION + " + Integer.parseInt(value) + ")";
/* 38:47 */ } else if (event.equals("AMOUTRECIVED")) {
/* 39:48 */ subsql = " AMOUTRECIVED = ( AMOUTRECIVED + " + Double.parseDouble(value) + ")";
/* 40:49 */ } else if (event.equals("USPS")) {
/* 41:50 */ subsql = " USPS= ( USPS+" + Integer.parseInt(value) + ")";
/* 42:51 */ } else if (event.equals("ADDRESSCHANGE")) {
/* 43:52 */ subsql = " ADDRESSCHANGE = ( ADDRESSCHANGE +" + Integer.parseInt(value) + ")";
/* 44:53 */ } else if (event.equals("SIGNUP")) {
/* 45:54 */ subsql = " SIGNUP = ( SIGNUP +" + Integer.parseInt(value) + ")";
/* 46:55 */ } else if (event.equals("DISCONNECT")) {
/* 47:56 */ subsql = " DISCONNECT = ( DISCONNECT +" + Integer.parseInt(value) + ")";
/* 48:57 */ } else if (event.equals("SPECIALOFFER")) {
/* 49:58 */ subsql = " SPECIALOFFER = ( SPECIALOFFER +" + Integer.parseInt(value) + ")";
/* 50:59 */ } else if (event.equals("JUNKMAIL")) {
/* 51:60 */ subsql = " JUNKMAIL = ( JUNKMAIL +" + Integer.parseInt(value) + ")";
/* 52:61 */ } else if (event.equals("JUNKMAILFAIL")) {
/* 53:62 */ subsql = " JUNKMAILFAIL = ( JUNKMAILFAIL +" + Integer.parseInt(value) + ")";
/* 54: */ }
/* 55:66 */ if (!subsql.equals(""))
/* 56: */ {
/* 57:67 */ sql = sql + " " + subsql + " where CURRENTDATE = ?";
/* 58:68 */ qh.addParam(currentSqlDate);
/* 59:69 */ qh.runQuery(sql);
/* 60: */ }
/* 61: */ }
/* 62: */ else
/* 63: */ {
/* 64:72 */ sql = "insert into ACTIVITY (" + event + ",CURRENTDATE) values (?,?)";
/* 65:73 */ qh.addParam(value);
/* 66:74 */ qh.addParam(currentSqlDate);
/* 67:75 */ qh.runQuery(sql);
/* 68: */ }
/* 69: */ }
/* 70: */ catch (Exception e)
/* 71: */ {
/* 72:79 */ e.printStackTrace();
/* 73: */ }
/* 74: */ finally
/* 75: */ {
/* 76:82 */ qh.releaseConnection();
/* 77: */ }
/* 78: */ }
/* 79: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.common.utility.Activity
* JD-Core Version: 0.7.0.1
*/
|
package com.system.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.teachsystem.dao.Dao;
/**
* Servlet implementation class ChangePassWordServlet
*/
@WebServlet("/ChangePassWordServlet")
public class ChangePassWordServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
String userName=request.getParameter("userName");
String studentUserName=request.getParameter("studentuserName");
String pass=request.getParameter("passWord");
if(userName==null){
userName="";
}
if(!userName.equals("")){
Dao dao=Dao.getInstance();
boolean flag=dao.changePassWord(Integer.parseInt(userName), pass);
Gson g=new Gson();
String json=g.toJson(flag);
response.getWriter().println(json);
}
if(studentUserName==null){
studentUserName="";
}
if(!studentUserName.equals("")){
Dao dao=new Dao();
boolean flag=dao.changePassWordBySno(Integer.parseInt(studentUserName), pass);
Gson g=new Gson();
String json=g.toJson(flag);
response.getWriter().println(json);
}
}
}
|
import java.io.IOException;
import java.util.*;
public class Service {
public static final String CAR_FILE = "car.csv";
public static final String CREATE_CAR_FILE = "createcar.csv";
public static final String DEALERSHIP_FILE = "dealerships.csv";
public static final String CREATE_DEALERSHIP_FILE = "createdealership.csv";
public static final String AUDIT_FILE = "audit.csv";
private final CreateDealerShip createDealerShip = new CreateDealerShip();
private final CreateCar createCar = new CreateCar();
private final Set<DealerShip> dealerships = new TreeSet<>();
// 1. La primul pas dorim sa cream un dealership nou
public void newDealerShip() throws IOException{
CreateDealerShip x = new CreateDealerShip();
DealerShip y = CreateDealerShip.newDealerShip();
dealerships.add(y);
log("createdealership");
}
// 2. Vrem sa adaugam masini in reprezentante
public void addCarInDS(int dealershipId) throws Eroare, IOException {
DealerShip x = getDSById(dealershipId);
CreateCar car = new CreateCar();
Car y = CreateCar.newCar();
x.addCar(y);
log("addcar");
}
// 3. Vrem sa afisam toate masinile dintr-o anumita reprezentanta
public void showCars(int dealershipId) throws Eroare, IOException {
System.out.println(getDSById(dealershipId).getCarDetails());
log("showcars");
}
// 4. Vrem sa afisam masinile dintr-o reprezentanta in ordine descrescatoare a anilor
public void sortCars(int dealershipId) throws Eroare {
getDSById(dealershipId).sortCarsYear(); // Mai intai o sortez
getDSById(dealershipId).reverseList(); // Apoi o inversez
}
// 5. Ma intereseaza motorizarea cea mai frecvent dorita
public String bestFuelType() {
Map<String, Integer> popular = new HashMap<>();
Integer Max = -1;
String motorizare = "No se puede mi amigo";
// intru in dealership-uri pe rand
for(DealerShip x: dealerships) {
// pentru fiecare masina din dealership verif cea mai frecventa motorizare
for(Car y: x.getCars()) {
String fuelType = y.getFuelType();
if(popular.containsKey(fuelType)) {
popular.put(fuelType, popular.get(fuelType) + 1);
}
else {
popular.put(fuelType, 1);
}
if(popular.get(fuelType) > Max) {
Max = popular.get(fuelType);
motorizare = fuelType;
}
}
}
return motorizare;
}
// 6. Vreau sa afisez toate masinile in functie de motorizare, intrucat am vazut inainte care este cea mai populara motorizare
public int showLikes(String fuelType) throws Eroare {
Map<String, Integer> exists = new HashMap<>();
for(DealerShip x: dealerships) {
for(Car y: x.getCars()) {
fuelType = y.getFuelType();
if(exists.containsKey(fuelType)) {
exists.put(fuelType, exists.get(fuelType) + 1);
}
else {
exists.put(fuelType, 1);
}
if(exists.get(fuelType) >= 1) {
return 1;
}
}
}
return 0;
}
// 7. Vreau sa pot verifica daca o masina exista sau nu intr-un dealership, in functie de nume
public boolean carExists(int dealershipId, String carName) throws Eroare {
return getDSById(dealershipId).carExists(carName);
}
// 8. Vreau sa pot vinde o masina creata anterior
public void sellCar(int dealershipId, String carName) throws Eroare {
DealerShip x = getDSById(dealershipId);
x.sellCar(carName);
}
// 9. Vreau sa am optiunea sa elimin toate masinile adaugate anterior intr-un dealership
public void clearOutDS(int dealershipId) throws Eroare {
getDSById(dealershipId).clearDS();
}
private DealerShip getDSById(int dealershipId) throws Eroare {
for(DealerShip x: dealerships) {
if(x.getId() == dealershipId) {
return x;
}
}
throw new Eroare("This dealership does not exist.");
}
public void load() throws IOException {
createDealerShip.readDataFromFile(CREATE_DEALERSHIP_FILE, 0);
createCar.readDataFromFile(CREATE_CAR_FILE, 0);
//CreateCar x = new CreateCar();
//x.readDataFromFile(CREATE_CAR_FILE, 0);
int position = 0;
Read nanu = Read.getInstance();
String[] interior1 = nanu.readLine(DEALERSHIP_FILE, position);
if(interior1 != null) {
for (String s: interior1) {
position += s.length() + 1;
}
position += 1; // pentru caracterul new line
while (position != -1) {
DealerShip s = new DealerShip();
position = s.readDataFromFile(DEALERSHIP_FILE, position);
if (position != -1) {
dealerships.add(s);
}
}
}
ArrayList<Car> cars = createCar.readCarsFromFile(CAR_FILE);
for (Car c: cars) {
try {
DealerShip ds = getDSById(c.getDealershipID());
ds.addCar(c);
} catch (Eroare eroare) {
throw new IOException("Invalid file");
}
}
}
public void save() throws IOException {
Write nanu = Write.getInstance();
// Clear the files content.
nanu.delete(CAR_FILE);
nanu.delete(DEALERSHIP_FILE);
nanu.delete(CREATE_CAR_FILE);
nanu.delete(CREATE_DEALERSHIP_FILE);
// Save the new state.
createDealerShip.writeDataInFile(CREATE_DEALERSHIP_FILE);
createCar.writeDataInFile(CREATE_CAR_FILE);
for (DealerShip ds: dealerships) {
ds.writeDataInFile(DEALERSHIP_FILE);
for (Car c: ds.getCars()) {
c.writeDataInFile(CAR_FILE);
}
}
}
private void log(String action) throws IOException {
Write nanu = Write.getInstance();
String timestamp = String.valueOf(System.currentTimeMillis());
nanu.write(AUDIT_FILE, action + ", " + timestamp + ",\n");
}
}
|
package shared;
import java.lang.*;
/** scoring device for CatTestResult **/
public class ScoringMetrics {
// Public member data
/** The number fo instances correctly classified.
*/
public int numCorrect;
/** The number fo instances incorrectly classified.
*/
public int numIncorrect;
/** The total amount of loss.
*/
public double totalLoss;
/** The minimum amount of loss.
*/
public double minimumLoss;
/** The maximum amount of loss.
*/
public double maximumLoss;
/** The weight of correctly classified instances.
*/
public double weightCorrect;
/** The weight of incorrectly classified instances.
*/
public double weightIncorrect;
/** The mean squared error value.
*/
public double meanSquaredError;
/** The mean absolute error value.
*/
public double meanAbsoluteError;
/** The total amount of log loss.
*/
public double totalLogLoss;
/** The number of none trivial leaves used by a tree inducer.
*/
public int treeleaves;
/** The number of none trivial nodes used by a tree inducer.
*/
public int treenodes;
// Methods
/** Constructor.
*/
public ScoringMetrics() {
numCorrect = 0;
numIncorrect = 0;
totalLoss = 0;
minimumLoss = 0;
maximumLoss = 0;
weightCorrect = 0;
weightIncorrect = 0;
meanSquaredError = 0;
meanAbsoluteError = 0;
totalLogLoss = 0;
treeleaves = 0;
treenodes = 0;
}
/** Returns the total weight of instances.
* @return The total weight.
*/
public double totalWeight() {
return (weightCorrect + weightIncorrect);
}
/** Returns the total number of instances. Easier than retreiving both values
* summing them external to this class.
* @return The total number of instances.
*/
public int totalInstances() {
return (numCorrect + numIncorrect);
}
}
|
package dng.deongeori;
public class DeongeoriInviteMessageBean {
private int dng_inv_id; // 덩어리 초대 메세지 번호.
private String dng_id; // 초대할 덩어리 아이디.
private String dng_inv_from; // 초대한 회원 아이디.
private String dng_inv_to; // 초대할 회원 아이디.
private char dng_inv_isallow; // 초대 수락 여부.
private String dng_inv_regdate; // 초대일시.
public int getDng_inv_id() {
return dng_inv_id;
}
public void setDng_inv_id(int dng_inv_id) {
this.dng_inv_id = dng_inv_id;
}
public String getDng_id() {
return dng_id;
}
public void setDng_id(String dng_id) {
this.dng_id = dng_id;
}
public String getDng_inv_from() {
return dng_inv_from;
}
public void setDng_inv_from(String dng_inv_from) {
this.dng_inv_from = dng_inv_from;
}
public String getDng_inv_to() {
return dng_inv_to;
}
public void setDng_inv_to(String dng_inv_to) {
this.dng_inv_to = dng_inv_to;
}
public char getDng_inv_isallow() {
return dng_inv_isallow;
}
public void setDng_inv_isallow(char dng_inv_isallow) {
this.dng_inv_isallow = dng_inv_isallow;
}
public String getDng_inv_regdate() {
return dng_inv_regdate;
}
public void setDng_inv_regdate(String dng_inv_regdate) {
this.dng_inv_regdate = dng_inv_regdate;
}
}
|
public class Car {
public void applyBrakes() {
System.out.println("driver applies brakes.");
checkSurroundings();
}
public void checkSurroundings() {
System.out.println("driver checks surroundings.");
}
}
|
/*
* 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.telas;
import java.net.URL;
import javax.swing.ImageIcon;
/**
*
* @author J4CkS0N
*/
public class ConfirmaGUI extends javax.swing.JFrame {
/**
* Creates new form ConfirmaGUI
*/
public ConfirmaGUI() {
initComponents();
this.setLocation(500, 300);
}
/**
* 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() {
lblConfirmar = new javax.swing.JLabel();
lblCancelar = new javax.swing.JLabel();
lblFechar = new javax.swing.JLabel();
lblMinimizar = new javax.swing.JLabel();
lblFundo = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
lblConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
lblConfirmarMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
lblConfirmarMouseExited(evt);
}
});
getContentPane().add(lblConfirmar, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 81, 55, 55));
lblCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
lblCancelarMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
lblCancelarMouseExited(evt);
}
});
getContentPane().add(lblCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 84, 55, 50));
lblFechar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lblFecharMouseClicked(evt);
}
});
getContentPane().add(lblFechar, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 0, 15, 15));
lblMinimizar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lblMinimizarMouseClicked(evt);
}
});
getContentPane().add(lblMinimizar, new org.netbeans.lib.awtextra.AbsoluteConstraints(305, 0, 15, 15));
lblFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Telas Pequenas/tela confirma.png"))); // NOI18N
lblFundo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lblFundoMouseClicked(evt);
}
});
getContentPane().add(lblFundo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void lblFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblFecharMouseClicked
this.dispose();
}//GEN-LAST:event_lblFecharMouseClicked
private void lblFundoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblFundoMouseClicked
}//GEN-LAST:event_lblFundoMouseClicked
private void lblMinimizarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblMinimizarMouseClicked
this.setExtendedState(ConfirmaGUI.ICONIFIED);
}//GEN-LAST:event_lblMinimizarMouseClicked
private void lblConfirmarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblConfirmarMouseEntered
}//GEN-LAST:event_lblConfirmarMouseEntered
private void lblConfirmarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblConfirmarMouseExited
}//GEN-LAST:event_lblConfirmarMouseExited
private void lblCancelarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblCancelarMouseEntered
}//GEN-LAST:event_lblCancelarMouseEntered
private void lblCancelarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblCancelarMouseExited
}//GEN-LAST:event_lblCancelarMouseExited
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ConfirmaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConfirmaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConfirmaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfirmaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ConfirmaGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel lblCancelar;
private javax.swing.JLabel lblConfirmar;
private javax.swing.JLabel lblFechar;
private javax.swing.JLabel lblFundo;
private javax.swing.JLabel lblMinimizar;
// End of variables declaration//GEN-END:variables
}
|
package com.dmt.sannguyen.lgwfb;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.LoginFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class ThemBabyActivity extends AppCompatActivity {
EditText edtBabyName;
RadioGroup radioGroupGioiTinh;
RadioButton radioBtn;
EditText edtHienThiNgaySinh;
ImageButton imgCalendar;
Button btnThem, btnHuy;
String userid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_baby);
final Intent intent = getIntent();
userid = intent.getStringExtra("userid");
Log.d("Track", "Add baby got: " + userid);
AnhXa();
imgCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
DatePickerDialog datePickerDialog = new DatePickerDialog(ThemBabyActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
edtHienThiNgaySinh.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
}
}, year, month, date);
datePickerDialog.show();
}
});
btnThem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String baby_name = edtBabyName.getText().toString().trim();
int selectedGT = radioGroupGioiTinh.getCheckedRadioButtonId();
radioBtn = findViewById(selectedGT);
String gioitinh = (String) radioBtn.getText();
String ngaysinh = edtHienThiNgaySinh.getText().toString().trim();
int gender;
if(gioitinh.equals("Nam")){
Log.d("Track", "Adding new baby with gioi tinh..."+ gioitinh);
gender = 1;
}else{
Log.d("Track", "Adding new baby with gioi tinh..."+ gioitinh);
gender = 0;
}
if(baby_name.length() > 0 && ngaysinh.length() > 0 ){
Log.d("Track", "Adding new baby with data..." + baby_name + " " + gender + " " + ngaysinh);
AddNewBaby(baby_name, ngaysinh, gender, userid);
Bundle bundle = new Bundle();
bundle.putString("userid", userid);
//send bundle data to BeYeuActivity activity
Intent intent1 = new Intent(ThemBabyActivity.this, MainActivity.class);
intent1.putExtras(bundle);
startActivity(intent1);
}else {
Toast.makeText(ThemBabyActivity.this, "thieu data", Toast.LENGTH_LONG).show();
}
}
});
}
private void AnhXa() {
edtBabyName = findViewById(R.id.edtBabyName);
radioGroupGioiTinh = findViewById(R.id.radioGrouptGioiTinh);
edtHienThiNgaySinh = findViewById(R.id.edtHienThiNgaySinh);
imgCalendar = findViewById(R.id.imgButtonCalendar);
btnThem = findViewById(R.id.btnThemBaby);
btnHuy = findViewById(R.id.btnCancelAddBaby);
}
private void AddNewBaby(final String name, final String dateofbirth, final int gender, final String userid){
String url = "https://babyvacxin.azurewebsites.net/api/AddBaby?code=Z791vFkebPlUlUy55cJzNsx6py6SWLs5Ay8ncnd7M8wrp9I0gbngfw==";
Log.d("Track", "Registering new user");
RequestQueue requestQueue = Volley.newRequestQueue(this);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Track", "Response from RegisterNewUser :" + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Track", "Response from RegisterNewUser :"+error);
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("dateofbirth", dateofbirth);
params.put("gender", String.valueOf(gender));
params.put("userid", userid);
return params;
}
};
//set to avoid Volley send request multiple times
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
}
|
package com.zhouyi.business.core.service;
import com.zhouyi.business.core.model.LedenBbs;
import com.zhouyi.business.core.model.PageData;
import com.zhouyi.business.core.model.Response;
import com.zhouyi.business.core.vo.BbsVo;
import java.util.List;
import java.util.Map;
/**
* 公告业务
*/
public interface LedenBbsService {
/**
* 分页查询公告业务
* @param conditions
* @return
*/
PageData<LedenBbs> searchBbsByConditions(Map<String, Object> conditions);
/**
* 修改公告业务
* @param bbsVo
* @return
*/
Boolean modifyLendenBbs(BbsVo bbsVo);
/**
* 新增公告
* @param bbsVo
* @return
*/
Boolean addLendenBbs(BbsVo bbsVo);
/**
* 删除公告
* @param pkId
* @return
*/
Boolean removeLendenBbs(String pkId);
/**
* 查询最新的一条公告
* */
Response selectBbsByDate();
}
|
package com.osce.server.portal.biz.training.res.room;
import com.osce.api.biz.training.res.room.PfRoomService;
import com.osce.dto.biz.training.res.room.RoomDto;
import com.osce.enums.SysDicGroupEnum;
import com.osce.result.PageResult;
import com.osce.server.portal.BaseController;
import com.osce.server.security.CurrentUserUtils;
import com.osce.server.utils.EnumUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @ClassName: PfRoomController
* @Description: PfSpController
* @Author yangtongbin
* @Date 2019-05-08
*/
@Controller
public class PfRoomController extends BaseController {
@Reference
private PfRoomService pfRoomService;
@Resource
private EnumUtil enumUtil;
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping("/pf/p/room/page")
public String page() {
return "pages/biz/training/res/room/roomPage";
}
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping("/pf/p/room/form")
public String form(String formType, Model model) {
model.addAttribute("formType", formType);
return "pages/biz/training/res/room/roomTagForm";
}
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping("/pf/p/room/device/page")
public String pageDevice(Long idRoom, Model model) {
model.addAttribute("idRoom", idRoom);
model.addAttribute("roomDeviceList", enumUtil.getEnumList(SysDicGroupEnum.SD_ROOM_DEVICE_CA.getCode()));
return "pages/biz/training/res/room/devicePage";
}
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping("/pf/p/room/device/form")
public String formDevice(String formType, Long idRoom, Model model) {
model.addAttribute("formType", formType);
model.addAttribute("idRoom", idRoom);
model.addAttribute("roomDeviceList", enumUtil.getEnumList(SysDicGroupEnum.SD_ROOM_DEVICE_CA.getCode()));
return "pages/biz/training/res/room/deviceForm";
}
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping(value = "/pf/p/room/list")
@ResponseBody
public PageResult pageRooms(RoomDto dto) {
dto.setIdOrg(CurrentUserUtils.getCurrentUserIdOrg());
return pfRoomService.pageRooms(dto);
}
@PreAuthorize("hasAnyRole('ROLE_01_02_001','ROLE_SUPER')")
@RequestMapping(value = "/pf/p/device/list")
@ResponseBody
public PageResult pageDevices(RoomDto dto) {
dto.setIdOrg(CurrentUserUtils.getCurrentUserIdOrg());
return pfRoomService.pageDevices(dto);
}
}
|
package com.example.imdb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.imdb.repository.MovieRepository;
@SpringBootApplication
public class ImdbSpringDataApplication implements ApplicationRunner{
public static void main(String[] args) {
SpringApplication.run(ImdbSpringDataApplication.class, args);
}
@Autowired
private MovieRepository movieRepo;
@Override
public void run(ApplicationArguments args) throws Exception {
// Movie movie = new Movie();
// movie.setTitle("test movie");
// movie.setYear(2019);
// movie.setImdb("tt1234567");
// movieRepo.save(movie);
movieRepo.filminTuruneGoreAra("War").forEach(System.out::println);
movieRepo.filminYilinaVeAdinaGoreAra(1970,1979,"the").forEach(System.out::println);
}
}
|
package dataStructures;
import java.io.Serializable;
/**
* This class is used for storing Corpus information like total documents
* and total number of postings generated after indexing
*
*/
public class CorpusStatistics implements Serializable{
private static final long serialVersionUID = 114248531690435365L;
private int totalDocuments, totalPostings;
public CorpusStatistics(int totalDocuments, int totalPostings) {
this.totalDocuments = totalDocuments;
this.totalPostings = totalPostings;
}
public int getTotalDocuments() {
return totalDocuments;
}
public int getTotalPostings() {
return totalPostings;
}
@Override
public String toString() {
return "CorpusStatistics [totalDocuments=" + totalDocuments
+ ", totalPostings=" + totalPostings + "]";
}
}
|
package com.penzias.service;
import com.penzias.core.interfaces.BasicService;
import com.penzias.entity.UserPersonalInfo;
import com.penzias.entity.UserPersonalInfoExample;
public interface UserPersonalInfoService extends BasicService<UserPersonalInfoExample, UserPersonalInfo> {
}
|
package havelsan.staj.SocialNetwork;
public class Movie extends GraphNode{
private MovieData data;
public MovieData getData() {
return data;
}
public void setData(MovieData data) {
this.data = data;
}
}
|
package ele_32_lab4;
public class Codificador2 {
int[] estados = new int[2];
int saida1 = 0;
int saida2 = 0;
int saida0 = 0;
int contador = 0;
public Scrambler scram;
public Codificador2(){
resetEstados();
scram = new Scrambler();
}
public void resetEstados(){
estados[1] = 0;
estados[0] = 0;
}
public void setEstado(String estado){
estados[1] = Character.getNumericValue(estado.charAt(0));
estados[0] = Character.getNumericValue(estado.charAt(1));
}
public int getEstado(){
String estadosString = Integer.toString(estados[1]) + Integer.toString(estados[0]);
return Integer.parseInt(estadosString, 2);
}
public String getSaida(int entrada){
contador++;
saida0 = entrada;
saida1 = ((entrada + estados[1] + estados[0])%2 + estados[1])%2;
//saida1 = (saida1 + scram.getBit())%2;
saida2 = ((entrada + estados[1] + estados[0])%2 + estados[0])%2;
//saida2 = (saida2 + scram.getBit())%2;
if(contador == 1000){
resetEstados();
contador = 0;
}
else{
int aux = (entrada + estados[1] + estados[0])%2;
estados[1] = estados[0];
estados[0] = aux;
}
return Integer.toString(saida0) + Integer.toString(saida1) + Integer.toString(saida2);
}
}
|
package org.browsexml.timesheetjob.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.browsexml.timesheetjob.model.BaseObject;
import org.browsexml.timesheetjob.model.CodeTerm;
import org.browsexml.timesheetjob.model.Constants;
import org.browsexml.timesheetjob.service.CodeTermManager;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class CodeTermController extends SimpleFormController {
private static Log log = LogFactory.getLog(CodeTermController.class);
private CodeTermManager mgr = null;
public CodeTermController() {
log.debug("LOADED " + this.getClass().getName());
}
public void setCodeTermManager(CodeTermManager CodeTermManager) {
this.mgr = CodeTermManager;
}
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
SimpleDateFormat dayFormat = Constants.displayDate;
dayFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dayFormat, true));
}
@Override
public Object formBackingObject(HttpServletRequest request) {
CodeTermBacking backing = new CodeTermBacking();
List<CodeTerm> terms = mgr.getTerms();
backing.setList(terms);
return backing;
}
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse arg1) throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'handleRequest' for " + this.getClass().getName() + "...");
}
CodeTermBacking backing = (CodeTermBacking) this.getCommand(request);
return new ModelAndView("codeTerm", this.getCommandName(), backing);
}
public static class CodeTermBacking extends BaseObject {
List<CodeTerm> list = null;
public CodeTermBacking() {
}
public List<CodeTerm> getList() {
return list;
}
public void setList(List<CodeTerm> list) {
this.list = list;
}
}
public static class CodeTermControllerValidator implements Validator {
private static Log log = LogFactory.getLog(CodeTermControllerValidator.class);
private CodeTermManager mgr = null;
public void setCodeTermManager(CodeTermManager CodeTermManager) {
this.mgr = CodeTermManager;
}
@Override
public boolean supports(Class theClass) {
return CodeTermBacking.class.equals(theClass);
}
@Override
public void validate(Object obj, Errors errors) {
}
}
}
|
package com.shoplite.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
//anotacion lombox
@Data
//crea en Mongodb la collection
@Document
public class Usuario {
@Id
public String id;
public String password;
}
|
package com.cn.my.util;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
@Component
public class CacheUtil{
@Autowired
private JedisPool jedisPool;
public boolean put2Cache(String cacheKey, String value) {
String result = jedisPool.getResource().set(cacheKey, value);
return "success".equals(result);
}
public boolean put2Cache(String cacheKey, String value, int seconds) {
String result = jedisPool.getResource().setex(cacheKey, seconds, value);
return "success".equals(result);
}
public String getFromCache(String cacheKey) {
return jedisPool.getResource().get(cacheKey);
}
public long incr(String key) {
return jedisPool.getResource().incr(key);
}
public long decr(String key) {
return jedisPool.getResource().decr(key);
}
public String putMap(String key, Map<String, String> map) {
return jedisPool.getResource().hmset(key, map);
}
public Map<String, String> getMap(String key) {
return jedisPool.getResource().hgetAll(key);
}
public Long lpush(String key, String... values) {
return jedisPool.getResource().lpush(key, values);
}
public Long rpush(String key, String... values) {
return jedisPool.getResource().rpush(key, values);
}
public String lpop(String key) {
return jedisPool.getResource().lpop(key);
}
public String rpop(String key) {
return jedisPool.getResource().rpop(key);
}
public Long del(String key) {
return jedisPool.getResource().del(key);
}
}
|
import java.util.*;
public class geography
{
static KBC obj = new KBC();
public static double question()
{
double i,r=0;
for (i = 0 ; r<10000;i++ )
{
i = Math.random();
r = i*10;
if(r<3&&r>-1)
{
break;
}
}
return r;
}
public static void soil()
{
geography ob = new geography();
for (int i = 1 ; i<2; i++)
{
int q[] = {(int)question()};
if(q[0]==0)
{
obj.ques++;
System.out.println("Q"+obj.ques+". Which soilis formed from ancient crystalline \n and metamorphic rock :");
System.out.println("1: Red soil 2: Black soil" );
System.out.println("3: Laterite soil 4: Alluvial soil ");
obj.correct=1;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==1)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==1)
{
obj.ques++;
System.out.println("Q"+obj.ques+". Which soil is also called regur soil : ");
System.out.println("1: Laterite soil \t 2: Black soil" );
System.out.println("3: Alluvial soil \t 4: Red Soil");
obj.correct=2;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==2)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==2)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". Which soil is slightly acidic in nature :");
System.out.println("1: Red soil \t 2: Alluvial soil" );
System.out.println("3: Black soil \t 4: Laterite soil");
obj.correct=4;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==4)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
}
}
public static void vegetation()
{
geography ob = new geography();
for (int i = 1 ; i<2; i++)
{
int q[] = {(int)question()};
if(q[0]==0)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". Process of planting trees on commercial basis :");
System.out.println("1: Sericulture \t 2: Horticulture" );
System.out.println("3: Silviculture \t 4: Afforestation");
obj.correct=3;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==3)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==1)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". What is rainfall requirement for deciduous forests : ");
System.out.println("1: >200 cm \t 2: 100-200 cm" );
System.out.println("3: 25 cm \t 4: 150-250 cm");
obj.correct=2;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==2)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==2)
{
obj.ques++;
System.out.println("Q "+obj.ques+". Which of the following trees have breathing roots :");
System.out.println("1: Hintal \t 2: Mava" );
System.out.println("3: Semul \t 4: Myrobalan");
obj.correct=1;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==1)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
}
}
public static void water()
{
geography ob = new geography();
for (int i = 1 ; i<2; i++)
{
int q[] = {(int)question()};
if(q[0]==0)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". Which is the longest canal in the world :");
System.out.println("1: Suez Canal \t 2: Indira Gandhi Canal" );
System.out.println("3: Saida Canal \t 4: Panama Canal");
obj.correct=2;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==2)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==1)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". Which canal is not located in Andhra Pradesh :");
System.out.println("1: Sirhind Canal \t 2: Godavari Canal " );
System.out.println("3: Krishna Delta Canal \t 4: Tungabhadra Canal");
obj.correct=1;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==1)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
if(q[0]==2)
{
obj.ques++;
System.out.println("Q"+ obj.ques+". What % of world's total water resources \n does India have :");
System.out.println("1: 1% \t 2: 2%" );
System.out.println("3: 3% \t 4: 4%");
obj.correct=4;
System.out.println("If you want to use lifeline press Y else N :");
obj.ch = new Scanner(System.in).nextLine().charAt(0);
if(obj.ch=='y'||obj.ch=='Y')
{
System.out.println("1:Expert's Advice \t 2:Audiance phone");
System.out.println("3:Phone a friend \t 4:Answer by computer");
System.out.println("Choose any of the lifeline that you have not yet choosen");
obj.cl = new Scanner(System.in).nextInt();
lifeline1.main();
lifeline2.main();
lifeline3.main();
lifeline4.main();}
System.out.println("Enter your choice :");
obj.c = new Scanner(System.in).nextInt();
if(obj.c==4)
{
System.out.println("Your answer is correct");
obj.i++;
System.out.println("Your balance is Rs "+obj.r[obj.i]);
}
else
{
System.out.println("Your answer is wrong");
obj.i--;
System.out.println("Your reduced balance is Rs "+obj.r[obj.i]);
}
System.out.println("Press any letter to continue: ");
obj.cont = new Scanner(System.in).nextLine().charAt(0);
System.out.println("\f");
}
}
}
public static void main()
{
geography ob = new geography();
int r = (int)question();
if(r==0)
{
ob.soil();
}
if(r==1)
{
ob.vegetation();
}
if(r==2)
{
ob.water();
}
}
}
|
package com.tencent.xweb.xwalk.a;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build.VERSION;
import com.tencent.smtt.utils.TbsLog;
import com.tencent.xweb.xwalk.a.a.a;
import com.tencent.xweb.xwalk.a.a.b;
import org.xwalk.core.NetworkUtil;
import org.xwalk.core.XWalkEnvironment;
import org.xwalk.core.XWalkInitializer;
public class c {
static c vFw;
static a vFx;
private c() {
}
public static synchronized c cJo() {
c cVar;
synchronized (c.class) {
if (vFw == null) {
vFw = new c();
}
cVar = vFw;
}
return cVar;
}
public static void Iy(int i) {
if (NetworkUtil.isNetworkAvailable()) {
SharedPreferences sharedPreferencesForUpdateConfig = XWalkEnvironment.getSharedPreferencesForUpdateConfig();
int i2 = sharedPreferencesForUpdateConfig.getInt("nTryCnt", 0) + 1;
if (i <= -2 && i >= -5) {
i2 += 3;
}
if (i2 > 3) {
XWalkInitializer.addXWalkInitializeLog("FailedTooManytimes at this version");
XWalkInitializer.addXWalkInitializeLog("abandon Current Scheduler");
a(null);
return;
}
cJv().vFC = i2;
Editor edit = sharedPreferencesForUpdateConfig.edit();
edit.putInt("nTryCnt", i2);
a(edit, i2);
edit.commit();
}
}
private static synchronized void a(Editor editor, int i) {
synchronized (c.class) {
long currentTimeMillis = System.currentTimeMillis() + ((long) (7200000 * i));
XWalkInitializer.addXWalkInitializeLog("rescheduler update time after " + ((7200000 * i) / 60000) + " minute");
editor.putLong("nTimeToUpdate", currentTimeMillis);
}
}
public static a a(a aVar) {
if (aVar == null) {
return null;
}
a cJv = cJv();
if (cJv == null || cJv.vFl == aVar.vFl) {
return null;
}
com.tencent.xweb.xwalk.a.a.c cVar;
int i;
cJv = new a();
if (aVar == null || aVar.vFm == null || aVar.vFm.length == 0) {
cVar = null;
} else {
i = VERSION.SDK_INT;
for (com.tencent.xweb.xwalk.a.a.c cVar2 : aVar.vFm) {
if (cVar2 != null) {
if (cVar2.vFr >= 49) {
if (cVar2.vFr > XWalkEnvironment.getAvailableVersion()) {
if (cVar2.vCo.cID()) {
cVar = cVar2;
break;
}
XWalkInitializer.addXWalkInitializeLog("no matched version filter retunr false");
} else {
XWalkInitializer.addXWalkInitializeLog("no matched version getAvailableVersion above ");
}
} else {
XWalkInitializer.addXWalkInitializeLog("no matched version below min support apk version ");
}
} else {
XWalkInitializer.addXWalkInitializeLog("no matched version version == null");
}
}
XWalkInitializer.addXWalkInitializeLog("no matched version");
cVar = null;
}
if (cVar == null || cVar.vFr <= XWalkEnvironment.getAvailableVersion()) {
XWalkInitializer.addXWalkInitializeLog("no matched version");
cJv = null;
} else {
XWalkInitializer.addXWalkInitializeLog("got matched version");
cJv.vFl = aVar.vFl;
cJv.vFk = cVar.vFk;
cJv.vFr = cVar.vFr;
cJv.vFB = cVar.vFu.vFv;
cJv.vFq = cVar.vFq;
cJv.bUseCdn = cVar.bUseCdn;
if (cVar.vFt != null) {
for (b bVar : cVar.vFt) {
if (bVar.vFo == XWalkEnvironment.getAvailableVersion()) {
XWalkInitializer.addXWalkInitializeLog("got matched patch");
break;
}
}
}
XWalkInitializer.addXWalkInitializeLog("no matched patch");
b bVar2 = null;
if (bVar2 != null) {
cJv.vFz = true;
cJv.vFp = bVar2.vFp;
cJv.bxD = bVar2.vFk;
cJv.vFq = bVar2.vFq;
cJv.bUseCdn = bVar2.bUseCdn;
} else {
cJv.vFz = false;
cJv.vFp = cVar.vFp;
}
i = (int) (Math.random() * ((double) cVar.vFs));
cJv.vFA = ((long) ((i * 60) * TbsLog.TBSLOG_CODE_SDK_BASE)) + System.currentTimeMillis();
XWalkInitializer.addXWalkInitializeLog("schedul after " + i + " minute to update");
}
if (cJv == null) {
return null;
}
a(cJv);
return cJv;
}
public static boolean cJp() {
if (!cJq()) {
return false;
}
XWalkInitializer.addXWalkInitializeLog("has scheduler for update");
return true;
}
public static synchronized boolean cJq() {
boolean z = false;
synchronized (c.class) {
if (!(cJv() == null || cJv().vFp == null || cJv().vFp.isEmpty())) {
if (cJv().vFr > XWalkEnvironment.getAvailableVersion()) {
z = true;
}
}
}
return z;
}
public final synchronized boolean cJr() {
boolean z = false;
synchronized (this) {
if (cJq()) {
if (System.currentTimeMillis() >= cJv().vFA) {
XWalkInitializer.addXWalkInitializeLog("time to update");
z = true;
} else {
XWalkInitializer.addXWalkInitializeLog("has scheduler waiting for update, but time is not up");
}
}
}
return z;
}
public final synchronized void cJs() {
Editor edit = XWalkEnvironment.getSharedPreferencesForUpdateConfig().edit();
edit.putLong("nLastFetchConfigTime", 0);
edit.putLong("nTimeToUpdate", 0);
edit.commit();
cJv().vFy = 0;
cJv().vFA = 0;
}
public static synchronized void a(a aVar) {
synchronized (c.class) {
vFx = aVar;
if (aVar == null) {
vFx = new a();
}
Editor edit = XWalkEnvironment.getSharedPreferencesForUpdateConfig().edit();
edit.putString("strMd5", vFx.vFk);
edit.putString("strUrl", vFx.vFp);
edit.putString("strConfigVer", vFx.vFl);
edit.putBoolean("bIsPatchUpdate", vFx.vFz);
edit.putBoolean("bCanUseCellular", vFx.vFq);
edit.putBoolean("bUseCdn", vFx.bUseCdn);
edit.putLong("nTimeToUpdate", vFx.vFA);
edit.putInt("nApkVer", vFx.vFr);
edit.putInt("nTryCnt", vFx.vFC);
edit.putString("strPatchMd5", vFx.bxD);
edit.putString("strVersionDetail", vFx.vFB);
edit.commit();
}
}
public static void cJt() {
cJv().vFy = System.currentTimeMillis();
Editor edit = XWalkEnvironment.getSharedPreferencesForUpdateConfig().edit();
edit.putLong("nLastFetchConfigTime", cJv().vFy);
edit.commit();
}
private static boolean M(long j, long j2) {
if (j > j2 + 86400000 || j + 86400000 < j2) {
return true;
}
XWalkInitializer.addXWalkInitializeLog("the most recent time to fetch config is too close");
return false;
}
public static boolean cJu() {
if (cJq()) {
XWalkInitializer.addXWalkInitializeLog("has scheduler , don't need to fetch config");
return false;
}
long currentTimeMillis = System.currentTimeMillis();
if (!M(currentTimeMillis, cJv().vFy)) {
return false;
}
long j = XWalkEnvironment.getSharedPreferencesForUpdateConfig().getLong("nLastFetchConfigTime", 0);
cJv().vFy = j;
if (!M(currentTimeMillis, j)) {
return false;
}
XWalkInitializer.addXWalkInitializeLog("enough time after last time fetch config");
return true;
}
public static a cJv() {
if (vFx != null) {
return vFx;
}
vFx = new a();
SharedPreferences sharedPreferencesForUpdateConfig = XWalkEnvironment.getSharedPreferencesForUpdateConfig();
vFx.vFy = sharedPreferencesForUpdateConfig.getLong("nLastFetchConfigTime", 0);
if (!sharedPreferencesForUpdateConfig.contains("strUrl")) {
return vFx;
}
vFx.vFk = sharedPreferencesForUpdateConfig.getString("strMd5", null);
vFx.vFp = sharedPreferencesForUpdateConfig.getString("strUrl", null);
vFx.vFl = sharedPreferencesForUpdateConfig.getString("strConfigVer", null);
vFx.vFz = sharedPreferencesForUpdateConfig.getBoolean("bIsPatchUpdate", false);
vFx.vFA = sharedPreferencesForUpdateConfig.getLong("nTimeToUpdate", 0);
vFx.vFr = sharedPreferencesForUpdateConfig.getInt("nApkVer", 0);
vFx.vFC = sharedPreferencesForUpdateConfig.getInt("nTryCnt", 0);
vFx.bxD = sharedPreferencesForUpdateConfig.getString("strPatchMd5", null);
vFx.vFB = sharedPreferencesForUpdateConfig.getString("strVersionDetail", null);
vFx.vFq = sharedPreferencesForUpdateConfig.getBoolean("bCanUseCellular", false);
vFx.bUseCdn = sharedPreferencesForUpdateConfig.getBoolean("bUseCdn", false);
return vFx;
}
}
|
package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JOptionPane;
import models.Query;
import persistence.FileManager;
import views.DialogDeleteVotes;
import views.WindowQueryAnticorruption;
public class Controller implements ActionListener {
private Query query;
private WindowQueryAnticorruption windowQueryAnticorruption;
private FileManager fileManager;
private DialogDeleteVotes dialogDeleteVotes;
public Controller() {
fileManager = new FileManager();
query = new Query();
try {
windowQueryAnticorruption = new WindowQueryAnticorruption(this, fileManager.readDepartaments());
dialogDeleteVotes = new DialogDeleteVotes(windowQueryAnticorruption, this);
} catch (IOException ex) {
System.err.println("No se pudo leer el archivo");
}
}
@Override
public void actionPerformed(ActionEvent e) {
switch (Events.valueOf(e.getActionCommand())) {
case SHOW_DELETE_VOTES_DIALOG:
showDeleteVotesDialog();
break;
case REGISTOR_VOTES:
registorVotes();
break;
case DELETE_VOTES:
deleteVotes();
break;
case SHOW_PEOPLE_PERCENTAGE:
showPeoplePercentage();
break;
}
}
private void showDeleteVotesDialog() {
dialogDeleteVotes.setVisible(true);
}
private void registorVotes() {
query.recordVotesObtained(windowQueryAnticorruption.getVotesNumber(), windowQueryAnticorruption.getDepartament());
windowQueryAnticorruption.registorVotes(query.getVotesNumber());
if (query.theTresholdVotesWasReached()) {
windowQueryAnticorruption.goalSucessfull();
}
}
private void deleteVotes() {
query.deleteVotes(dialogDeleteVotes.deleteVotes());
windowQueryAnticorruption.registorVotes(query.getVotesNumber());
if (!query.theTresholdVotesWasReached()) {
windowQueryAnticorruption.sayFail();
}
dialogDeleteVotes.setVisible(false);
}
private void showPeoplePercentage() {
JOptionPane.showMessageDialog(windowQueryAnticorruption, "No votaron el " + query.countHowManyPeopleDidNotVote() + "% de personas");
}
}
|
package interviewbit.array;
import java.util.ArrayList;
public class Interval {
public int start;
public int end;
public Interval() {
start = 0;
end = 0;
}
public Interval(int s, int e) {
start = s;
end = e;
}
public ArrayList<Interval> insertInterval(ArrayList<Interval> intervals,
Interval newInterval) {
int startPoint = -1;
int endPoint = -1;
int startIndex = 0;
int endIndex = 0;
for (Interval o : intervals) {
System.out.println("Interval : " + o.start + "\t" + o.end);
}
System.out.println("new interval = " + newInterval.start + "\t"
+ newInterval.end);
if (newInterval.start > newInterval.end) {
int temp = newInterval.start;
newInterval.start = newInterval.end;
newInterval.end = temp;
System.out.println("UPDATED interval = " + newInterval.start + "\t"
+ newInterval.end);
}
if (intervals.isEmpty()) {
intervals.add(newInterval);
return intervals;
}
if (newInterval.start <= intervals.get(0).start
&& newInterval.end >= intervals.get(intervals.size() - 1).end) {
intervals.clear();
intervals.add(newInterval);
return intervals;
}
if (newInterval.start > intervals.get(intervals.size() - 1).end) {
intervals.add(newInterval);
return intervals;
}
if (newInterval.end < intervals.get(0).start) {
intervals.add(0, newInterval);
return intervals;
}
if (newInterval.start < intervals.get(0).start
&& newInterval.end == intervals.get(0).end) {
intervals.get(0).start = newInterval.start;
return intervals;
}
for (int a = 0; a < intervals.size(); a++) {
if (newInterval.start < intervals.get(a).end) {
if (newInterval.end < intervals.get(a).start) {
intervals.add(a, newInterval);
return intervals;
} else {
int m = a;
// System.out.println(a);
if (newInterval.start < intervals.get(a).start) {
startPoint = newInterval.start;
if (a > 0) {
startIndex = a - 1;
}
} else {
startPoint = intervals.get(a).start;
startIndex = a;
}
while (m < intervals.size()) {
if (newInterval.end <= intervals.get(m).end) {
if (newInterval.end >= intervals.get(m).start) {
endPoint = intervals.get(m).end;
endIndex = m;
break;
} else {
endPoint = newInterval.end;
endIndex = m;
break;
}
} else {
if (m > a) {
/*
* System.out.println("LAST ELSE\t start = " +
* intervals.get(m).start + "\tend" +
* intervals.get(m).end);
*/
intervals.remove(m);
} else
m++;
}
}
// System.out.println("start = " + startPoint +
// "\tend = "
// + endPoint);
if (startPoint != 0 && endPoint != 0) {
break;
}
}
}
}
for (Interval o : intervals) {
System.out.println("Interval : " + o.start + " " + o.end);
}
System.out.println("POINTS\t\t\tstart = " + startPoint + "\tend = "
+ endPoint);
System.out.println("\nINDEX\tstart = " + startIndex + "\tend = "
+ endIndex);
if (startPoint != -1 && endPoint != -1) {
if (intervals.get(startIndex).end >= startPoint) {
if (intervals.get(endIndex).start > endPoint) {
intervals.get(startIndex).end = endPoint;
if (intervals.get(startIndex).start > startPoint) {
intervals.get(startIndex).start = startPoint;
}
return intervals;
} else {
intervals.get(startIndex).end = intervals.get(endIndex).end;
intervals.remove(endIndex);
if (intervals.get(startIndex).start > startPoint) {
intervals.get(startIndex).start = startPoint;
}
return intervals;
}
} else {
intervals.get(startIndex + 1).start = startPoint;
if (intervals.get(startIndex + 1).end <= endPoint) {
intervals.get(startIndex + 1).end = endPoint;
if ((startIndex + 1) != endIndex) {
if (intervals.get(startIndex + 1).end == intervals
.get(endIndex).end) {
intervals.remove(endIndex);
}
}
return intervals;
}
if ((startIndex + 1) != endIndex) {
if (intervals.get(startIndex + 1).end > intervals
.get(endIndex).start) {
intervals.get(startIndex + 1).end = intervals
.get(endIndex).end;
intervals.remove(endIndex);
return intervals;
}
}
}
}
if (startPoint == -1 && endPoint == -1) {
System.out.println("WTF");
}
if (startPoint != -1 && endPoint == -1) {
if (intervals.get(startIndex).end < startPoint) {
if (intervals.get(startIndex + 1).start > startPoint) {
intervals.get(startIndex + 1).start = startPoint;
}
if (intervals.get(startIndex + 1).end < newInterval.end) {
intervals.get(startIndex + 1).end = newInterval.end;
}
return intervals;
} else {
intervals.get(startIndex).end = newInterval.end;
return intervals;
}
}
return intervals;
}
}
|
public class Chief extends FullTime {
public float salary(int[] workingHours) {
int dayOfWork = 5 * 4;
int severancePay = (2016 - getYearOfStart()) * 16;
int overWorkHours = 0;
for (int i = 0; i < 4; i++) {
if ((workingHours[i]-40) > 8)
overWorkHours += 8;
else
overWorkHours += (workingHours[i]-40);
}
int overWorkSalary = overWorkHours * 5;
float totalSalary = dayOfWork * 84 + severancePay + overWorkSalary;
return totalSalary;
}
}
|
package idv.randy.petwall;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.java.iPet.R;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.sql.Date;
import idv.randy.ut.AsyncAdapter;
import idv.randy.ut.AsyncImageTask;
import idv.randy.ut.AsyncObjTask;
import idv.randy.ut.Me;
public class PwDetailActivity extends AppCompatActivity implements PwDetailFragment.OnListFragmentInteractionListener, View.OnClickListener {
private static final String TAG = "PwDetailActivity";
private static PwrListener pwrListener;
private Bundle arguments;
private int pwNo;
private int memNo;
private EditText etPwrContent;
private ImageView ivSend;
private ImageView ivPwPicture;
private LinearLayout llPwr;
private FloatingActionButton btnFab;
private PwDetailFragment fragment = new PwDetailFragment();
private SharedPreferences pref;
private boolean loginStatus;
View.OnClickListener onSendListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = etPwrContent.getText().toString();
if (content.trim().equals("")) {
hideKeyPad();
llPwr.setVisibility(View.GONE);
btnFab.setVisibility(View.VISIBLE);
return;
}
if (!loginStatus) {
Toast.makeText(Me.gc(), "登入後可留言", Toast.LENGTH_SHORT).show();
return;
}
// try {
// new AsyncObjTask(null, insertPwr(content)).execute(Me.PwrServlet).get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
// hideKeyPad();
// PwDetailFragment fragment = new PwDetailFragment();
// fragment.setArguments(arguments);
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.item_detail_container, fragment)
// .commit();
// etPwrContent.setText("");
// llPwr.setVisibility(View.GONE);
// btnFab.setVisibility(View.VISIBLE);
// pwrListener.onPwrSend();
new AsyncObjTask(new AsyncAdapter() {
@Override
public void onFinish(String result) {
super.onFinish(result);
PwDetailFragment fragment = new PwDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
pwrListener.onPwrSend();
}
}, insertPwr(content)).execute(Me.PwrServlet);
etPwrContent.setText("");
hideKeyPad();
llPwr.setVisibility(View.GONE);
btnFab.setVisibility(View.VISIBLE);
}
};
public static void start(Context context, int pwNo, int memNo) {
Intent intent = new Intent(context, PwDetailActivity.class);
intent.putExtra("pwNo", pwNo);
intent.putExtra("memNo", memNo);
context.startActivity(intent);
if (context instanceof PwrListener) {
pwrListener = (PwrListener) context;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.r_activity_pw_detail);
findViews();
btnFab.setVisibility(View.VISIBLE);
llPwr.setVisibility(View.GONE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("");
}
pref = getSharedPreferences("UserData", MODE_PRIVATE);
loginStatus = pref.getBoolean("login", false);
btnFab.setOnClickListener(this);
Intent intent = getIntent();
pwNo = intent.getExtras().getInt("pwNo");
memNo = intent.getExtras().getInt("memNo");
new AsyncImageTask(pwNo, ivPwPicture, R.drawable.aa1418273).execute(Me.PetServlet);
if (savedInstanceState == null) {
arguments = new Bundle();
arguments.putInt("pwNo",
pwNo);
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
ivSend.setOnClickListener(onSendListener);
}
private void findViews() {
etPwrContent = (EditText) findViewById(R.id.etPwrContent);
llPwr = (LinearLayout) findViewById(R.id.llPwr);
btnFab = (FloatingActionButton) findViewById(R.id.btnFab);
ivSend = (ImageView) findViewById(R.id.ivSend);
ivPwPicture = (ImageView) findViewById(R.id.ivPwPicture);
}
private JsonObject insertPwr(String content) {
PwrVO pwrVO = new PwrVO();
pwrVO.setPwrdate(new Date(System.currentTimeMillis()));
pwrVO.setPwrcontent(content);
pwrVO.setMemno(pref.getInt("memNo", 0));
pwrVO.setPwno(pwNo);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "insertPwr");
jsonObject.addProperty("pwrVO", gson.toJson(pwrVO));
return jsonObject;
}
@Override
public void onListFragmentInteraction(PwrVO item) {
}
@Override
public void refresh() {
arguments = new Bundle();
arguments.putInt("pwNo",
pwNo);
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SharedPreferences pref = getSharedPreferences("UserData", MODE_PRIVATE);
if (loginStatus && pref.getInt("memNo", 0) == memNo) {
getMenuInflater().inflate(R.menu.menu_pw_detail, menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
switch (item.getItemId()) {
case R.id.delete:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "deletePw");
jsonObject.addProperty("pwNo", pwNo);
new AsyncObjTask(null, jsonObject).execute(Me.PetServlet);
if (pwrListener != null) {
pwrListener.onDelete();
}
break;
}
return super.onOptionsItemSelected(item);
}
void hideKeyPad() {
etPwrContent.clearFocus();
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(this
.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnFab:
if (!loginStatus) {
Toast.makeText(Me.gc(), "登入後可留言", Toast.LENGTH_SHORT).show();
return;
}
btnFab.setVisibility(View.GONE);
llPwr.setVisibility(View.VISIBLE);
showKeyboard();
break;
}
}
private void showKeyboard() {
etPwrContent.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(etPwrContent, 0);
}
public interface PwrListener {
void onPwrSend();
void onDelete();
}
}
|
package com.fixit.notifications;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import com.fixit.app.R;
import com.fixit.feedback.OrderFeedbackFlowManager;
import com.fixit.feedback.OrderFeedbackNotificationData;
import com.fixit.ui.activities.OrderFeedbackActivity;
import com.fixit.utils.Constants;
import java.util.concurrent.TimeUnit;
/**
* Created by Kostyantin on 7/16/2017.
*/
public class OrderNotificationManager {
public static void initiateOrderFeedback(Context context, String orderId) {
Intent intent = new Intent();
intent.setAction(OrderFeedbackNotificationReceiver.ACTION);
OrderFeedbackNotificationData[] notificationData = OrderFeedbackFlowManager.createNotificationData(context, orderId);
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
for(OrderFeedbackNotificationData data : notificationData) {
intent.putExtra(Constants.ARG_NOTIFICATION_DATA, data);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + TimeUnit.MINUTES.toMillis(data.delayMin), alarmIntent);
}
}
public static void registerOrderFeedbackNotification(Context context, String orderId, boolean sendImmediately, int forFlow) {
Intent intent = new Intent();
intent.setAction(OrderFeedbackNotificationReceiver.ACTION);
OrderFeedbackNotificationData[] notificationData = OrderFeedbackFlowManager.createNotificationData(context, orderId, forFlow);
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
for(OrderFeedbackNotificationData data : notificationData) {
intent.putExtra(Constants.ARG_NOTIFICATION_DATA, data);
if(sendImmediately) {
context.sendBroadcast(intent);
} else {
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + TimeUnit.MINUTES.toMillis(data.delayMin), alarmIntent);
}
}
}
static Notification createOrderFeedbackNotification(Context context, OrderFeedbackNotificationData data, int notificationRequestCode) {
Notification notification = new NotificationCompat.Builder(context)
//.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_xl_yellow_logo_white_border))
.setSmallIcon(R.drawable.ic_large_yellow_logo_white_border)
.setContentTitle(data.title)
.setContentText(data.message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(data.message))
.setAutoCancel(true)
.setContentIntent(createPendingIntent(context, 1, data.orderId, data.flowCode, false, false, notificationRequestCode))
.addAction(createAction(context, 2, data.orderId, data.flowCode, true, notificationRequestCode))
.addAction(createAction(context, 3, data.orderId, data.flowCode, false, notificationRequestCode))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[] {1, 1, 1})
.build();
notification.flags |= Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_ONLY_ALERT_ONCE;
return notification;
}
private static NotificationCompat.Action createAction(Context context, int requestCode, String orderId, int flowCode, boolean yesAction, int notificationRequestCode) {
int drawableId;
int textId;
if(yesAction) {
drawableId = R.drawable.ic_check_white_24dp;
textId = R.string.yes;
} else {
drawableId = R.drawable.ic_close_white_24dp;
textId = R.string.no;
}
return new NotificationCompat.Action.Builder(
drawableId,
context.getString(textId),
createPendingIntent(context, requestCode, orderId, flowCode, true, yesAction, notificationRequestCode)
).build();
}
private static PendingIntent createPendingIntent(Context context, int requestCode, String orderId, int flowCode, boolean fromAction, boolean yesAction, int notificationRequestCode) {
Intent intent;
if(!fromAction) {
intent = createDefaultIntent(context, orderId, flowCode);
} else {
intent = createActionIntent(context, orderId, flowCode, yesAction);
}
intent.putExtra(Constants.ARG_NOTIFICATION_REQUEST_CODE, notificationRequestCode);
return PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
private static Intent createActionIntent(Context context, String orderId, int flowCode, boolean yesAction) {
Intent intent = createIntent(context, orderId, flowCode);
intent.putExtra(Constants.ARG_FROM_ACTION, true);
intent.putExtra(Constants.ARG_SELECTED_YES, yesAction);
return intent;
}
private static Intent createDefaultIntent(Context context, String orderId, int flowCode) {
Intent intent = createIntent(context, orderId, flowCode);
intent.putExtra(Constants.ARG_FROM_ACTION, false);
return intent;
}
private static Intent createIntent(Context context, String orderId, int flowCode) {
Intent intent = new Intent(context, OrderFeedbackActivity.class);
intent.putExtra(Constants.ARG_ORDER_ID, orderId);
intent.putExtra(Constants.ARG_FLOW_CODE, flowCode);
return intent;
}
}
|
package edu.wpi.teamname;
public class FizzBuzzWhiz {
public FizzBuzzWhiz() {}
public String answer(int number) {
if (number % 3 == 0 && number % 5 == 0) {
return "fizzbuzz";
} else if (number % 3 == 0) {
return "fizz";
} else if (number % 5 == 0) {
return "buzz";
} else if (isPrime(number)) {
return "whiz";
} else {
return String.valueOf(number);
}
}
static boolean isPrime(int n) {
// Corner case
if (n <= 1) return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++) if (n % i == 0) return false;
return true;
}
}
|
/**
* MrHan 所提供的文字处理工具类
*/
package com.mrhan.text;
|
package com.mrhan.util;
/**
* 其他工具类
*/
public class OtherUtil {
/**
* 判断一个字符串是否是数字 +1 -1 -1.1 都可以识别数字
*
* @param str 检测字符串
* @return Boolean true代表是数字
*/
public static boolean isNumber(String str){
int p= 0;//当前字符下标
int l = str.length();//字符串长度
if(str.isEmpty())//判断字符串是否为空
return false;
char c = str.charAt(p);//获取第一个字符
if(str.indexOf(".") != str.lastIndexOf("."))//判断是否有多个小数点
return false;
if(c=='-' || c=='+'){//判断第一位是否有占位符 + -
p++;
while(p<l){
c= str.charAt(p++);
if(c<'0' || c>'9'){
return false;
}
}
}else if(c>='0' && c<='9'){//判断第一位是否是数字
while(p<l){
c= str.charAt(p++);
if(c<'0' || c>'9'){
return false;
}
}
}else{
return false;
}
return true;
}
}
|
package discreteStochaticSim;
import antColony.HCResults;
import antColony.HamiltonianCycle;
import antColony.OptProblem;
import antColony.StochasticOptimProb;
import discreteStochaticSim.*;
import graph.graph;
/************************************************************************************
* Controlo dos Prints do Evento
*
* @author Grupo 11
*
* <p> Esta subclasse e uma extensao da classe Event abstrata e manipulara os eventos
* Control Print. Nao possui campos em si, mas herda o tempo e o individuo da superclasse.
* Individual e definido como nulo e o tempo e definido como um multiplo do tempo total
* dividido por 20. Ele precisa sobrescrever os metodos Execute Event e toString.
*
***********************************************************************************/
public class EventControlPrints extends Event {
/* ==== ATRIBUTOS ==== */
<<<<<<< HEAD:discreteStochaticSim/EventControlPrints.java
=======
>>>>>>> master:antColony/EventControlPrints.java
/* ==== CONSTRUTORES ==== */
/*********************************************************************************************
* Este e o construtor.O que ele faz e chamar o construtor da super classe com
* os argumentos indicados. Ant e sempre null uma vez que nao fazemos "target"
* a uma formiga em especifico.
*
* @param time e o instante em que queremos imprimir a informacao de controlo.
**********************************************************************************************/
public EventControlPrints(double time) {
super(time, null);
}
/* ==== METODOS ==== */
/*********************************************************************************************
* Este metodo e uma redefinicao do metodo geral de evento com o mesmo nome.
*
* Neste caso em particular, temos que imprimir as informacoes de controle solicitadas no
* enunciado do projeto.
*
* @param opP -- Problema de Optimizacao com os dados todos a analisar
* @param gr -- grafo do problema a optimizar
* @param hC -- ciclo hamiltoniano
**********************************************************************************************/
public void ExecutaEvent(OptProblem opP,graph<Integer,Integer> gr,HamiltonianCycle<Integer,Integer> hC)
{
String formato1 = "%-35s %-16f\n";
String formato2 = "%-35s %-17d\n";
HCResults opt;
StochasticOptimProb op = (StochasticOptimProb) opP;
int numControl = op.getNumControlPrint();
op.setNumControlPrint(op.getNumControlPrint()+1);
System.out.println("Observation " + numControl + ":");
System.out.println("\t\t");
System.out.printf(formato1,"Present Instant: ",op.p.getActual_time());
System.out.println("\t\t");
System.out.printf(formato2, "Number of move events: ",op.get_mevent());
System.out.println("\t\t");
System.out.printf(formato2, "Number of evaporation events: ",op.get_eevent());
System.out.println("\t\t");
opt=op.findOpt();
<<<<<<< HEAD:discreteStochaticSim/EventControlPrints.java
System.out.print(opt.getPath());
=======
System.out.print("Hamiltonian cycle: " + opt);
/**
* falta o caminho ....
*/
>>>>>>> master:antColony/EventControlPrints.java
System.out.println();
}
}
|
package net.plazmix.core.api.spigot;
import net.plazmix.core.api.CoreApi;
import net.plazmix.core.api.common.command.CommandBuilder;
import net.plazmix.core.api.spigot.inventory.view.builder.GlobalViewInventoryBuilder;
import net.plazmix.core.api.spigot.inventory.view.builder.PersonalViewInventoryBuilder;
import net.plazmix.core.api.spigot.nametag.NametagManager;
import net.plazmix.core.api.spigot.sidebar.SidebarBuilder;
import org.bukkit.plugin.Plugin;
/**
* @author MasterCapeXD
*/
public interface SpigotCoreApi extends CoreApi {
Plugin getPlugin();
GlobalViewInventoryBuilder<?> newGlobalViewInventory();
GlobalViewInventoryBuilder<?> newGlobalViewInventory(Plugin plugin);
PersonalViewInventoryBuilder<?> newPersonalViewInventory();
PersonalViewInventoryBuilder<?> newPersonalViewInventory(Plugin plugin);
CommandBuilder newCommand(String holder, String name);
CommandBuilder newCommand(Plugin plugin, String name);
CommandBuilder newCommand(Plugin plugin, String holder, String name);
NametagManager getNametagManager();
SidebarBuilder newSidebar();
}
|
package edu.curd.operation.student;
import edu.curd.operation.*;
import edu.curd.dto.StudentDTO;
import edu.dbConnection.DatabaseConnection;
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 java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ManageStudent implements JDBCOperation {
@Override
public void setContext(Properties properties) {
this.contextProperties = properties;
}
private Properties contextProperties;
public ManageStudent(Properties contextProperties) {
this.setContext(contextProperties);
}
@Override
public List<Integer> create(List<JDBCDataObject> jdbcDataObjects) {
if (jdbcDataObjects != null && jdbcDataObjects.isEmpty()) {
return new ArrayList<>();
}
List<Integer> returnKeys = new ArrayList<>();
Connection connection = DatabaseConnection.getConnection(contextProperties);
PreparedStatement insertStatemtn = null;
String insertSQL = "INSERT INTO `classroom_records`.`student` (`first_name`,`last_name`,`gender`,`dob`,`phone`,`address`) VALUES(? , ? , ?, ? , ? , ? );";
try {
connection.setAutoCommit(false);
insertStatemtn = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
for (JDBCDataObject rawDTO : jdbcDataObjects) {
StudentDTO student = (StudentDTO) rawDTO;
insertStatemtn.setString(1, student.getFirstName());
insertStatemtn.setString(2, student.getLastName());
insertStatemtn.setString(3, student.getGender());
insertStatemtn.setString(4, student.getDob());
insertStatemtn.setString(5, student.getPhone());
insertStatemtn.setString(6, student.getAddress());
insertStatemtn.executeUpdate();
ResultSet rs = insertStatemtn.getGeneratedKeys();
if (rs.next()) {
returnKeys.add(rs.getInt(1));
}
connection.commit();
}
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException sqlError) {
Logger.getLogger(ManageStudent.class.getName()).log(Level.SEVERE, "Error while performing the operation.", sqlError);
}
}
} finally {
if (insertStatemtn != null) {
try {
insertStatemtn.close();
} catch (SQLException ex) {
}
}
if (connection != null) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (SQLException ex) {
}
}
}
return returnKeys;
}
@Override
public List<Integer> update(List<JDBCDataObject> jdbcDataObjects) {
if (jdbcDataObjects != null && jdbcDataObjects.isEmpty()) {
return new ArrayList<>();
}
List<Integer> returnKeys = new ArrayList<>();
Connection connection = DatabaseConnection.getConnection(contextProperties);
PreparedStatement updateStatemtn = null;
String updateSQL = "UPDATE `classroom_records`.`student` SET `first_name` =?, `last_name` =?,`gender` = ?,`dob` = ?,`phone` =?,`address` = ? WHERE `student_id` = ?;";
try {
connection.setAutoCommit(false);
updateStatemtn = connection.prepareStatement(updateSQL);
for (JDBCDataObject rawDTO : jdbcDataObjects) {
StudentDTO student = (StudentDTO) rawDTO;
if (student.getStudentId() > 0) {
updateStatemtn.setString(1, student.getFirstName());
updateStatemtn.setString(2, student.getLastName());
updateStatemtn.setString(3, student.getGender());
updateStatemtn.setString(4, student.getDob());
updateStatemtn.setString(5, student.getPhone());
updateStatemtn.setString(6, student.getAddress());
updateStatemtn.setInt(7, student.getStudentId());
if (updateStatemtn.executeUpdate() > 0) {
returnKeys.add(student.getStudentId());
}
connection.commit();
}
}
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException sqlError) {
Logger.getLogger(ManageStudent.class.getName()).log(Level.SEVERE, "Error while performing the operation.", sqlError);
}
}
} finally {
if (updateStatemtn != null) {
try {
updateStatemtn.close();
} catch (SQLException ex) {
}
}
if (connection != null) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (SQLException ex) {
}
}
}
return returnKeys;
}
@Override
public List<Integer> delete(List<JDBCDataObject> jdbcDataObjects) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<JDBCDataObject> read(JDBCDataObject jdbcDataObjects) {
if (jdbcDataObjects == null) {
return new ArrayList<>();
}
List<JDBCDataObject> returnObjects = new ArrayList<>();
Connection connection = DatabaseConnection.getConnection(contextProperties);
PreparedStatement selectStatement = null;
StringBuilder selectSQL = generateSelectStatment(jdbcDataObjects);
try {
selectStatement = connection.prepareStatement(selectSQL.toString());
ResultSet results = selectStatement.executeQuery();
while (results.next()) {
returnObjects.add(new StudentDTO(results.getInt(1), results.getString(2), results.getString(3), results.getString(4), results.getString(5), results.getString(6), results.getString(7), results.getString(8))
);
}
} catch (SQLException e) {
System.err.print("Erro while listing data.");
} finally {
if (selectStatement != null) {
try {
selectStatement.close();
} catch (SQLException ex) {
}
}
if (connection != null) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (SQLException ex) {
}
}
}
return returnObjects;
}
private StringBuilder generateSelectStatment(JDBCDataObject jdbcDataObjects) {
StringBuilder selectSQL = new StringBuilder("SELECT * FROM `classroom_records`.`student` WHERE 1=1 ");
StudentDTO student = (StudentDTO) jdbcDataObjects;
if (student.getStudentId() > 0) {
selectSQL.append(" AND ").append("student_id=").append(student.getStudentId());
} else {
if (student.getFirstName() != null) {
selectSQL.append(" AND ").append("first_name=").append("'").append(student.getFirstName().trim()).append("'");
}
if (student.getLastName() != null) {
selectSQL.append(" AND ").append("last_name=").append("'").append(student.getLastName().trim()).append("'");
}
if (student.getGender() != null) {
selectSQL.append(" AND ").append("gender=").append("'").append(student.getGender().trim()).append("'");
}
if (student.getDob() != null) {
selectSQL.append(" AND ").append("dob=").append("'").append(student.getDob().trim()).append("'");
}
if (student.getPhone() != null) {
selectSQL.append(" AND ").append("phone=").append("'").append(student.getPhone().trim()).append("'");
}
if (student.getAddress() != null) {
selectSQL.append(" AND ").append("address=").append("'").append(student.getAddress().trim()).append("'");
}
if (student.getTimeStamp() != null) {
selectSQL.append(" AND ").append("created_ts=").append("'").append(student.getTimeStamp().trim()).append("'");
}
}
return selectSQL;
}
}
|
package com.boardex.demo.service;
import com.boardex.demo.domain.entity.BoardEntity;
import com.boardex.demo.domain.repository.BoardRepositoryInterface;
import com.boardex.demo.dto.BoardDto;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.*;
@Service
@AllArgsConstructor
public class BoardService {
private final BoardRepositoryInterface boardRepository;
private static final int DISPLAY_PAGE_LENGTH = 5; // pagination Block
private static final int DISPLAY_ENTITY_COUNT = 4; // 画面別表示するポストの数
@Transactional //トランザクションを適用するアノテーション
public Long savePost(BoardDto boardDto) {
return boardRepository.save(boardDto.toEntity()).getArticleNumber();
//save() ->DBのINSERT、UPDATE担当
}
/* 処理 - 掲示板ポストのリスト */
@Transactional
public List<BoardDto> getBoardList(Integer pageNum) {
/* Sort.by(Sort.Direction.DESC, "[基準カラム名]" でポスト目録の並べ替え */
Page<BoardEntity> page = boardRepository.findAll(PageRequest.of(pageNum - 1, DISPLAY_ENTITY_COUNT, Sort.by(Sort.Direction.DESC, "articleNumber")));
List<BoardEntity> boardEntities = page.getContent();
List<BoardDto> boardDtoList = new ArrayList<>();
for (BoardEntity boardEntity : boardEntities) {
boardDtoList.add(this.convertEntityToDto(boardEntity)); //Controller <--> Service 間のデータやり取りはDTOでするため
}
return boardDtoList;
}
@Transactional
public Long getBoardCount() {
// エンティティの数(DB内のテーブルの行数)を返す
return boardRepository.count();
}
public Integer[] getPageList(Integer curPageNum) {
Integer[] pageList = new Integer[DISPLAY_PAGE_LENGTH];
Double totalEntityCount = Double.valueOf(this.getBoardCount());
int totalPage = (int)(Math.ceil((totalEntityCount/ DISPLAY_ENTITY_COUNT)));
if(curPageNum <= 0){
curPageNum = 1;
}
int currentBlock = curPageNum % DISPLAY_PAGE_LENGTH == 0 ?
curPageNum / DISPLAY_PAGE_LENGTH : (curPageNum / DISPLAY_PAGE_LENGTH) + 1;
int startPage = (currentBlock-1) * DISPLAY_PAGE_LENGTH + 1;
int endPage = startPage+DISPLAY_PAGE_LENGTH -1;
if (endPage > totalPage) {
endPage = totalPage;
}
for (int val = startPage, idx = 0; val <= endPage; val++, idx++) {
pageList[idx] = val;
}
return pageList;
}
/* ポスト確認 */
public BoardDto getPost(Long articleNumber) {
Optional<BoardEntity> boardEntityWrapper = boardRepository.findById(articleNumber); //PKの値をwhere句に入れてデータを取る。
BoardEntity boardEntity = boardEntityWrapper.get(); // get() :WrapperからEntityを取得
return convertEntityToDto(boardEntity);
}
/* ポスト削除 */
@Transactional
public void deletePost(Long articleNumberBoardDto) {
boardRepository.deleteById(articleNumberBoardDto);
}
/* ポスト検索*/
@Transactional
public List<BoardDto> searchPosts(int searchOption, String keyword) {
List<BoardDto> boardDtoList = new ArrayList<>();
List<BoardEntity> boardEntities = new ArrayList<>();
switch (searchOption){
case 1: // 検索基準:タイトル
boardEntities = boardRepository.findByTitleContaining(keyword , Sort.by(Sort.Direction.DESC, "articleNumber"));
break;
case 2:// 検索基準:作成者
boardEntities = boardRepository.findByWriterContaining(keyword , Sort.by(Sort.Direction.DESC, "articleNumber"));
break;
case 3:// 検索基準:内容
boardEntities = boardRepository.findByContentContaining(keyword , Sort.by(Sort.Direction.DESC, "articleNumber"));
break;
default:
break;
}
if (boardEntities.isEmpty()) return boardDtoList;
for (BoardEntity boardEntity : boardEntities) {
boardDtoList.add(this.convertEntityToDto(boardEntity));
}
return boardDtoList;
}
private BoardDto convertEntityToDto(BoardEntity boardEntity) {
return BoardDto.builder()
.articleNumber(boardEntity.getArticleNumber())
.title(boardEntity.getTitle())
.content(boardEntity.getContent())
.writer(boardEntity.getWriter())
.createdDate(boardEntity.getCreatedDate())
.build();
}
public Map<String, Integer> getPrevEndPage(int curPageNum) {
Map<String, Integer> otherBlock = new HashMap<>();
Double totalEntityCount = Double.valueOf(this.getBoardCount());
int totalPage = (int)(Math.ceil((totalEntityCount/ DISPLAY_ENTITY_COUNT)));
if(curPageNum <= 0){
curPageNum = 1;
}
int currentBlock = curPageNum % DISPLAY_PAGE_LENGTH == 0 ?
curPageNum / DISPLAY_PAGE_LENGTH : (curPageNum / DISPLAY_PAGE_LENGTH) + 1;
int tempBlock = currentBlock;
if (currentBlock >= 2){
currentBlock = currentBlock - 1;
}
int startPage = (currentBlock-1) * DISPLAY_PAGE_LENGTH + 1;
int endPage = startPage+DISPLAY_PAGE_LENGTH -1;
if (endPage > totalPage) {
endPage = totalPage;
}
if(startPage == 1 && tempBlock == 1){
endPage = 1;
}
otherBlock.put("previous", endPage);
return otherBlock;
}
public Map<String, Integer> getNextStartPage(int curPageNum) {
Map<String, Integer> otherBlock = new HashMap<>();
Double totalEntityCount = Double.valueOf(this.getBoardCount());
int totalPage = (int)(Math.ceil((totalEntityCount/ DISPLAY_ENTITY_COUNT)));
if(curPageNum <= 0){
curPageNum = 1;
}
int currentBlock = curPageNum % DISPLAY_PAGE_LENGTH == 0 ?
curPageNum / DISPLAY_PAGE_LENGTH : (curPageNum / DISPLAY_PAGE_LENGTH) + 1;
currentBlock++;
int nextStartPage = (currentBlock-1) * DISPLAY_PAGE_LENGTH + 1;
otherBlock.put("next", nextStartPage);
otherBlock.put("total", totalPage);
return otherBlock;
}
}
|
Compiled from "FreezeAlien.java"
final class xfiles.T extends java.lang.Enum<xfiles.T> {
public static xfiles.T[] values();
Code:
0: getstatic #1 // Field $VALUES:[Lxfiles/T;
3: invokevirtual #2 // Method "[Lxfiles/T;".clone:()Ljava/lang/Object;
6: checkcast #3 // class "[Lxfiles/T;"
9: areturn
public static xfiles.T valueOf(java.lang.String);
Code:
0: ldc #4 // class xfiles/T
2: aload_0
3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #4 // class xfiles/T
9: areturn
static {};
Code:
0: iconst_0
1: anewarray #4 // class xfiles/T
4: putstatic #1 // Field $VALUES:[Lxfiles/T;
7: return
|
package com.mpakhomov.tree;
/**
* A node of Red Black Tree (BST)
*
* @author mpakhomov
* @since: 7/13/2015
* @param <T> the type of keys
*/
public class RbtNode<T extends Comparable<T>> extends BstNode {
boolean color = RedBlackTree.BLACK;
public RbtNode(T key, boolean color) {
super(key);
this.color = color;
}
public RbtNode(T key, boolean color, RbtNode<T> parent) {
super(key);
this.color = color;
this.parent = parent;
}
@Override
public String toString() {
return "key = " + key + ", left = " + (left != null ? left.key : "null") +
", right = " + (right != null ? right.key : "null") + ", parent = " +
(parent != null ? parent.key : "null") +
", color = " + (color == RedBlackTree.BLACK ? "B" : "R");
}
@Override
public String getKeyAsString() {
return key + ":" + (color == RedBlackTree.BLACK ? "B" : "R");
}
}
|
package com.mysql.cj.protocol.a;
import com.mysql.cj.Constants;
import com.mysql.cj.Messages;
import com.mysql.cj.conf.PropertyDefinitions;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.conf.PropertySet;
import com.mysql.cj.conf.RuntimeProperty;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.exceptions.UnableToConnectException;
import com.mysql.cj.exceptions.WrongArgumentException;
import com.mysql.cj.protocol.AuthenticationPlugin;
import com.mysql.cj.protocol.AuthenticationProvider;
import com.mysql.cj.protocol.Protocol;
import com.mysql.cj.protocol.ServerSession;
import com.mysql.cj.protocol.a.authentication.CachingSha2PasswordPlugin;
import com.mysql.cj.protocol.a.authentication.MysqlClearPasswordPlugin;
import com.mysql.cj.protocol.a.authentication.MysqlNativePasswordPlugin;
import com.mysql.cj.protocol.a.authentication.MysqlOldPasswordPlugin;
import com.mysql.cj.protocol.a.authentication.Sha256PasswordPlugin;
import com.mysql.cj.protocol.a.result.OkPacket;
import com.mysql.cj.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class NativeAuthenticationProvider implements AuthenticationProvider<NativePacketPayload> {
protected static final int AUTH_411_OVERHEAD = 33;
private static final String NONE = "none";
protected String seed;
private boolean useConnectWithDb;
private ExceptionInterceptor exceptionInterceptor;
private PropertySet propertySet;
private Protocol<NativePacketPayload> protocol;
public void init(Protocol<NativePacketPayload> prot, PropertySet propSet, ExceptionInterceptor excInterceptor) {
this.protocol = prot;
this.propertySet = propSet;
this.exceptionInterceptor = excInterceptor;
}
public void connect(ServerSession sessState, String user, String password, String database) {
long clientParam = sessState.getClientParam();
NativeCapabilities capabilities = (NativeCapabilities)sessState.getCapabilities();
NativePacketPayload buf = capabilities.getInitialHandshakePacket();
this.seed = capabilities.getSeed();
sessState.setServerDefaultCollationIndex(capabilities.getServerDefaultCollationIndex());
sessState.setStatusFlags(capabilities.getStatusFlags());
int capabilityFlags = capabilities.getCapabilityFlags();
if ((capabilityFlags & 0x8000) != 0) {
String seedPart2;
StringBuilder newSeed;
clientParam |= 0x8000L;
int authPluginDataLength = capabilities.getAuthPluginDataLength();
if (authPluginDataLength > 0) {
seedPart2 = buf.readString(NativeConstants.StringLengthDataType.STRING_FIXED, "ASCII", authPluginDataLength - 8);
newSeed = new StringBuilder(authPluginDataLength);
} else {
seedPart2 = buf.readString(NativeConstants.StringSelfDataType.STRING_TERM, "ASCII");
newSeed = new StringBuilder(20);
}
newSeed.append(this.seed);
newSeed.append(seedPart2);
this.seed = newSeed.toString();
} else {
throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_SECURE_CONNECTION is required", getExceptionInterceptor());
}
if ((capabilityFlags & 0x20) != 0 && ((Boolean)this.propertySet.getBooleanProperty(PropertyKey.useCompression).getValue()).booleanValue())
clientParam |= 0x20L;
this
.useConnectWithDb = (database != null && database.length() > 0 && !((Boolean)this.propertySet.getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue()).booleanValue());
if (this.useConnectWithDb)
clientParam |= 0x8L;
RuntimeProperty<Boolean> useInformationSchema = this.propertySet.getProperty(PropertyKey.useInformationSchema);
if (this.protocol.versionMeetsMinimum(8, 0, 3) && !((Boolean)useInformationSchema.getValue()).booleanValue() && !useInformationSchema.isExplicitlySet())
useInformationSchema.setValue(Boolean.valueOf(true));
PropertyDefinitions.SslMode sslMode = (PropertyDefinitions.SslMode)this.propertySet.getEnumProperty(PropertyKey.sslMode).getValue();
if ((capabilityFlags & 0x800) == 0 && sslMode != PropertyDefinitions.SslMode.DISABLED && sslMode != PropertyDefinitions.SslMode.PREFERRED)
throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("MysqlIO.15"), getExceptionInterceptor());
if ((capabilityFlags & 0x4) != 0) {
clientParam |= 0x4L;
sessState.setHasLongColumnInfo(true);
}
if (!((Boolean)this.propertySet.getBooleanProperty(PropertyKey.useAffectedRows).getValue()).booleanValue())
clientParam |= 0x2L;
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.allowLoadLocalInfile).getValue()).booleanValue())
clientParam |= 0x80L;
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.interactiveClient).getValue()).booleanValue())
clientParam |= 0x400L;
if ((capabilityFlags & 0x800000) != 0);
if ((capabilityFlags & 0x1000000) != 0)
clientParam |= 0x1000000L;
if ((capabilityFlags & 0x80000) != 0) {
sessState.setClientParam(clientParam);
proceedHandshakeWithPluggableAuthentication(sessState, user, password, database, buf);
} else {
throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_PLUGIN_AUTH is required", getExceptionInterceptor());
}
}
private Map<String, AuthenticationPlugin<NativePacketPayload>> authenticationPlugins = null;
private List<String> disabledAuthenticationPlugins = null;
private String clientDefaultAuthenticationPlugin = null;
private String clientDefaultAuthenticationPluginName = null;
private String serverDefaultAuthenticationPluginName = null;
private void loadAuthenticationPlugins() {
this.clientDefaultAuthenticationPlugin = (String)this.propertySet.getStringProperty(PropertyKey.defaultAuthenticationPlugin).getValue();
if (this.clientDefaultAuthenticationPlugin == null || "".equals(this.clientDefaultAuthenticationPlugin.trim()))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.BadDefaultAuthenticationPlugin", new Object[] { this.clientDefaultAuthenticationPlugin }), getExceptionInterceptor());
String disabledPlugins = (String)this.propertySet.getStringProperty(PropertyKey.disabledAuthenticationPlugins).getValue();
if (disabledPlugins != null && !"".equals(disabledPlugins)) {
this.disabledAuthenticationPlugins = new ArrayList<>();
List<String> pluginsToDisable = StringUtils.split(disabledPlugins, ",", true);
Iterator<String> iter = pluginsToDisable.iterator();
while (iter.hasNext())
this.disabledAuthenticationPlugins.add(iter.next());
}
this.authenticationPlugins = new HashMap<>();
boolean defaultIsFound = false;
List<AuthenticationPlugin<NativePacketPayload>> pluginsToInit = new LinkedList<>();
pluginsToInit.add(new MysqlNativePasswordPlugin());
pluginsToInit.add(new MysqlClearPasswordPlugin());
pluginsToInit.add(new Sha256PasswordPlugin());
pluginsToInit.add(new CachingSha2PasswordPlugin());
pluginsToInit.add(new MysqlOldPasswordPlugin());
String authenticationPluginClasses = (String)this.propertySet.getStringProperty(PropertyKey.authenticationPlugins).getValue();
if (authenticationPluginClasses != null && !"".equals(authenticationPluginClasses)) {
List<String> pluginsToCreate = StringUtils.split(authenticationPluginClasses, ",", true);
String className = null;
try {
for (int i = 0, s = pluginsToCreate.size(); i < s; i++) {
className = pluginsToCreate.get(i);
pluginsToInit.add((AuthenticationPlugin<NativePacketPayload>)Class.forName(className).newInstance());
}
} catch (Throwable t) {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { className }), t, this.exceptionInterceptor);
}
}
for (AuthenticationPlugin<NativePacketPayload> plugin : pluginsToInit) {
plugin.init(this.protocol);
if (addAuthenticationPlugin(plugin))
defaultIsFound = true;
}
if (!defaultIsFound)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.DefaultAuthenticationPluginIsNotListed", new Object[] { this.clientDefaultAuthenticationPlugin }), getExceptionInterceptor());
}
private boolean addAuthenticationPlugin(AuthenticationPlugin<NativePacketPayload> plugin) {
boolean isDefault = false;
String pluginClassName = plugin.getClass().getName();
String pluginProtocolName = plugin.getProtocolPluginName();
boolean disabledByClassName = (this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginClassName));
boolean disabledByMechanism = (this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginProtocolName));
if (disabledByClassName || disabledByMechanism) {
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName))
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.BadDisabledAuthenticationPlugin", new Object[] { disabledByClassName ? pluginClassName : pluginProtocolName }), getExceptionInterceptor());
} else {
this.authenticationPlugins.put(pluginProtocolName, plugin);
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
this.clientDefaultAuthenticationPluginName = pluginProtocolName;
isDefault = true;
}
}
return isDefault;
}
private AuthenticationPlugin<NativePacketPayload> getAuthenticationPlugin(String pluginName) {
AuthenticationPlugin<NativePacketPayload> plugin = this.authenticationPlugins.get(pluginName);
if (plugin != null && !plugin.isReusable())
try {
plugin = (AuthenticationPlugin<NativePacketPayload>)plugin.getClass().newInstance();
plugin.init(this.protocol);
} catch (Throwable t) {
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { plugin.getClass().getName() }), t,
getExceptionInterceptor());
}
return plugin;
}
private void checkConfidentiality(AuthenticationPlugin<?> plugin) {
if (plugin.requiresConfidentiality() && !this.protocol.getSocketConnection().isSSLEstablished())
throw ExceptionFactory.createException(
Messages.getString("AuthenticationProvider.AuthenticationPluginRequiresSSL", new Object[] { plugin.getProtocolPluginName() }), getExceptionInterceptor());
}
private void proceedHandshakeWithPluggableAuthentication(ServerSession sessState, String user, String password, String database, NativePacketPayload challenge) {
if (this.authenticationPlugins == null)
loadAuthenticationPlugins();
boolean skipPassword = false;
int passwordLength = 16;
int userLength = (user != null) ? user.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = (userLength + passwordLength + databaseLength) * 3 + 7 + 33;
long clientParam = sessState.getClientParam();
int serverCapabilities = sessState.getCapabilities().getCapabilityFlags();
AuthenticationPlugin<NativePacketPayload> plugin = null;
NativePacketPayload fromServer = null;
ArrayList<NativePacketPayload> toServer = new ArrayList<>();
boolean done = false;
NativePacketPayload last_sent = null;
boolean old_raw_challenge = false;
int counter = 100;
while (0 < counter--) {
if (!done) {
if (challenge != null) {
if (challenge.isOKPacket())
throw ExceptionFactory.createException(
Messages.getString("AuthenticationProvider.UnexpectedAuthenticationApproval", new Object[] { plugin.getProtocolPluginName() }), getExceptionInterceptor());
clientParam |= 0xEA201L;
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.allowMultiQueries).getValue()).booleanValue())
clientParam |= 0x10000L;
if ((serverCapabilities & 0x400000) != 0 &&
!((Boolean)this.propertySet.getBooleanProperty(PropertyKey.disconnectOnExpiredPasswords).getValue()).booleanValue())
clientParam |= 0x400000L;
if ((serverCapabilities & 0x100000) != 0 &&
!"none".equals(this.propertySet.getStringProperty(PropertyKey.connectionAttributes).getValue()))
clientParam |= 0x100000L;
if ((serverCapabilities & 0x200000) != 0)
clientParam |= 0x200000L;
sessState.setClientParam(clientParam);
if ((serverCapabilities & 0x800) != 0 && this.propertySet
.getEnumProperty(PropertyKey.sslMode).getValue() != PropertyDefinitions.SslMode.DISABLED)
negotiateSSLConnection(packLength);
String pluginName = null;
if ((serverCapabilities & 0x80000) != 0)
if (!this.protocol.versionMeetsMinimum(5, 5, 10) || (this.protocol
.versionMeetsMinimum(5, 6, 0) && !this.protocol.versionMeetsMinimum(5, 6, 2))) {
pluginName = challenge.readString(NativeConstants.StringLengthDataType.STRING_FIXED, "ASCII", ((NativeCapabilities)sessState
.getCapabilities()).getAuthPluginDataLength());
} else {
pluginName = challenge.readString(NativeConstants.StringSelfDataType.STRING_TERM, "ASCII");
}
plugin = getAuthenticationPlugin(pluginName);
if (plugin == null) {
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
} else if (pluginName.equals(Sha256PasswordPlugin.PLUGIN_NAME) && !this.protocol.getSocketConnection().isSSLEstablished() && this.propertySet
.getStringProperty(PropertyKey.serverRSAPublicKeyFile).getValue() == null &&
!((Boolean)this.propertySet.getBooleanProperty(PropertyKey.allowPublicKeyRetrieval).getValue()).booleanValue()) {
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
skipPassword = !this.clientDefaultAuthenticationPluginName.equals(pluginName);
}
this.serverDefaultAuthenticationPluginName = plugin.getProtocolPluginName();
checkConfidentiality(plugin);
fromServer = new NativePacketPayload(StringUtils.getBytes(this.seed));
} else {
plugin = getAuthenticationPlugin((this.serverDefaultAuthenticationPluginName == null) ? this.clientDefaultAuthenticationPluginName : this.serverDefaultAuthenticationPluginName);
checkConfidentiality(plugin);
fromServer = new NativePacketPayload(StringUtils.getBytes(this.seed));
}
} else {
challenge = (NativePacketPayload)this.protocol.checkErrorMessage();
old_raw_challenge = false;
if (plugin == null)
plugin = getAuthenticationPlugin((this.serverDefaultAuthenticationPluginName == null) ? this.clientDefaultAuthenticationPluginName : this.serverDefaultAuthenticationPluginName);
if (challenge.isOKPacket()) {
OkPacket ok = OkPacket.parse(challenge, null);
sessState.setStatusFlags(ok.getStatusFlags(), true);
plugin.destroy();
break;
}
if (challenge.isAuthMethodSwitchRequestPacket()) {
skipPassword = false;
String pluginName = challenge.readString(NativeConstants.StringSelfDataType.STRING_TERM, "ASCII");
if (!plugin.getProtocolPluginName().equals(pluginName)) {
plugin.destroy();
plugin = getAuthenticationPlugin(pluginName);
if (plugin == null)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { pluginName }), getExceptionInterceptor());
} else {
plugin.reset();
}
checkConfidentiality(plugin);
fromServer = new NativePacketPayload(StringUtils.getBytes(challenge.readString(NativeConstants.StringSelfDataType.STRING_TERM, "ASCII")));
} else {
if (!this.protocol.versionMeetsMinimum(5, 5, 16)) {
old_raw_challenge = true;
challenge.setPosition(challenge.getPosition() - 1);
}
fromServer = new NativePacketPayload(challenge.readBytes(NativeConstants.StringSelfDataType.STRING_EOF));
}
}
plugin.setAuthenticationParameters(user, skipPassword ? null : password);
done = plugin.nextAuthenticationStep(fromServer, toServer);
if (toServer.size() > 0) {
if (challenge == null) {
String str = getEncodingForHandshake();
last_sent = new NativePacketPayload(packLength + 1);
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, 17L);
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(user, str));
if (((NativePacketPayload)toServer.get(0)).getPayloadLength() < 256) {
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, ((NativePacketPayload)toServer.get(0)).getPayloadLength());
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_EOF, ((NativePacketPayload)toServer.get(0)).getByteBuffer(), 0, ((NativePacketPayload)toServer.get(0)).getPayloadLength());
} else {
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
}
if (this.useConnectWithDb) {
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(database, str));
} else {
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
}
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1,
AuthenticationProvider.getCharsetForHandshake(str, sessState.getCapabilities().getServerVersion()));
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
if ((serverCapabilities & 0x80000) != 0)
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(plugin.getProtocolPluginName(), str));
if ((clientParam & 0x100000L) != 0L)
appendConnectionAttributes(last_sent, (String)this.propertySet.getStringProperty(PropertyKey.connectionAttributes).getValue(), str);
this.protocol.send(last_sent, last_sent.getPosition());
continue;
}
if (challenge.isAuthMethodSwitchRequestPacket()) {
this.protocol.send(toServer.get(0), ((NativePacketPayload)toServer.get(0)).getPayloadLength());
continue;
}
if (challenge.isAuthMoreData() || old_raw_challenge) {
for (NativePacketPayload buffer : toServer)
this.protocol.send(buffer, buffer.getPayloadLength());
continue;
}
String enc = getEncodingForHandshake();
last_sent = new NativePacketPayload(packLength);
last_sent.writeInteger(NativeConstants.IntegerDataType.INT4, clientParam);
last_sent.writeInteger(NativeConstants.IntegerDataType.INT4, 16777215L);
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1,
AuthenticationProvider.getCharsetForHandshake(enc, sessState.getCapabilities().getServerVersion()));
last_sent.writeBytes(NativeConstants.StringLengthDataType.STRING_FIXED, new byte[23]);
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(user, enc));
if ((serverCapabilities & 0x200000) != 0) {
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, ((NativePacketPayload)toServer.get(0)).readBytes(NativeConstants.StringSelfDataType.STRING_EOF));
} else {
last_sent.writeInteger(NativeConstants.IntegerDataType.INT1, ((NativePacketPayload)toServer.get(0)).getPayloadLength());
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_EOF, ((NativePacketPayload)toServer.get(0)).getByteBuffer());
}
if (this.useConnectWithDb)
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(database, enc));
if ((serverCapabilities & 0x80000) != 0)
last_sent.writeBytes(NativeConstants.StringSelfDataType.STRING_TERM, StringUtils.getBytes(plugin.getProtocolPluginName(), enc));
if ((clientParam & 0x100000L) != 0L)
appendConnectionAttributes(last_sent, (String)this.propertySet.getStringProperty(PropertyKey.connectionAttributes).getValue(), enc);
this.protocol.send(last_sent, last_sent.getPosition());
}
}
if (counter == 0)
throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class,
Messages.getString("CommunicationsException.TooManyAuthenticationPluginNegotiations"), getExceptionInterceptor());
this.protocol.afterHandshake();
if (!this.useConnectWithDb)
this.protocol.changeDatabase(database);
}
private Map<String, String> getConnectionAttributesMap(String attStr) {
Map<String, String> attMap = new HashMap<>();
if (attStr != null) {
String[] pairs = attStr.split(",");
for (String pair : pairs) {
int keyEnd = pair.indexOf(":");
if (keyEnd > 0 && keyEnd + 1 < pair.length())
attMap.put(pair.substring(0, keyEnd), pair.substring(keyEnd + 1));
}
}
attMap.put("_client_name", "MySQL Connector/J");
attMap.put("_client_version", "8.0.19");
attMap.put("_runtime_vendor", Constants.JVM_VENDOR);
attMap.put("_runtime_version", Constants.JVM_VERSION);
attMap.put("_client_license", "GPL");
return attMap;
}
private void appendConnectionAttributes(NativePacketPayload buf, String attributes, String enc) {
NativePacketPayload lb = new NativePacketPayload(100);
Map<String, String> attMap = getConnectionAttributesMap(attributes);
for (String key : attMap.keySet()) {
lb.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, StringUtils.getBytes(key, enc));
lb.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, StringUtils.getBytes(attMap.get(key), enc));
}
buf.writeInteger(NativeConstants.IntegerDataType.INT_LENENC, lb.getPosition());
buf.writeBytes(NativeConstants.StringLengthDataType.STRING_FIXED, lb.getByteBuffer(), 0, lb.getPosition());
}
public String getEncodingForHandshake() {
String enc = (String)this.propertySet.getStringProperty(PropertyKey.characterEncoding).getValue();
if (enc == null)
enc = "UTF-8";
return enc;
}
public ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
private void negotiateSSLConnection(int packLength) {
this.protocol.negotiateSSLConnection(packLength);
}
public void changeUser(ServerSession serverSession, String userName, String password, String database) {
proceedHandshakeWithPluggableAuthentication(serverSession, userName, password, database, null);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\NativeAuthenticationProvider.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.dubainow.mobile.pages;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.dubainow.mobile.base.TestBase;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
public class AllServicesPage extends TestBase {
@AndroidFindBy (id = "com.deg.mdubai:id/btnCancel" )
public MobileElement enoc;
@AndroidFindBy(xpath = "//android.widget.TextView[@text='Utilities & Bills']")
public MobileElement utility;
public AlJalilaPage ClickonUtility() {
WebDriverWait wait = new WebDriverWait(driver,100);
MobileElement enoc1 = (MobileElement) wait.until(ExpectedConditions.elementToBeClickable(enoc));
enoc1.click();
MobileElement utility1 = (MobileElement) wait.until(ExpectedConditions.elementToBeClickable(utility));
utility1.click();
return new AlJalilaPage(driver);
}
public AllServicesPage(AndroidDriver<MobileElement> driver) {
//this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
}
|
package co.th.aten.football.ui.report;
import co.th.aten.football.Configuration;
import java.awt.Color;
import com.jensoft.sw2d.core.democomponent.Sw2dDemo;
import com.jensoft.sw2d.core.glyphmetrics.StylePosition;
import com.jensoft.sw2d.core.glyphmetrics.painter.fill.GlyphFill;
import com.jensoft.sw2d.core.glyphmetrics.painter.marker.RoundMarker;
import com.jensoft.sw2d.core.palette.ColorPalette;
import com.jensoft.sw2d.core.palette.InputFonts;
import com.jensoft.sw2d.core.palette.NanoChromatique;
import com.jensoft.sw2d.core.palette.PetalPalette;
import com.jensoft.sw2d.core.palette.RosePalette;
import com.jensoft.sw2d.core.palette.TangoPalette;
import com.jensoft.sw2d.core.plugin.outline.OutlinePlugin;
import com.jensoft.sw2d.core.plugin.radar.DimensionMetrics;
import com.jensoft.sw2d.core.plugin.radar.Radar;
import com.jensoft.sw2d.core.plugin.radar.RadarDimension;
import com.jensoft.sw2d.core.plugin.radar.RadarPlugin;
import com.jensoft.sw2d.core.plugin.radar.RadarSurfaceAnchor;
import com.jensoft.sw2d.core.plugin.radar.RadarToolkit;
import com.jensoft.sw2d.core.plugin.radar.painter.dimension.DimensionDefaultPainter;
import com.jensoft.sw2d.core.plugin.radar.painter.radar.RadarDefaultPainter;
import com.jensoft.sw2d.core.view.View2D;
import com.jensoft.sw2d.core.window.Window2D;
import java.awt.BasicStroke;
import java.text.DecimalFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ViewReportTestRadarDlg extends Sw2dDemo {
private double gc;
private int match;
private int playingTime;
private int flag;
private DecimalFormat df = new DecimalFormat("#,###");
private final Log logger = LogFactory.getLog(getClass());
public static void main(String[] args) {
try {
Configuration.loadConfig();
final TemplateReportFrame templateFrame = new TemplateReportFrame();
ViewReportTestRadarDlg report = new ViewReportTestRadarDlg(4000000, 20, 1590, 0);
templateFrame.show(report);
// templateFrame.setView(report.getView());
// templateFrame.pack();
templateFrame.setSize(465, 360);
// templateFrame.setSize(865, 660);
templateFrame.setLocation(250, 120);
// final TemplateReportFrame templateFrame = new TemplateReportFrame();
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// ViewReportTestRadarDlg report = new ViewReportTestRadarDlg();
// templateFrame.show(report);
// templateFrame.setView(report.getView());
// }
// });
// templateFrame.pack();
// templateFrame.setSize(800, 500);
// templateFrame.setLocation(250, 120);
} catch (Exception e) {
e.printStackTrace();
}
}
public ViewReportTestRadarDlg(double gc, int match, int playingTime, int flag) {
this.gc = gc;
this.match = match;
this.playingTime = playingTime;
this.flag = flag;
}
private View2D view;
public View2D getView() {
return view;
}
public void setView(View2D view) {
this.view = view;
}
@Override
public View2D createView2D() {
view = new View2D();
try {
run();
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
private void run() {
try {
view.setName("ReportRadar");
view.setBackground(Color.WHITE);
view.setPlaceHolderAxisEast(3);
view.setPlaceHolderAxisNorth(3);
view.setPlaceHolderAxisSouth(3);
view.setPlaceHolderAxisWest(3);
Window2D radarWindow2D = new Window2D.Linear(-100, 100, -100, 100);
radarWindow2D.setName("compatible pie window");
RadarPlugin radarPlugin = new RadarPlugin();
radarPlugin.setPriority(100);
radarWindow2D.registerPlugin(radarPlugin);
if (flag == 0) {
radarWindow2D.registerPlugin(new OutlinePlugin(Color.BLACK));
}
final Radar radar = new Radar(0, 0, 100);
radar.setCenterX(-5);
radar.setCenterY(-20);
radar.setRadarPainter(new RadarDefaultPainter());
final RadarDimension radardimension = new RadarDimension("GC",NanoChromatique.GRAY, 90.0D, 0.0D, Configuration.getInt("GC"));
radardimension.setDimensionPainter(new DimensionDefaultPainter());
final RadarDimension radardimension2 = new RadarDimension("Match",NanoChromatique.GRAY, 210D, 0.0D, Configuration.getInt("Match"));
radardimension2.setDimensionPainter(new DimensionDefaultPainter());
final RadarDimension radardimension4 = new RadarDimension("Playing Time",NanoChromatique.GRAY, 330D, 0.0D, Configuration.getInt("PlayingTime"));
radardimension4.setDimensionPainter(new DimensionDefaultPainter());
RadarToolkit.pushDimensions(radar, new RadarDimension[]{radardimension, radardimension2, radardimension4});
java.awt.Font font = InputFonts.getFont(InputFonts.NO_MOVE, 12);
float af[] = {0.0F, 0.3F, 0.7F, 1.0F};
Color acolor[] = {new Color(0, 0, 0, 100), new Color(0, 0, 0, 255),
new Color(0, 0, 0, 255), new Color(0, 0, 0, 100)};
BasicStroke basicstroke = new BasicStroke(2.0F);
com.jensoft.sw2d.core.plugin.radar.painter.label.RadarDimensionDefaultLabel radardimensiondefaultlabel = RadarToolkit
.createDimensionDefaultLabel("GC", font, ColorPalette.WHITE,
RosePalette.REDWOOD, af, acolor, 20);
radardimensiondefaultlabel.setOutlineStroke(basicstroke);
com.jensoft.sw2d.core.plugin.radar.painter.label.RadarDimensionDefaultLabel radardimensiondefaultlabel2 = RadarToolkit
.createDimensionDefaultLabel("Match", font, ColorPalette.WHITE,
RosePalette.REDWOOD, af, acolor, 20);
radardimensiondefaultlabel2.setOutlineStroke(basicstroke);
com.jensoft.sw2d.core.plugin.radar.painter.label.RadarDimensionDefaultLabel radardimensiondefaultlabel4 = RadarToolkit
.createDimensionDefaultLabel("Playing Time", font, ColorPalette.WHITE,
RosePalette.REDWOOD, af, acolor, 20);
radardimensiondefaultlabel4.setOutlineStroke(basicstroke);
radardimension.setDimensionLabel(radardimensiondefaultlabel);
radardimension2.setDimensionLabel(radardimensiondefaultlabel2);
radardimension4.setDimensionLabel(radardimensiondefaultlabel4);
radarPlugin.addRadar(radar);
view.registerWindow2D(radarWindow2D);
try {
com.jensoft.sw2d.core.plugin.radar.RadarSurface radarsurface = RadarToolkit
.createSurface("surface1", ColorPalette.alpha(NanoChromatique.BLUE, 240), ColorPalette.alpha(NanoChromatique.BLUE, 80));
radar.addSurface(radarsurface);
java.awt.Font font3 = InputFonts.getFont(InputFonts.NO_MOVE, 10);
GlyphFill glyphfill = new GlyphFill(Color.BLUE, NanoChromatique.BLUE);
RoundMarker roundmarker = new RoundMarker(NanoChromatique.BLUE,
Color.WHITE, 3);
// RadarSurfaceAnchor radarsurfaceanchor = RadarToolkit.createSurfaceAnchor(
// radardimension, (gc==0?"":df.format(gc)), gc, StylePosition.Default, 25, glyphfill,
// roundmarker, font3);
// RadarSurfaceAnchor radarsurfaceanchor2 = RadarToolkit.createSurfaceAnchor(
// radardimension2, (match==0?"":df.format(match)), match, StylePosition.Default, 10, glyphfill,
// roundmarker, font3);
// RadarSurfaceAnchor radarsurfaceanchor4 = RadarToolkit.createSurfaceAnchor(
// radardimension4, (playingTime==0?"":df.format(playingTime)), playingTime, StylePosition.Default, 10, glyphfill,
// roundmarker, font3);
RadarSurfaceAnchor radarsurfaceanchor = RadarToolkit.createSurfaceAnchor(
radardimension, "", gc, StylePosition.Default, 25, glyphfill,
roundmarker, font3);
RadarSurfaceAnchor radarsurfaceanchor2 = RadarToolkit.createSurfaceAnchor(
radardimension2, "", match, StylePosition.Default, 10, glyphfill,
roundmarker, font3);
RadarSurfaceAnchor radarsurfaceanchor4 = RadarToolkit.createSurfaceAnchor(
radardimension4, "", playingTime, StylePosition.Default, 10, glyphfill,
roundmarker, font3);
RadarToolkit.pushAnchors(radarsurface, new RadarSurfaceAnchor[]{
radarsurfaceanchor, radarsurfaceanchor2, radarsurfaceanchor4});
com.jensoft.sw2d.core.plugin.radar.RadarSurface radarsurface1 = RadarToolkit
.createSurface("surface2", Color.WHITE, ColorPalette.alpha(
RosePalette.PLUMWINE, 20));
radar.addSurface(radarsurface1);
view.repaintDevice();
glyphfill = new GlyphFill(Color.WHITE, NanoChromatique.ORANGE);
RadarSurfaceAnchor radarsurfaceanchor6 = RadarToolkit.createSurfaceAnchor(
radardimension, "", Configuration.getDouble("GC"), StylePosition.Default, 10, glyphfill,
null, font3);
RadarSurfaceAnchor radarsurfaceanchor8 = RadarToolkit.createSurfaceAnchor(
radardimension2, "", Configuration.getDouble("Match"), StylePosition.Default, 10, glyphfill,
null, font3);
RadarSurfaceAnchor radarsurfaceanchor10 = RadarToolkit.createSurfaceAnchor(
radardimension4, "", Configuration.getDouble("PlayingTime"), StylePosition.Default, 10, glyphfill,
null, font3);
RadarToolkit.pushAnchors(radarsurface1, new RadarSurfaceAnchor[]{radarsurfaceanchor6, radarsurfaceanchor8, radarsurfaceanchor10});
view.repaintDevice();
java.awt.Font font1 = InputFonts.getFont(InputFonts.SANSATION_REGULAR, 12);
glyphfill = new GlyphFill(RosePalette.MANDARIN, RosePalette.CHOCOLATE);
roundmarker = new RoundMarker(RosePalette.REDWOOD, Color.WHITE, 3);
DimensionMetrics dimensionmetrics = RadarToolkit.createDimensionMetrics(
"", Configuration.getDouble("GC"), StylePosition.Default, 20, glyphfill, roundmarker,
font1);
DimensionMetrics dimensionmetrics2 = RadarToolkit.createDimensionMetrics(
"", Configuration.getDouble("Match"), StylePosition.Default, 20, glyphfill, roundmarker,
font1);
DimensionMetrics dimensionmetrics4 = RadarToolkit.createDimensionMetrics(
"", Configuration.getDouble("PlayingTime"), StylePosition.Default, 20, glyphfill, roundmarker,
font1);
radardimension.addMetrics(dimensionmetrics);
radardimension2.addMetrics(dimensionmetrics2);
radardimension4.addMetrics(dimensionmetrics4);
view.repaintDevice();
} catch (Exception e) {
e.printStackTrace();
}
view.repaintDevice();
} catch (Exception e) {
logger.info("" + e);
e.printStackTrace();
}
}
}
|
package ru.recursiy.alpintour;
import android.content.Context;
import android.database.Cursor;
import android.widget.SimpleCursorTreeAdapter;
import ru.recursiy.alpintour.storage.Storage;
/**
* Adapter for routes list
*/
public class RouteListAdapter extends SimpleCursorTreeAdapter {
Storage storage;
public RouteListAdapter(Storage storage, Context context, Cursor cursor, int collapsedGroupLayout, int expandedGroupLayout, String[] groupFrom, int[] groupTo, int childLayout, int lastChildLayout, String[] childFrom, int[] childTo) {
super(context, cursor, collapsedGroupLayout, expandedGroupLayout, groupFrom, groupTo, childLayout, lastChildLayout, childFrom, childTo);
this.storage = storage;
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
//todo: async load through cursor loader
int idIndex = groupCursor.getColumnIndex(Storage.COLUMN_ID);
return storage.getBriefRouteDescription(groupCursor.getInt(idIndex));
}
}
|
package com.inspiredcoda.getitdone;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logo = findViewById(R.id.logo_solo);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this, SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Pair[] pair = new Pair[1];
pair[0] = new Pair<View, String>(logo, "logo_trans");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, pair);
startActivity(intent, options.toBundle());
}else{
startActivity(intent);
}
}
}, 3000);
}
}
|
package com.example.sas_maxnot19.luckyapp.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import com.example.sas_maxnot19.luckyapp.R;
import com.example.sas_maxnot19.luckyapp.models.Profile;
import com.google.gson.Gson;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class ProfileActivity extends AppCompatActivity {
private TextView firstname_tv;
private TextView lastname_tv;
private TextView birthday_tv;
private TextView timeOfBirth_tv;
private RadioButton male_rdb, female_rdb;
private TextView back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initComponent();
}
private void initComponent(){
setTitle("Profile");
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF4081")));
back = (TextView)findViewById(R.id.back_btn);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ProfileActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
});
Profile profile = getProfile();
//Constant.profile = getProfile();
DateFormat format = new SimpleDateFormat("dd/MMM/yyyy");
male_rdb = (RadioButton) findViewById(R.id.male_rdb);
female_rdb = (RadioButton) findViewById(R.id.female_rdb);
male_rdb.setChecked(profile.isMale());
female_rdb.setChecked(!profile.isMale());
firstname_tv = (TextView) findViewById(R.id.firstname_tv);
firstname_tv.setText(profile.getFirstname());
lastname_tv = (TextView) findViewById(R.id.lastname_tv);
lastname_tv.setText(profile.getLastname());
birthday_tv = (TextView) findViewById(R.id.birthday_tv);
birthday_tv.setText(format.format(profile.getDate()));
timeOfBirth_tv = (TextView) findViewById(R.id.timeOfBirthday_tv);
timeOfBirth_tv.setText(String.format("%2d:%2d" , profile.getDate().getHours() , profile.getDate().getMinutes()));
}
public Profile getProfile() {
SharedPreferences sp = getSharedPreferences(Constant.PROFILE_KEY,MODE_PRIVATE);
Gson gson = new Gson();
String profileStr = sp.getString("profile",null);
return gson.fromJson(profileStr,Profile.class);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.