blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a390252427b88f6cc0039d7d685c2423b371ed4 | f36ef14397ee790bfd2df0e1c4f414a416f8e00a | /src/main/java/com/vaya20/backend/EmailSender/EmailSenderController.java | a11d5780c814f65e789b9f0ad6c0dc9d0f6d86b4 | []
| no_license | joegaBonito/vaya-back-spring | e8915b0948ea04210929479cd6766b3c7f961c0c | f5629b37048e870beaf089b0fec3d03bba88b6e9 | refs/heads/master | 2021-09-22T11:43:15.895748 | 2018-09-10T04:02:47 | 2018-09-10T04:02:47 | 111,177,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,224 | java | package com.vaya20.backend.EmailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping("/api")
public class EmailSenderController {
private Logger logger = LoggerFactory.getLogger(EmailSenderController.class);
@Autowired
EmailSenderService emailSenderService;
EmailSenderController(EmailSenderService emailSenderService) {
this.emailSenderService = emailSenderService;
}
@RequestMapping(value="/contact-us", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void contactUs(@RequestBody Email email) {
//send a notification
try{
this.emailSenderService.sendEmail(email);
} catch (MailException e){
//catch error
logger.info("Error sending email: " + e.getMessage());
}
}
}
| [
"Joe Jung"
]
| Joe Jung |
8b19197c6741cef0b16a28559c84304e2bd5cc54 | d41b0bd1aee8222b244af4f6403a10c6f3be2361 | /modules/cpr/src/main/java/org/atmosphere/util/FakeHttpSession.java | 2b34b3d1affbecbfe468ba4e2999f4912c739272 | []
| no_license | jrarnett/atmosphere | db2c97be847fa02c4b2b62a0997112f6276b319e | bd96d6db8f1ff65e6225ee7f92c3447865953449 | refs/heads/master | 2021-01-15T16:15:56.355422 | 2013-09-18T00:34:29 | 2013-09-18T00:34:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,850 | java | /*
* Copyright 2013 Jeanfrancois Arcand
*
* 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.atmosphere.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.util.Collections;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
public class FakeHttpSession implements HttpSession {
private final long creationTime;
private final ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
private final String sessionId;
private final ServletContext servletContext;
private int maxInactiveInterval;
private final AtomicBoolean valid = new AtomicBoolean(true);
public FakeHttpSession(String sessionId, ServletContext servletContext, long creationTime, int maxInactiveInterval) {
this.sessionId = sessionId;
this.servletContext = servletContext;
this.creationTime = creationTime;
this.maxInactiveInterval = maxInactiveInterval;
}
public FakeHttpSession(HttpSession session) {
this(session.getId(), session.getServletContext(), session.getLastAccessedTime(), session.getMaxInactiveInterval());
copyAttributes(session);
}
public void destroy() {
attributes.clear();
}
@Override
public long getCreationTime() {
if (!valid.get()) throw new IllegalStateException();
return creationTime;
}
@Override
public String getId() {
if (!valid.get()) throw new IllegalStateException();
return sessionId;
}
// TODO: Not supported for now. Must update on every WebSocket Message
@Override
public long getLastAccessedTime() {
if (!valid.get()) throw new IllegalStateException();
return 0;
}
@Override
public ServletContext getServletContext() {
return servletContext;
}
@Override
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
@Override
public int getMaxInactiveInterval() {
return maxInactiveInterval;
}
@Override
public HttpSessionContext getSessionContext() {
return null;
}
@Override
public Object getAttribute(String name) {
if (!valid.get()) throw new IllegalStateException();
return attributes.get(name);
}
@Override
public Object getValue(String name) {
if (!valid.get()) throw new IllegalStateException();
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
if (!valid.get()) throw new IllegalStateException();
return attributes.keys();
}
@Override
public String[] getValueNames() {
if (!valid.get()) throw new IllegalStateException();
return (String[]) Collections.list(attributes.keys()).toArray();
}
@Override
public void setAttribute(String name, Object value) {
if (!valid.get()) throw new IllegalStateException();
attributes.put(name, value);
}
@Override
public void putValue(String name, Object value) {
if (!valid.get()) throw new IllegalStateException();
attributes.put(name, value);
}
@Override
public void removeAttribute(String name) {
if (!valid.get()) throw new IllegalStateException();
attributes.remove(name);
}
@Override
public void removeValue(String name) {
if (!valid.get()) throw new IllegalStateException();
attributes.remove(name);
}
public FakeHttpSession copyAttributes(HttpSession httpSession){
Enumeration<String> e = httpSession.getAttributeNames();
String k;
while(e.hasMoreElements()) {
k = e.nextElement();
if (k == null) continue;
Object o = httpSession.getAttribute(k);
if (o == null) continue;
attributes.put(k, o);
}
return this;
}
@Override
public void invalidate() {
if (!valid.get()) throw new IllegalStateException();
valid.set(false);
}
@Override
public boolean isNew() {
if (!valid.get()) throw new IllegalStateException();
return false;
}
}
| [
"[email protected]"
]
| |
5f7f818628232f4365c3097560236c7c0fbcbbc4 | 63a3d036e523c76a481d9fab10da27264ea35b49 | /src/main/java/com/app/derin/uaa/service/InvalidPasswordException.java | b4d78878c752941a5417c9f3a3f61f4208767345 | []
| no_license | EbruYaren/jhipster-authentication-gateway-project | 21f7a4e70d196f243c61bfd472cb89dc59630a8a | d6c5a5d8d976874072109855c293ccd89ce310bb | refs/heads/master | 2022-12-16T08:43:57.059437 | 2020-01-15T11:41:32 | 2020-01-15T11:41:32 | 234,097,238 | 0 | 0 | null | 2022-12-16T04:43:26 | 2020-01-15T14:23:18 | Java | UTF-8 | Java | false | false | 188 | java | package com.app.derin.uaa.service;
public class InvalidPasswordException extends RuntimeException {
public InvalidPasswordException() {
super("Incorrect password");
}
}
| [
"[email protected]"
]
| |
8f13a3ac5eaf17cbbe21e09aa15221a09ea02619 | aa8a94423e9f69bf375f01f1c46b0fea44d354f4 | /app/src/main/java/lipnus/com/realworld/SimpleFunction.java | ea559eb8e88e4f5f3ad025d4bc0c210fa479553f | []
| no_license | lipnus/Realworld | c5238941e13d99248d832198b146245baf39bc1e | 229a692917ffedff482066eb8300daaa3e00cce6 | refs/heads/master | 2021-05-04T14:32:49.262137 | 2018-07-03T16:52:25 | 2018-07-03T16:52:25 | 120,202,672 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,312 | java | package lipnus.com.realworld;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Created by LIPNUS on 2018-02-19.
*/
public class SimpleFunction {
//리스트뷰 안의 내용을 토대로 세로크기를 정해준다
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
Log.d("SSBB", "totalHeight: " + totalHeight);
ViewGroup.LayoutParams params = listView.getLayoutParams();
int padding = 100;
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + padding;
listView.setLayoutParams(params);
listView.requestLayout();
}
}
| [
"[email protected]"
]
| |
ae2d1ea847b8cf68c9b1cc5bd95069651acba27c | 5ba08a86e72754f272feaa3b352e808d212d883b | /Fibonacci.java | c90cc85d5f15914031794a7e87dacb2fc5adcc55 | []
| no_license | iannielsenCode/University-Work-DataStructures | cc53ce70c94fb6836d8c3511a8bce80e6a8f66f6 | 738490fc7e7c3f3ea1b45af7899271423048b29c | refs/heads/master | 2020-03-30T05:07:28.371923 | 2018-09-28T18:52:15 | 2018-09-28T18:52:15 | 150,782,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 282 | java | package data.structures;
public class Fibonacci {
public static int Fib(int n){
if(n <2){
return 1;
}
else{
return Fib(n-1) + Fib(n-2);
}
}
public static void main(String[] args){
System.out.println(Fibonacci.Fib(15));
}
}
| [
"[email protected]"
]
| |
e241852c4f6bf0d4446ce39411014f2ae2be1751 | 89c36d0d4b40754170720613e927fbf99f227e9d | /src/stratage/IQuackBehavior.java | 11d9b10b58e8f599876e3bf88c8fee5d02e10b0e | []
| no_license | Howiezhang226/DesignPattern | eee0f1283b77ba0126281f55b2f03d14432b4d79 | cf1a8e1a6f642f4156abf4451063bd788bbd4525 | refs/heads/main | 2023-08-07T05:53:54.941282 | 2021-09-22T00:37:14 | 2021-09-22T00:37:14 | 409,008,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 50 | java | package stratage;
public interface Ibehavior {
}
| [
"[email protected]"
]
| |
befd6d061cd2553a6678ba1c28c636f2484fff16 | 9e62158d75f9fc88151639122b6bc6a14588e823 | /src/main/java/demo/java/io/demoIO.java | 7fd25d26b66b176b4a1b4cc8dbd1b2e8508a80f2 | []
| no_license | bhrgv-bolla/demo-java-io | e144eb5c146b6bc441111f3ea720d52524ead5ab | a55ae4b869bdbf22ecac3a8cc7ebc28ed3c3f2cb | refs/heads/master | 2020-03-28T10:00:56.934423 | 2018-09-13T04:00:44 | 2018-09-13T04:00:44 | 148,076,034 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,467 | java | package demo.java.io;
import java.io.*;
public class demoIO {
public static void demoStreamTokenizer() throws IOException {
FileReader fileReader = new FileReader("demo_files/fileWith10Words");
BufferedReader bufferedReader = new BufferedReader(fileReader);
StreamTokenizer streamTokenizer = new StreamTokenizer(bufferedReader);
int t;
int words = 0;
while ((t = streamTokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
switch (t) {
case StreamTokenizer.TT_WORD:
System.out.println(streamTokenizer.sval);
words++;
break;
}
}
System.out.println("Num Words: " + words);
}
private static void demoFileWriter() throws IOException {
FileWriter fileWriter = new FileWriter("demo_files/fileWriter");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("some text");
bufferedWriter.flush();
fileWriter.close();
FileReader fileReader = new FileReader("demo_files/fileWriter");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String t;
while ((t = bufferedReader.readLine()) != null) {
System.out.println(t);
}
}
public static void main(String[] args) throws IOException {
demoStreamTokenizer();
demoFileWriter();
}
}
| [
"[email protected]"
]
| |
3cddd590c795529d22d607d159289acb1751f2b9 | 720821ba4de36637aa914984d92d187d12c3aea9 | /common/src/main/java/com/a528854302/utils/OkHttpClientUtil.java | 4df3fc3c77919778efe89cd1083910a8209664b6 | []
| no_license | 528854302/manage | 7c4de625cf4c220a3343a3020498ca8ae3875817 | 80423f6c4892cc09d0aab9cf420c65c4efba9802 | refs/heads/master | 2021-02-08T01:58:28.258166 | 2020-03-07T03:28:47 | 2020-03-07T03:28:47 | 244,096,198 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,481 | java | package com.a528854302.utils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpClientUtil {
private static final int READ_TIMEOUT = 100;
private static final int CONNECT_TIMEOUT = 60;
private static final int WRITE_TIMEOUT = 60;
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final byte[] LOCKER = new byte[0];
private static OkHttpClientUtil mInstance;
private OkHttpClient okHttpClient;
private OkHttpClientUtil() {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
// 读取超时
clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
// 连接超时
clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
//写入超时
clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
okHttpClient = clientBuilder.build();
}
/**
* 单例模式获取 NetUtils
*
* @return {@link OkHttpClientUtil}
*/
public static OkHttpClientUtil getInstance() {
if (mInstance == null) {
synchronized (LOCKER) {
if (mInstance == null) {
mInstance = new OkHttpClientUtil();
}
}
}
return mInstance;
}
/**
* GET,同步方式,获取网络数据
*
* @param url 请求地址
* @return {@link Response}
*/
public Response getData(String url) {
// 构造 Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call,得到 Response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* POST 请求,同步方式,提交数据
*
* @param url 请求地址
* @param bodyParams 请求参数
* @return {@link Response}
*/
public Response postData(String url, Map<String, String> bodyParams) {
// 构造 RequestBody
RequestBody body = setRequestBody(bodyParams);
// 构造 Request
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call,得到 Response
Response response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* GET 请求,异步方式,获取网络数据
*
* @param url 请求地址
* @param myNetCall 回调函数
*/
public void getDataAsync(String url, final MyNetCall myNetCall) {
// 构造 Request
Request.Builder builder = new Request.Builder();
Request request = builder.get().url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myNetCall.success(call, response);
}
});
}
/**
* POST 请求,异步方式,提交数据
*
* @param url 请求地址
* @param bodyParams 请求参数
* @param myNetCall 回调函数
*/
public void postDataAsync(String url, Map<String, String> bodyParams, final MyNetCall myNetCall) {
// 构造 RequestBody
RequestBody body = setRequestBody(bodyParams);
// 构造 Request
buildRequest(url, myNetCall, body);
}
/**
* 构造 POST 请求参数
*
* @param bodyParams 请求参数
* @return {@link RequestBody}
*/
private RequestBody setRequestBody(Map<String, String> bodyParams) {
RequestBody body = null;
okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
if (bodyParams != null) {
Iterator<String> iterator = bodyParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
formEncodingBuilder.add(key, bodyParams.get(key));
}
}
body = formEncodingBuilder.build();
return body;
}
/**
* 构造 Request 发起异步请求
*
* @param url 请求地址
* @param myNetCall 回调函数
* @param body {@link RequestBody}
*/
private void buildRequest(String url, MyNetCall myNetCall, RequestBody body) {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder.post(body).url(url).build();
// 将 Request 封装为 Call
Call call = okHttpClient.newCall(request);
// 执行 Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
myNetCall.failed(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
myNetCall.success(call, response);
}
});
}
/**
* 自定义网络回调接口
*/
public interface MyNetCall {
/**
* 请求成功的回调处理
*
* @param call {@link Call}
* @param response {@link Response}
* @throws IOException 异常
*/
void success(Call call, Response response) throws IOException;
/**
* 请求失败的回调处理
*
* @param call {@link Call}
* @param e 异常
*/
void failed(Call call, IOException e);
}
}
| [
"[email protected]"
]
| |
bf3121946947ab47f232c7658332bb1323ae64bb | e0bd20ae76523f4046ee19013ef4b0e51f7364cc | /basecmlib/src/main/java/com/efan/basecmlib/okhttputils/request/PostFormRequest.java | daddadcf8778e72f1e2a7f96e41bd033c5a5a0f6 | []
| no_license | efany/basecmlib | 557b1cf609f41a6959989bf2605247d2a5c91403 | 19a9c3f6dc4e7e3fbd108a7fa97580a4ebcb3697 | refs/heads/master | 2021-01-10T12:28:15.007550 | 2016-03-26T10:56:32 | 2016-03-26T10:56:32 | 54,327,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,006 | java | package com.efan.basecmlib.okhttputils.request;
import com.efan.basecmlib.okhttputils.OkHttpUtils;
import com.efan.basecmlib.okhttputils.builder.PostFormBuilder;
import com.efan.basecmlib.okhttputils.callback.Callback;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
public class PostFormRequest extends OkHttpRequest
{
private List<PostFormBuilder.FileInput> files;
public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, List<PostFormBuilder.FileInput> files)
{
super(url, tag, params, headers);
this.files = files;
}
@Override
protected RequestBody buildRequestBody()
{
if (files == null || files.isEmpty())
{
FormBody.Builder builder = new FormBody.Builder();
addParams(builder);
return builder.build();
} else
{
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
addParams(builder);
for (int i = 0; i < files.size(); i++)
{
PostFormBuilder.FileInput fileInput = files.get(i);
RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
}
return builder.build();
}
}
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
if (callback == null) return requestBody;
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
{
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength)
{
OkHttpUtils.getInstance().getDelivery().post(new Runnable()
{
@Override
public void run()
{
callback.inProgress(bytesWritten * 1.0f / contentLength);
}
});
}
});
return countingRequestBody;
}
@Override
protected Request buildRequest(Request.Builder builder, RequestBody requestBody)
{
return builder.post(requestBody).build();
}
private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
private void addParams(MultipartBody.Builder builder)
{
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
RequestBody.create(null, params.get(key)));
}
}
}
private void addParams(FormBody.Builder builder)
{
if (params == null || params.isEmpty())
{
builder.add("1", "1");
return;
}
for (String key : params.keySet())
{
builder.add(key, params.get(key));
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
if (files != null)
{
for (PostFormBuilder.FileInput file : files)
{
sb.append(file.toString()+" ");
}
}
return sb.toString();
}
}
| [
"[email protected]"
]
| |
4ce9fb22e75c7d1417271a0dc8dc9097634fa515 | 4c204c07723a898c7912a43c51ac7b609c3a9209 | /src/main/java/desktop/database/services/MapToPojos.java | c441bc0cfd70ec1e82d6c27d2dabe86e8290b9dd | []
| no_license | carletonDev/OS-Automation | 28b4bd1b4a6510c0a383ce22a2eb0a018d1b11e3 | 34c2448fa938fb1f6e82e754f55213879d0d1270 | refs/heads/master | 2022-12-19T04:06:37.564110 | 2020-09-25T04:26:31 | 2020-09-25T04:26:31 | 296,196,534 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,671 | java | package desktop.database.services;
import desktop.database.pojos.Steps;
import desktop.database.pojos.Suite;
import desktop.database.pojos.TestCase;
import desktop.database.pojos.TestCaseSteps;
import desktop.database.repositories.StepsRepository;
import desktop.database.repositories.SuiteRepository;
import desktop.database.repositories.TestCaseRepository;
import desktop.excel.ExcelFileNames;
import desktop.excel.dataDrive.ClassParser;
import desktop.excel.dataDrive.ClassParser.ClassParserException;
import desktop.excel.dataDrive.ClassParser.DataNotAvailableException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
@Service
public class MapToPojos {
private ClassParser parser;
public MapToPojos(ClassParser parser) {
this.parser=parser;
}
public List<TestCase> maptoTestCasePojo(Map<String, List<String>> data)
throws ClassParserException, DataNotAvailableException {
List<TestCase> list;
List<Suite> suites = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
//get list of Suites
data.get(ExcelFileNames.suite.name()).forEach(value -> {
Suite suite = new Suite();
suite.setSuiteName(value);
suites.add(suite);
});
//move all other data into list
list = parser.getTestCaseFromMap(data);
//set suites to TestCase
list.forEach(testCase -> {
testCase.setSuite(suites.get(count.get()));
count.getAndIncrement();
});
return list;
}
List<TestCase> maptoTestCasePojo(Map<String, List<String>> data,
SuiteRepository suiteRepository)
throws ClassParserException, DataNotAvailableException {
List<TestCase> list;
List<Suite> suites = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
//get list of Suites
data.get(ExcelFileNames.suite.name()).forEach(value -> {
Suite suite = new Suite();
suite.setSuiteName(value);
if (suiteRepository != null) {
Optional<Suite> example = suiteRepository.findOne(Example.of(suite));
suites.add(example.orElse(suite));
} else {
suites.add(suite);
}
});
//move all other data into list
list = parser.getTestCaseFromMap(data);
//set suites to TestCase
list.forEach(testCase -> {
testCase.setSuite(suites.get(count.get()));
count.getAndIncrement();
});
return list;
}
List<TestCaseSteps> maptoTestCaseStepsPojo(Map<String, List<String>> data,
TestCaseRepository testCaseRepository, StepsRepository stepsRepository)
throws ClassParserException, DataNotAvailableException {
//Declare values
List<TestCaseSteps> list;
List<TestCase> testCases = new ArrayList<>();
List<Steps> steps = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
//getList of Test Cases from Repository for each test case name in excel spreadsheet
data.get("testCaseName").forEach(value -> {
TestCase testCase = new TestCase();
testCase.setTestCaseName(value);
if (testCaseRepository != null) {
Optional<TestCase> optional = testCaseRepository.findOne(Example.of(testCase));
testCases.add(optional.orElse(testCase));
} else {
testCases.add(testCase);
}
});
//get List of Steps from Repository for each row of step names in excel spreadsheet
data.get("steps").forEach(value -> {
Steps step = new Steps();
step.setAction(value);
if (stepsRepository != null) {
Optional<Steps> optional = stepsRepository.findOne(Example.of(step));
steps.add(optional.orElse(step));
} else {
steps.add(step);
}
});
//use class parser class to parse remaining map data into a list of TestCaseSteps
list = parser.getTestCaseStepsFromMap(data);
//for Each TestCase Step Object insert the Step from the List of Steps matching and Test Case
list.forEach(tcs -> {
tcs.setSteps(steps.get(count.get()));
tcs.setTestCase(
testCases.get(count.get()));
count.getAndIncrement();
});
return list;
}
public List<TestCaseSteps> maptoTestCaseStepsPojo(Map<String, List<String>> data)
throws ClassParserException, DataNotAvailableException {
//Declare values
List<TestCaseSteps> list;
List<TestCase> testCases = new ArrayList<>();
List<Steps> steps = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
//getList of Test Cases from Repository for each test case name in excel spreadsheet
data.get("testCaseName").forEach(value -> {
TestCase testCase = new TestCase();
testCase.setTestCaseName(value);
testCases.add(testCase);
});
//get List of Steps from Repository for each row of step names in excel spreadsheet
data.get("steps").forEach(value -> {
Steps step = new Steps();
step.setAction(value);
steps.add(step);
});
//use class parser class to parse remaining map data into a list of TestCaseSteps
list = parser.getTestCaseStepsFromMap(data);
//for Each TestCase Step Object insert the Step from the List of Steps matching and Test Case
list.forEach(tcs -> {
tcs.setSteps(steps.get(count.get()));
tcs.setTestCase(
testCases.get(count.get()));
count.getAndIncrement();
});
return list;
}
}
| [
"[email protected]"
]
| |
8df7cea4389d4953648d4fd6d1dc84248cd6ba46 | 243515d644d4b3cb81d05b65c70a564aa42b264f | /java/src/shared/outputObjects/RegisterUserOutput.java | b39974445d5efe0812a20e62cffd45c1df80cbb4 | []
| no_license | derbraun/catanpublic | 31739ef54342089fe26a6d4b05a3cc62aa0f439d | 2894aa45161a128320cf69b99827be9bc3cdf7b1 | refs/heads/master | 2021-05-11T03:48:14.450033 | 2016-09-28T04:14:52 | 2016-09-28T04:14:52 | 117,924,180 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,045 | java | package shared.outputObjects;
/**
* Holds the output parameters needed for RegisterUser()
*/
public class RegisterUserOutput extends OutputObject {
/**
* Indicates whether or not the operation was successful
*/
String success;
/**
* Creates an instance of the RegisterUser output parameters object
* @pre none
* @post An RegisterUserOutput object is created
*/
public RegisterUserOutput() {
this.success = "TRUE";
}
/**
* An overload constructor to handle failed operations
* @param success Indicates whether or not the operation was successful
*/
public RegisterUserOutput(String success) {
this.success = success;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
/**
* Indicates whether the operation was successful or not
*/
@Override
public boolean Failed() {
// TODO Auto-generated method stub
return success.equals("FALSE") || success.equals("FAILED");
}
}
| [
"[email protected]"
]
| |
6f7e5ee5171c884aaa08d46c6ad7ec9f31c712ab | a076c5e6f9aa8b7875af0c9c03ea89bd464b016d | /src/class31_Filehandling/WebDriverTasnk.java | 77b58233c3c7f9ebe8ec20831d873b9b979e15fe | []
| no_license | Guljemal1994/JavaBasics | c0f91189ad7b4735774e3eb1c4d99e2764ee23f6 | 4439131cef289031e9140b8e219fa048b000656d | refs/heads/master | 2021-04-04T02:51:06.751747 | 2020-05-17T23:21:07 | 2020-05-17T23:21:07 | 248,418,906 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 577 | java | package class31_Filehandling;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class WebDriverTasnk {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
String path = "configs\\Task.Properties";
FileInputStream fis = new FileInputStream(path);
Properties pro = new Properties();
pro.load(fis);
String b = pro.getProperty("browser");
if(b.equals("Chrome")) {
WebDriverTasnk dr = new WebDriverTasnk();
}
}
}
| [
"[email protected]"
]
| |
e9c5513bbc963f18988ca74b10ec8ecdc31af12a | 92638ec484b96f75138bb45783ed608428de346f | /src/main/java/com/Dailydrip/controller/IndexController.java | a42464eff5a2795d4599b60bf252775fe3931997 | []
| no_license | 564025324/Dailydrip | 299d5186e8e1d0ba162ca34283b5617c1544fc3c | affd7790b6380d897ae7f10e1d70a383551a402e | refs/heads/master | 2022-06-23T03:39:39.572198 | 2020-01-22T07:54:30 | 2020-01-22T07:54:30 | 210,657,057 | 0 | 0 | null | 2022-06-21T01:56:14 | 2019-09-24T17:11:22 | HTML | UTF-8 | Java | false | false | 934 | java | package com.Dailydrip.controller;
import java.util.HashMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping(value = "/index")
public String index(HashMap<String, Object> map, Model model) {
model.addAttribute("username", "li Jingwen");
map.put("username", "lijingwen map");
System.out.println("model :" + JSONObject.toJSONString(model));
return "index";
}
@RequestMapping(value = "/center")
public String center() {
return "center/center";
}
@RequestMapping(value = "/excel")
public String excelIndex() {
return "excel/excel";
}
}
| [
"[email protected]"
]
| |
e33bf1721815795c468109ea90d68701007c79ac | e5281ebba4c285069c9e2cb38d37bca0a4e45c20 | /boot-web/src/test/java/std/ach/studyolle/modules/account/AccountControllerTest.java | 8e269a6afc5d5998c724fada12a281c25737ce31 | []
| no_license | proper-for-me/std-spring-boot | fc352c14bf313078117794a63210aa32efabddc1 | 96f8bb9f11ed7d0c172c057a03759e66a7adaeb0 | refs/heads/master | 2023-04-14T02:51:14.302161 | 2020-09-03T05:27:26 | 2020-09-03T05:27:26 | 288,172,524 | 0 | 1 | null | 2021-04-28T19:06:49 | 2020-08-17T12:19:33 | Java | UTF-8 | Java | false | false | 3,428 | java | package std.ach.studyolle.modules.account;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.web.servlet.MockMvc;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
//@ExtendWith(MockitoExtension.class)
//@SpringBootTest( classes = BootWebApp.class)
@SpringBootTest
@AutoConfigureMockMvc
@Slf4j
class AccountControllerTest {
@Autowired private MockMvc mockMvc;
@Autowired AccountRepository accountRepository;
@MockBean JavaMailSender javaMailSender;
@Test
void index() throws Exception {
mockMvc.perform(get("/signup"))
.andExpect(status().isOk())
.andExpect(view().name("account/signup"))
.andDo(print())
;
}
@DisplayName("회원가입화면 호출 테스트")
@Test
void signUpForm() throws Exception {
mockMvc.perform(get("/signup"))
.andExpect(status().isOk())
.andExpect(view().name("account/signup"))
.andDo(print())
;
}
@DisplayName("회원가입화면 처리 - 입력값 오류")
@Test
void signUpSubmit_with_wrong_input() throws Exception {
mockMvc.perform(post("/signup")
.param("nickName", "user")
.param("email", "[email protected]")
.param("password","1234")
.with(csrf()) )
.andExpect(status().isOk())
.andExpect(view().name("account/signup"))
.andDo(print())
;
}
@DisplayName("회원가입화면 처리 - 입력값 정상")
@Test
void signUpSubmit_with_correct_input() throws Exception {
mockMvc.perform(post("/signup")
.param("nickName", "user")
.param("email", "[email protected]")
.param("password","12345678")
.with(csrf()) )
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"))
.andDo(print())
;
assertNotNull(accountRepository.existsByEmail("[email protected]"));
Account account = accountRepository.findByEmail("[email protected]");
log.info(" ************************* " + account.getPassword());
assertNotNull(account);
assertNotEquals(account.getPassword(), "12345678");
then(javaMailSender).should().send(any(SimpleMailMessage.class));
;
}
} | [
"[email protected]"
]
| |
86c9664f6364d16b0721d1aca0ddb3a64238b64d | 6615ed1484855b3d9624d5cf77258688667978c1 | /app/src/main/java/com/example/administrator/myapplication/SpendingPieChartActivity.java | ab50f3bffa2501b31a81952520fa50a25002d250 | []
| no_license | huixiaoyang/Keep-Accounts | 47a1d83bb61587d46c8b9420c198f4150e75ac18 | b4826fe1a712575e8dd56fccd17f1527ac0747d7 | refs/heads/master | 2020-03-06T22:50:08.423602 | 2018-04-08T09:39:59 | 2018-04-08T09:39:59 | 127,115,151 | 0 | 1 | null | 2018-04-08T09:08:08 | 2018-03-28T09:16:06 | Java | UTF-8 | Java | false | false | 7,305 | java | package com.example.administrator.myapplication;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.view.View;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
/**
* Created by Administrator on 2018\4\6 0006.
*/
public class SpendingPieChartActivity extends AppCompatActivity implements OnChartValueSelectedListener {
private PieChart mPieChart;
private DatabaseHelper databaseHelper;
public static String TABLE_NAME_SPENDING = "acounts";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spending_pie_chart);
databaseHelper = new DatabaseHelper(this);
initChart();
}
public void btnReturnMain(View view) {
//to do when the button is clicked
startActivity(new Intent(this, MainActivity.class));
finish();
}
public void btnReturnIncome(View view) {
//to do when the button is clicked
startActivity(new Intent(this, IncomePieChartActivity.class));
finish();
}
private void initChart() {
mPieChart = (PieChart) findViewById(R.id.mPieChart);
mPieChart.setUsePercentValues(true);//设置value是否用显示百分数
//mPieChart.getDescription().setEnabled(false);
mPieChart.setExtraOffsets(5, 10, 5, 5);//设置图距离上下左右的偏移量
mPieChart.setDragDecelerationFrictionCoef(0.95f);//设置阻尼系数,范围在[0,1]之间,越小饼状图转动越困难
mPieChart.setDrawHoleEnabled(true);//是否绘制饼状图中间的圆
mPieChart.setHoleColor(Color.WHITE);//饼状图中间的圆的绘制颜色
mPieChart.setHoleRadius(58f);//饼状图中间的圆的半径大小
mPieChart.setTransparentCircleColor(Color.WHITE);//设置圆环的颜色
mPieChart.setTransparentCircleAlpha(110);//设置圆环的透明度[0,255]
mPieChart.setTransparentCircleRadius(61f);//设置圆环的半径值
mPieChart.setDrawCenterText(true);//是否绘制中间的文字
mPieChart.setCenterText(generateCenterSpannableText());//设置中间文字
mPieChart.setCenterTextSize(24);//中间的文字字体大小
mPieChart.setRotationEnabled(true);//设置饼状图是否可以旋转(默认为true)
mPieChart.setRotationAngle(0);//设置饼状图旋转的角度
mPieChart.setHighlightPerTapEnabled(true);//设置旋转的时候点中的tab是否高亮(默认为true)
//变化监听
mPieChart.setOnChartValueSelectedListener(this);
//从数据库中获取数据并使用数据
ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
getData(entries);
mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);//设置Y轴上的绘制动画
Legend l = mPieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);//设置tab之间Y轴方向上的空白间距值
l.setYOffset(0f);
// 设置每块扇形中文字标签样式
mPieChart.setEntryLabelColor(Color.BLACK);
mPieChart.setEntryLabelTextSize(12f);
}
//设置中间文字
private SpannableString generateCenterSpannableText() {
SpannableString s = new SpannableString("Spending");
return s;
}
private void getData(ArrayList<PieEntry> entries) {
Cursor cursor = databaseHelper.readData(TABLE_NAME_SPENDING);
if (cursor.getCount() != 0) {
float[] intMoney = new float[50];
String[] strType = new String[50];
int flag = 1;
if (cursor.getCount() != 0) {
cursor.moveToLast();
String tempType = cursor.getString(1);
String tempMoney = cursor.getString(4);
float tempIntMoney = Float.valueOf(tempMoney);
strType[0] = tempType;
intMoney[0] = tempIntMoney;
flag:
while (cursor.moveToPrevious()) {
tempType = cursor.getString(1);
tempMoney = cursor.getString(4);
tempIntMoney = Float.valueOf(tempMoney);
for (int i = 0; i < flag; i++) {
if (strType[i].equals(tempType)) {
intMoney[i] = intMoney[i] + tempIntMoney;
continue flag;
}
}
strType[flag] = tempType;
intMoney[flag] = tempIntMoney;
++flag;
}
}
//Toast.makeText(this,Integer.toString(strType.length), Toast.LENGTH_SHORT).show();
float totalmoney = 0;
for (int i = 0; i < flag; i++)
totalmoney = totalmoney + intMoney[i];
for (int i = 0; i < flag; i++) {
entries.add(new PieEntry(100 * intMoney[i] / totalmoney, strType[i]));
}
//使用数据
setData(entries);
}
}
private void setData(ArrayList<PieEntry> entries) {
PieDataSet dataSet = new PieDataSet(entries, "Spending");
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
//数据和颜色
ArrayList<Integer> colors = new ArrayList<Integer>();
for (int c : ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
for (int c : ColorTemplate.JOYFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.COLORFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.LIBERTY_COLORS)
colors.add(c);
for (int c : ColorTemplate.PASTEL_COLORS)
colors.add(c);
colors.add(ColorTemplate.getHoloBlue());
dataSet.setColors(colors);
PieData data = new PieData(dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
mPieChart.setData(data);
mPieChart.highlightValues(null);
//刷新
mPieChart.invalidate();
}
@Override
public void onValueSelected(Entry e, Highlight h) {
}
@Override
public void onNothingSelected() {
}
}
| [
"[email protected]"
]
| |
30f058a790f2d743c3831fa7667c9778e6ba3626 | 6c68e07f78438ad961114c3543e1a8de3f8c538b | /Tron/model/src/main/java/DAO/TronBDDConnector.java | e31543aa4891e1e2de0f4aa3f095937026a012b0 | []
| no_license | SheillaKamdem/GAME | 9a9e3281468bde0371cbabe2e2c528976d9936e3 | 4ffd5a8d0f3d87c2341a00d62f42ea5441135c0b | refs/heads/master | 2022-07-19T09:05:13.610604 | 2019-07-08T22:16:03 | 2019-07-08T22:16:03 | 195,892,250 | 0 | 0 | null | 2022-06-21T01:27:00 | 2019-07-08T22:05:49 | Java | UTF-8 | Java | false | false | 3,343 | java |
package DAO;
/**
* @author KAMDEM
* @version 1.0
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import model.ITronBDDConector;
/**
* <h1>The Class LoranBDDConnector.</h1>
*
*
* @version 1.0
*/
final class TronBDDConnector implements ITronBDDConector{
/** The instance. */
private static TronBDDConnector instance;
/** The login. */
private static String user = "root";
/** The password. */
private static String password = "";
/** The url. */
private static String url = "jdbc:mysql://localhost/tron?useSSL=false&serverTimezone=UTC";
/** The connection. */
private Connection connection;
/** The statement. */
private Statement statement;
/**
* Instantiates a new BDD connector.
*/
private TronBDDConnector() {
this.open();
}
/**
* Gets the single instance of TronBDDConnector.
*
* @return single instance of TronBDDConnector
*/
public static TronBDDConnector getInstance() {
if (instance == null) {
setInstance(new TronBDDConnector());
}
return instance;
}
/**
* Sets the instance.
*
* @param instance
* the new instance
*/
private static void setInstance(final TronBDDConnector instance) {
TronBDDConnector.instance = instance;
}
/**
* Open.
*
* @return true, if successful
*/
private boolean open() {
try {
this.connection = DriverManager.getConnection(TronBDDConnector.url, TronBDDConnector.user,
TronBDDConnector.password);
this.statement = this.connection.createStatement();
return true;
} catch (final SQLException exception) {
exception.printStackTrace();
}
return false;
}
/**
* Execute query.
*
* @param query
* the query
* @return the result set
*/
public ResultSet executeQuery(final String query) {
try {
return this.getStatement().executeQuery(query);
} catch (final SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Prepare call.
*
* @param query
* the query
* @return the java.sql. callable statement
*/
public java.sql.CallableStatement prepareCall(final String query) {
try {
return this.getConnection().prepareCall(query);
} catch (final SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Execute update.
*
* @param query
* the query
* @return the int
*/
public int executeUpdate(final String query) {
try {
return this.statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
} catch (final SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the connection.
*
* @return the connection
*/
private Connection getConnection() {
return this.connection;
}
/**
* Sets the connection.
*
* @param connection
* the new connection
*/
public void setConnection(final Connection connection) {
this.connection = connection;
}
/**
* Gets the statement.
*
* @return the statement
*/
private Statement getStatement() {
return this.statement;
}
/**
* Sets the statement.
*
* @param statement
* the new statement
*/
public void setStatement(final Statement statement) {
this.statement = statement;
}
}
| [
"HP@LAPTOP-LKUAOGQ9"
]
| HP@LAPTOP-LKUAOGQ9 |
a4e798dc3bf82c991114cf622b42f2614827330f | 92ced26f361a2d48d216f46b6ff4a4deda7ce3e0 | /TdBus/src/test/java/com/rex/tdbus/ExampleUnitTest.java | d6106be88b3f27249d8c3bc70cb68d4c8012593c | []
| no_license | wenfu92/TdAndroid | 8724eddf07f88f6affe5a6bf2686a67ac35950f1 | 87a8b3887b747ef32b983f51a1266eb78f5cf778 | refs/heads/master | 2020-05-16T10:25:08.771634 | 2019-04-23T09:44:23 | 2019-04-23T09:44:23 | 182,984,083 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 374 | java | package com.rex.tdbus;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
aa1e8d3df708ee5bd8ac2a800150d5287d1946c3 | 84e0bbd1f244bd703bed304cc8bb26fd3e1073bd | /SearchApp/src/org/nacao/searchapp/statistics/StatisticsChart.java | 60cddd7e8450ded476c63451ffd9559d2d02772e | []
| no_license | lzy-persist/pro_app | 7789e437d8dbf9aaec72acc7dfa7c2cf80f36726 | a12f39435bd3f6c6834ef1ad5a7b2092c6ba5a6b | refs/heads/master | 2016-09-06T17:18:00.905832 | 2013-04-11T02:34:06 | 2013-04-11T02:34:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package org.nacao.searchapp.statistics;
import android.content.Context;
import android.content.Intent;
public interface StatisticsChart {
String NAME = "name";
String DESC = "desc";
String getName();
String getDesc();
Intent execute(Context context);
}
| [
"[email protected]"
]
| |
b08a2c7f85eccabee9c0c96e5ebe0d761fd3e194 | 77fc56c933bdb229047c486b2f227fdd08822d63 | /epzilla 1.0.0/src/net/epzilla/stratification/restruct/SystemRestructure.java | 1f6147fc00e030fb38088c28bf00d85ec7b9d6e0 | []
| no_license | harshana05/epzilla | 45d8597ed33da7a89dfd8607a7402914c33383ff | 22e3558315120024b799063ec607c44b17f636be | refs/heads/master | 2021-01-25T06:01:07.065887 | 2011-10-30T06:13:24 | 2011-10-30T06:13:24 | 33,530,906 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,351 | java | /***************************************************************************************************
Copyright 2009 - 2010 Harshana Eranga Martin, Dishan Metihakwala, Rajeev Sampath, Chathura Randika
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 net.epzilla.stratification.restruct;
import jstm.core.TransactedList;
import net.epzilla.stratification.dynamic.SystemVariables;
import net.epzilla.stratification.query.BasicQueryParser;
import net.epzilla.stratification.query.InvalidSyntaxException;
import net.epzilla.stratification.query.Query;
import net.epzilla.stratification.query.QueryParser;
import org.epzilla.clusterNode.clusterInfoObjectModel.NodeIPObject;
import org.epzilla.clusterNode.dataManager.ClusterIPManager;
import org.epzilla.dispatcher.clusterHandler.TriggerSender;
import org.epzilla.dispatcher.dataManager.TriggerManager;
import org.epzilla.dispatcher.dispatcherObjectModel.TriggerInfoObject;
import org.epzilla.dispatcher.rmi.TriggerRepresentation;
import org.epzilla.util.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.util.*;
/**
* responsible for performin operations related to reorgaizing the query base.
*/
public class SystemRestructure {
private static SystemRestructure instance = new SystemRestructure();
public static SystemRestructure getInstance() {
return instance;
}
/**
* reorganizes the query base.
*
* @throws InvalidSyntaxException
*/
public void restructureSystem() throws InvalidSyntaxException {
LinkedList<TriggerInfoObject> list = new LinkedList(TriggerManager.getTriggers());
HashMap<String, LinkedList<TriggerInfoObject>> map = new HashMap();
for (Object o : list) {
if (o instanceof TriggerInfoObject) {
TriggerInfoObject tio = (TriggerInfoObject) o;
try {
if (!"OOOO".equals(tio.gettrigger()) && (tio.gettrigger().length() > 10)) {
LinkedList<TriggerInfoObject> clist = map.get(tio.getclientID());
if (clist == null) {
clist = new LinkedList();
map.put(tio.getclientID(), clist);
}
clist.add(tio);
}
} catch (Exception e) {
Logger.error("", e);
}
}
}
LinkedList<LinkedList<LinkedList<Cluster>>> slist = new LinkedList();
LinkedList<TriggerStrcutureManager> tsmlist = new LinkedList();
for (String clientId : map.keySet()) {
try {
LinkedList<TriggerInfoObject> clientList = map.get(clientId);
TriggerStrcutureManager tsm = new TriggerStrcutureManager();
tsm.setClientId(clientId);
slist.add(tsm.getVirtualStructure(clientList));
tsmlist.add(tsm);
} catch (Exception ex) {
Logger.error("", ex);
}
}
LinkedList<Cluster> total = new LinkedList<Cluster>();
for (LinkedList<LinkedList<Cluster>> l1 : slist) {
for (LinkedList<Cluster> l2 : l1) {
total.addAll(l2);
}
}
Collections.sort(total, new Cluster.ClusterComparator());
redistribute(total);
for (TriggerStrcutureManager tsx : tsmlist) {
tsx.restructure();
}
// fully restructured.
}
/**
* sends required information for clusters in order to finalize trigger redistribution.
* @return
*/
public boolean sendRestructureCommands() {
try {
TransactedList<TriggerInfoObject> trList = TriggerManager.getTriggers();
HashMap<String, HashMap<String, HashMap<String, ArrayList<TriggerRepresentation>>>> remList = new HashMap();
HashMap<String, HashMap<String, HashMap<String, ArrayList<TriggerRepresentation>>>> addList = new HashMap();
for (TriggerInfoObject tio : trList) {
if ((!tio.getclusterID().equals(tio.getoldClusterId())) || (!tio.getstratumId().equals(tio.getoldStratumId()))) {
HashMap<String, HashMap<String, ArrayList<TriggerRepresentation>>> remStratum = remList.get(tio.getoldStratumId());
HashMap<String, HashMap<String, ArrayList<TriggerRepresentation>>> addStratum = addList.get(tio.getstratumId());
if (remStratum == null) {
remStratum = new HashMap();
remList.put(tio.getoldStratumId(), remStratum);
}
if (addStratum == null) {
addStratum = new HashMap();
addList.put(tio.getstratumId(), addStratum);
}
HashMap<String, ArrayList<TriggerRepresentation>> remCluster = remStratum.get(tio.getoldClusterId());
HashMap<String, ArrayList<TriggerRepresentation>> addCluster = addStratum.get(tio.getclusterID());
if (remCluster == null) {
remCluster = new HashMap();
remStratum.put(tio.getoldClusterId(), remCluster);
}
if (addCluster == null) {
addCluster = new HashMap();
addStratum.put(tio.getclusterID(), addCluster);
}
ArrayList<TriggerRepresentation> rem = remCluster.get(tio.getclientID());
ArrayList<TriggerRepresentation> add = addCluster.get(tio.getclientID());
if (rem == null) {
rem = new ArrayList<TriggerRepresentation>();
// rem.setClientId(tio.getclientID());
remCluster.put(tio.getclientID(), rem);
}
if (add == null) {
add = new ArrayList<TriggerRepresentation>();
addCluster.put(tio.getclientID(), add);
}
TriggerRepresentation at = new TriggerRepresentation();
TriggerRepresentation rt = new TriggerRepresentation();
at.setClientId(tio.getclientID());
at.setTriggerId(tio.gettriggerID());
at.setTrigger(tio.gettrigger());
rt.setClientId(tio.getclientID());
rt.setTriggerId(tio.gettriggerID());
add.add(at);
rem.add(rt);
// rem.addTriggerIds(tio.gettriggerID());
}
}
Logger.log("sending command.");
for (String stratum : remList.keySet()) {
TransactedList<NodeIPObject> tl = ClusterIPManager.getIpList();
Logger.log("tl size:" + tl.size());
for (NodeIPObject no : tl) {
String id = no.getclusterID();
if (remList.get(stratum).containsKey(id)) {
HashMap<String, ArrayList<TriggerRepresentation>> m = remList.get(stratum).get(id);
for (String user : m.keySet()) {
ArrayList<TriggerRepresentation> al = m.get(user);
TriggerSender.requestTriggerDeletion(no.getIP(), id, al, user);
}
}
}
}
for (String stratum : addList.keySet()) {
TransactedList<NodeIPObject> tl = ClusterIPManager.getIpList();
for (NodeIPObject no : tl) {
String id = no.getclusterID();
if (addList.get(stratum).containsKey(id)) {
HashMap<String, ArrayList<TriggerRepresentation>> m = addList.get(stratum).get(id);
for (String user : m.keySet()) {
ArrayList<TriggerRepresentation> al = m.get(user);
TriggerSender.triggerAdding(no.getIP(), id, al, user);
}
}
}
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* assigns real strata and clusters to the virtual structure.
* @param total
*/
private void redistribute(LinkedList<Cluster> total) {
int i = 0;
int j = 0;
int sts = SystemVariables.getNumStrata();
int stsm1 = sts - 1;
boolean increasing = true;
for (int x = 0; x < sts; x++) {
int cls = SystemVariables.getClusters(x) - 1;
j = 0;
for (Cluster c : total) {
if ((c.getStratum() == x) || (c.getStratum() > x && x == stsm1)) {
c.setRealStratum(x);
if (!c.isIndependent()) {
if ((j <= cls) && (j >= 0)) {
c.setRealCluster(j);
} else {
if (increasing) {
j = cls;
increasing = false;
} else {
j = 0;
increasing = true;
}
c.setRealCluster(j);
}
if (increasing) {
j++;
} else {
j--;
}
}
}
}
}
}
}
| [
"harshana05@6d78cf82-acc7-11de-ba6e-69e41c8db662"
]
| harshana05@6d78cf82-acc7-11de-ba6e-69e41c8db662 |
8344fab8f1d37b9fe8d33be3a59c3824b34048b6 | 16ca4ab455fb1c0a1fb538ff869bb99f0f238404 | /app/src/main/pb_gen/com/yijianyi/protocol/OrderSAAS.java | 297e7800e2f2a309cde34c3f96c09a0c9720c045 | []
| no_license | Yiny123/USER | 6de6abe9aff5d629795ea1202154ec9294b4729b | 7b441814435eb3b225323b1160151edb51afe465 | refs/heads/master | 2020-03-17T13:01:35.625547 | 2018-05-16T05:18:04 | 2018-05-16T05:18:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,374 | java | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: AppInterface.proto at 856:1
package com.yijianyi.protocol;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireField;
import com.squareup.wire.internal.Internal;
import java.io.IOException;
import java.lang.Integer;
import java.lang.Long;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import okio.ByteString;
public final class OrderSAAS extends Message<OrderSAAS, OrderSAAS.Builder> {
public static final ProtoAdapter<OrderSAAS> ADAPTER = new ProtoAdapter_OrderSAAS();
private static final long serialVersionUID = 0L;
public static final String DEFAULT_CREATETIMESTR = "";
public static final Long DEFAULT_CREATETIME = 0L;
public static final Integer DEFAULT_ORDERSTATUS = 0;
public static final String DEFAULT_ORDERSTATUSSTR = "";
@WireField(
tag = 1,
adapter = "com.yijianyi.protocol.Order#ADAPTER"
)
public final Order orders;
/**
* 下单时间
*/
@WireField(
tag = 2,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String createTimestr;
/**
* 下单时间
*/
@WireField(
tag = 3,
adapter = "com.squareup.wire.ProtoAdapter#UINT64"
)
public final Long createTime;
/**
* 状态 1-待指派 2-等待服务 ,3-服务中 , 4-待结算 ,6-已完成
*/
@WireField(
tag = 4,
adapter = "com.squareup.wire.ProtoAdapter#UINT32"
)
public final Integer orderStatus;
@WireField(
tag = 5,
adapter = "com.squareup.wire.ProtoAdapter#STRING"
)
public final String orderStatusStr;
public OrderSAAS(Order orders, String createTimestr, Long createTime, Integer orderStatus, String orderStatusStr) {
this(orders, createTimestr, createTime, orderStatus, orderStatusStr, ByteString.EMPTY);
}
public OrderSAAS(Order orders, String createTimestr, Long createTime, Integer orderStatus, String orderStatusStr, ByteString unknownFields) {
super(ADAPTER, unknownFields);
this.orders = orders;
this.createTimestr = createTimestr;
this.createTime = createTime;
this.orderStatus = orderStatus;
this.orderStatusStr = orderStatusStr;
}
@Override
public Builder newBuilder() {
Builder builder = new Builder();
builder.orders = orders;
builder.createTimestr = createTimestr;
builder.createTime = createTime;
builder.orderStatus = orderStatus;
builder.orderStatusStr = orderStatusStr;
builder.addUnknownFields(unknownFields());
return builder;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof OrderSAAS)) return false;
OrderSAAS o = (OrderSAAS) other;
return unknownFields().equals(o.unknownFields())
&& Internal.equals(orders, o.orders)
&& Internal.equals(createTimestr, o.createTimestr)
&& Internal.equals(createTime, o.createTime)
&& Internal.equals(orderStatus, o.orderStatus)
&& Internal.equals(orderStatusStr, o.orderStatusStr);
}
@Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = unknownFields().hashCode();
result = result * 37 + (orders != null ? orders.hashCode() : 0);
result = result * 37 + (createTimestr != null ? createTimestr.hashCode() : 0);
result = result * 37 + (createTime != null ? createTime.hashCode() : 0);
result = result * 37 + (orderStatus != null ? orderStatus.hashCode() : 0);
result = result * 37 + (orderStatusStr != null ? orderStatusStr.hashCode() : 0);
super.hashCode = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (orders != null) builder.append(", orders=").append(orders);
if (createTimestr != null) builder.append(", createTimestr=").append(createTimestr);
if (createTime != null) builder.append(", createTime=").append(createTime);
if (orderStatus != null) builder.append(", orderStatus=").append(orderStatus);
if (orderStatusStr != null) builder.append(", orderStatusStr=").append(orderStatusStr);
return builder.replace(0, 2, "OrderSAAS{").append('}').toString();
}
public static final class Builder extends Message.Builder<OrderSAAS, Builder> {
public Order orders;
public String createTimestr;
public Long createTime;
public Integer orderStatus;
public String orderStatusStr;
public Builder() {
}
public Builder orders(Order orders) {
this.orders = orders;
return this;
}
/**
* 下单时间
*/
public Builder createTimestr(String createTimestr) {
this.createTimestr = createTimestr;
return this;
}
/**
* 下单时间
*/
public Builder createTime(Long createTime) {
this.createTime = createTime;
return this;
}
/**
* 状态 1-待指派 2-等待服务 ,3-服务中 , 4-待结算 ,6-已完成
*/
public Builder orderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
return this;
}
public Builder orderStatusStr(String orderStatusStr) {
this.orderStatusStr = orderStatusStr;
return this;
}
@Override
public OrderSAAS build() {
return new OrderSAAS(orders, createTimestr, createTime, orderStatus, orderStatusStr, super.buildUnknownFields());
}
}
private static final class ProtoAdapter_OrderSAAS extends ProtoAdapter<OrderSAAS> {
ProtoAdapter_OrderSAAS() {
super(FieldEncoding.LENGTH_DELIMITED, OrderSAAS.class);
}
@Override
public int encodedSize(OrderSAAS value) {
return (value.orders != null ? Order.ADAPTER.encodedSizeWithTag(1, value.orders) : 0)
+ (value.createTimestr != null ? ProtoAdapter.STRING.encodedSizeWithTag(2, value.createTimestr) : 0)
+ (value.createTime != null ? ProtoAdapter.UINT64.encodedSizeWithTag(3, value.createTime) : 0)
+ (value.orderStatus != null ? ProtoAdapter.UINT32.encodedSizeWithTag(4, value.orderStatus) : 0)
+ (value.orderStatusStr != null ? ProtoAdapter.STRING.encodedSizeWithTag(5, value.orderStatusStr) : 0)
+ value.unknownFields().size();
}
@Override
public void encode(ProtoWriter writer, OrderSAAS value) throws IOException {
if (value.orders != null) Order.ADAPTER.encodeWithTag(writer, 1, value.orders);
if (value.createTimestr != null) ProtoAdapter.STRING.encodeWithTag(writer, 2, value.createTimestr);
if (value.createTime != null) ProtoAdapter.UINT64.encodeWithTag(writer, 3, value.createTime);
if (value.orderStatus != null) ProtoAdapter.UINT32.encodeWithTag(writer, 4, value.orderStatus);
if (value.orderStatusStr != null) ProtoAdapter.STRING.encodeWithTag(writer, 5, value.orderStatusStr);
writer.writeBytes(value.unknownFields());
}
@Override
public OrderSAAS decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1;) {
switch (tag) {
case 1: builder.orders(Order.ADAPTER.decode(reader)); break;
case 2: builder.createTimestr(ProtoAdapter.STRING.decode(reader)); break;
case 3: builder.createTime(ProtoAdapter.UINT64.decode(reader)); break;
case 4: builder.orderStatus(ProtoAdapter.UINT32.decode(reader)); break;
case 5: builder.orderStatusStr(ProtoAdapter.STRING.decode(reader)); break;
default: {
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
@Override
public OrderSAAS redact(OrderSAAS value) {
Builder builder = value.newBuilder();
if (builder.orders != null) builder.orders = Order.ADAPTER.redact(builder.orders);
builder.clearUnknownFields();
return builder.build();
}
}
}
| [
"[email protected]"
]
| |
647b70a70e4eefb25719898e0a8b293e147a0bb9 | 3ae236b4b3fcd69d93dc9dcc033ca1a267b42a9b | /src/main/java/com/evilcry/shardingspheredemo/mybatis/service/SpringUserServiceImpl.java | dbce3168186b4966d9480e586782499d729ca65f | []
| no_license | surick/shardingsphere-demo | c812f74ec6ff6f5cfe44d08e014970b57f1fc10c | ecdae0d96420704147e64e135f8f9339e5ecd0d6 | refs/heads/master | 2020-05-31T05:36:14.680145 | 2019-06-04T03:19:15 | 2019-06-04T03:19:15 | 190,121,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,208 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evilcry.shardingspheredemo.mybatis.service;
import com.evilcry.shardingspheredemo.api.entity.User;
import com.evilcry.shardingspheredemo.api.repository.UserRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class SpringUserServiceImpl implements UserService {
@Resource
private UserRepository userRepository;
@Override
public void initEnvironment() {
userRepository.createTableIfNotExists();
userRepository.truncateTable();
}
@Override
public void cleanEnvironment() {
userRepository.dropTable();
}
@Override
public void processSuccess() {
System.out.println("-------------- Process Success Begin ---------------");
List<Long> userIds = insertData();
printData();
deleteData(userIds);
printData();
System.out.println("-------------- Process Success Finish --------------");
}
private List<Long> insertData() {
System.out.println("---------------------------- Insert Data ----------------------------");
List<Long> result = new ArrayList<>(10);
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("test_mybatis_" + i);
user.setPwd("pwd_mybatis_" + i);
userRepository.insert(user);
result.add((long) user.getUserId());
}
return result;
}
@Override
public void processFailure() {
System.out.println("-------------- Process Failure Begin ---------------");
insertData();
System.out.println("-------------- Process Failure Finish --------------");
throw new RuntimeException("Exception occur for transaction test.");
}
private void deleteData(final List<Long> userIds) {
System.out.println("---------------------------- Delete Data ----------------------------");
for (Long each : userIds) {
userRepository.delete(each);
}
}
@Override
public void printData() {
System.out.println("---------------------------- Print User Data -----------------------");
for (Object each : userRepository.selectAll()) {
System.out.println(each);
}
}
}
| [
"[email protected]"
]
| |
fb633f0ddce56399830be295cb10aa6a82d8ee7f | 14f5b2ab71d482bf1e8a6e8f697199cc5554ae40 | /app/src/androidTest/java/isfaaghyth/app/advanced/ExampleInstrumentedTest.java | 6c91b625ac8b03b2cf2c8ef0e894c47943afbea7 | []
| no_license | isfaaghyth/IAK-Advanced | 01d75c71d5a2b5c9e49d239e022fe4b0adaddd88 | d729b852eec46e9d8b94cf38650aa59c15fbedcd | refs/heads/master | 2020-12-30T15:30:24.853868 | 2017-05-14T08:15:45 | 2017-05-14T08:15:45 | 91,151,598 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 750 | java | package isfaaghyth.app.advanced;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("isfaaghyth.app.advanced", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
aa2e2cf268b15bff03765714534c8a8f0b1ac9e1 | a84426616b0e3262334a42aa891880d8bb413d39 | /CrazyChatClient/src/com/crazychat/client/ui/TopPanel.java | 4932be882b7ff74b8636ace8eed52eeecdce5cfa | [
"MIT"
]
| permissive | superferryman/CrazyChat | e66e4f48912bdc164b24f8e549bb2209f911cdff | 43f1d95d387969a58dd5de6fbc25d823bdc40db7 | refs/heads/master | 2020-05-24T19:58:37.997628 | 2018-06-09T18:17:13 | 2018-06-09T18:17:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,760 | java | package com.crazychat.client.ui;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.border.EmptyBorder;
import com.crazychat.client.ClientService;
import com.crazychat.client.constant.ColorConst;
import com.crazychat.client.constant.ImageConst;
import com.crazychat.client.constant.StringConst;
import com.crazychat.client.ui.component.AnimatePanel;
import com.crazychat.client.ui.component.FrameControlButtons;
import com.crazychat.client.ui.listener.FrameControlButtonsListener;
/**
* 客户端顶栏面板
*
* @author RuanYaofeng
* @date 2018-04-19 09:25
*/
@SuppressWarnings("serial")
public class TopPanel extends AnimatePanel {
/** 外层Frame */
private MainFrame mainFrame;
/*
* 标签页
*/
public static final int TAB_DIALOG = 0;
public static final int TAB_CONTACTS = 1;
/** 储存当前标签页索引 */
int tabIndex = 0;
/*
* 用户状态组件
*/
private JLabel lblUserPicture;
private JLabel lblUserNickname;
private JLabel lblUserStatus;
/*
* 标签切换按钮
*/
private JButton btnDialogTab;
private JButton btnContactsTab;
/** 窗口控制按钮 */
private FrameControlButtons frameControlButtons;
/*
* 尺寸定义
*/
private Dimension cornerBoxSize = new Dimension(240, 56);
private Dimension userHeadSize = new Dimension(40, 40);
/** 储存鼠标按下位置 (实现窗口拖动) */
Point dragStartPoint;
/**
* Create the panel.
*
* @param parentFrame 外层Frame容器
*/
public TopPanel(MainFrame mainFrame) {
this.mainFrame = mainFrame;
initUI(); // 初始化UI控件
initEvent();// 初始化窗口事件
}
/**
* @return the tabIndex
*/
public int getTabIndex() {
return tabIndex;
}
/**
* @param tabIndex the tabIndex to set
*/
public void setTabIndex(int tabIndex) {
this.tabIndex = tabIndex;
}
/**
* 初始化UI控件
*/
void initUI() {
/*
* 整体布局 (分为左中右3个Box)
*/
setBackground(ColorConst.THEME_PRIMARY);
setLayout(new BorderLayout(0, 0));
Box userBox = Box.createHorizontalBox();
Box tabBox = Box.createHorizontalBox();
Box menuBox = Box.createHorizontalBox();
userBox.setPreferredSize(cornerBoxSize);
menuBox.setPreferredSize(cornerBoxSize);
add(userBox, BorderLayout.WEST);
add(tabBox);
add(menuBox, BorderLayout.EAST);
// 设置鼠标为默认 (解决窗口拖曳和ResizableFrame冲突)
setCursor(Cursor.getDefaultCursor());
/*
* 左侧用户信息布局
*/
lblUserPicture = new JLabel();
lblUserNickname = new JLabel(ClientService.currentUser.getNickname());
lblUserStatus = new JLabel(StringConst.STATUS_ONLINE);
lblUserPicture.setBorder(new EmptyBorder(8, 8, 8, 8));
setUserPicture(ImageConst.IC_USER_PICTURES[ClientService.currentUser.getPictureId()]);
lblUserPicture.setCursor(new Cursor(Cursor.HAND_CURSOR));
lblUserNickname.setFont(new Font(StringConst.DEFAULT_FONT_NAME, Font.BOLD, 16));
lblUserStatus.setIcon(ImageConst.IC_USER_STATUS_ONLINE);
lblUserNickname.setForeground(ColorConst.TEXT_TITLE_PRIMARY);
lblUserStatus.setForeground(ColorConst.TEXT_TITLE_PRIMARY);
// 布局
Box userTextBox = Box.createVerticalBox();
userTextBox.add(lblUserNickname);
userTextBox.add(lblUserStatus);
userBox.add(lblUserPicture);
userBox.add(userTextBox);
/*
* 中间标签切换按钮布局
*/
btnDialogTab = new JButton(StringConst.MESSAGE);
btnContactsTab = new JButton(StringConst.FRIEND);
Font tabFont = new Font(StringConst.DEFAULT_FONT_NAME, Font.PLAIN, 16);
btnDialogTab.setFont(tabFont);
btnContactsTab.setFont(tabFont);
btnDialogTab.setHorizontalTextPosition(JButton.LEFT); // 文字在图标左侧
btnDialogTab.setRolloverIcon(ImageConst.IC_TAB_DIALOG_FOCUS);
btnContactsTab.setRolloverIcon(ImageConst.IC_TAB_CONTACTS_FOCUS);
updateTabStatus(); // 更新标签按钮状态
btnDialogTab.setBorder(null);
btnContactsTab.setBorder(null);
btnDialogTab.setContentAreaFilled(false);
btnContactsTab.setContentAreaFilled(false);
btnDialogTab.setFocusPainted(false);
btnContactsTab.setFocusPainted(false);
// 布局
tabBox.add(Box.createHorizontalGlue());
tabBox.add(btnDialogTab);
tabBox.add(Box.createHorizontalStrut(16));
tabBox.add(btnContactsTab);
tabBox.add(Box.createHorizontalGlue());
/*
* 右侧按钮布局 (窗口控制按钮)
*/
frameControlButtons = new FrameControlButtons(mainFrame);
menuBox.add(Box.createHorizontalGlue()); // 按钮前填充空白
menuBox.add(frameControlButtons);
}
/**
* 初始化事件监听
*/
private void initEvent() {
/*
* 重写关闭按钮监听
*/
frameControlButtons.setFrameControlButtonsListener(new FrameControlButtonsListener() {
@Override
public void onCloseButtonClick() {
int result = JOptionPane.showConfirmDialog(null, StringConst.REALLY_TO_EXIT, StringConst.CRAZYCHAT,
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
/*
* 实现窗口拖曳
*/
MouseListener windowDragListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
dragStartPoint = e.getPoint(); // 获取到的坐标是相对于容器而非屏幕
}
};
this.addMouseListener(windowDragListener);
MouseMotionListener windowDragMotionListener = new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
// mouseDragged触发时的窗口位置
Point frameLocation = mainFrame.getLocation();
mainFrame.setLocation(frameLocation.x - dragStartPoint.x + e.getX(),
frameLocation.y - dragStartPoint.y + e.getY());
}
};
this.addMouseMotionListener(windowDragMotionListener);
/*
* 标签切换的处理
*/
MouseListener btnTabMouseListener = new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
((JButton) e.getSource()).setForeground(ColorConst.TEXT_TITLE_PRIMARY);
}
@Override
public void mouseExited(MouseEvent e) {
updateTabStatus();
}
};
btnDialogTab.addMouseListener(btnTabMouseListener);
btnContactsTab.addMouseListener(btnTabMouseListener);
ActionListener btnTabActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 将要切换到的标签索引
int switchTargetIndex = tabIndex;
if (e.getSource() == btnDialogTab) {
switchTargetIndex = TAB_DIALOG;
} else if (e.getSource() == btnContactsTab) {
switchTargetIndex = TAB_CONTACTS;
}
// 只能切换到不同的标签
if (tabIndex != switchTargetIndex) {
tabIndex = switchTargetIndex;
mainFrame.switchTab(tabIndex);
}
}
};
btnDialogTab.addActionListener(btnTabActionListener);
btnContactsTab.addActionListener(btnTabActionListener);
/*
* 点击头像修改资料
*/
lblUserPicture.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ClientService.showEditProfileFrame();
}
@Override
public void mouseEntered(MouseEvent e) {
lblUserPicture.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
BorderFactory.createLineBorder(ColorConst.THEME_PRIMARY_DARK, 4)));
}
@Override
public void mouseExited(MouseEvent e) {
lblUserPicture.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
}
});
}
/**
* 根据当前标签更新标签按钮状态
*/
public void updateTabStatus() {
// 按钮状态重置
btnDialogTab.setIcon(ImageConst.IC_TAB_DIALOG_NORMAL);
btnContactsTab.setIcon(ImageConst.IC_TAB_CONTACTS_NORMAL);
btnDialogTab.setForeground(ColorConst.TEXT_TITLE_SECONDARY);
btnContactsTab.setForeground(ColorConst.TEXT_TITLE_SECONDARY);
// 点亮当前标签按钮
switch (tabIndex) {
case 0:
btnDialogTab.setIcon(ImageConst.IC_TAB_DIALOG_FOCUS);
btnDialogTab.setForeground(ColorConst.TEXT_TITLE_PRIMARY);
break;
case 1:
btnContactsTab.setIcon(ImageConst.IC_TAB_CONTACTS_FOCUS);
btnContactsTab.setForeground(ColorConst.TEXT_TITLE_PRIMARY);
break;
default:
break;
}
}
/**
* 刷新用户状态
*/
public void updateUserStatus() {
setUserPicture(ImageConst.IC_USER_PICTURES[ClientService.currentUser.getPictureId()]);
lblUserNickname.setText(ClientService.currentUser.getNickname());
}
/**
* 设置用户头像
*
* @param avatarIcon
*/
public void setUserPicture(ImageIcon avatarIcon) {
ImageIcon icon = new ImageIcon(avatarIcon.getImage().getScaledInstance(userHeadSize.width, userHeadSize.height,
java.awt.Image.SCALE_SMOOTH));
lblUserPicture.setIcon(icon);
}
}
| [
"[email protected]"
]
| |
368e10774ba760c38a9c5228046e462511ccc993 | 640511db296699affb190139aaa4bc7684ac5b04 | /tracker/src/main/java/com/customer/tracker/service/EmployeeService.java | 3c0653bc90fdc41ad0eb0aa226b923002e1c33e6 | []
| no_license | ab-seth/Customer_web_tracker | 9ed445eb1dab45fb5042cd3bdc163188ee1e6e37 | 33f32aabd005dbe20fcfbef2bcb0559f4d52c897 | refs/heads/master | 2022-11-23T23:59:22.259821 | 2020-07-26T21:53:01 | 2020-07-26T21:53:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 374 | java | package com.luv2code.springboot.cruddemo.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.luv2code.springboot.cruddemo.entity.Employee;
public interface EmployeeService {
public List<Employee> findAll();
public Employee findById(int theId);
public void save(Employee theEmployee);
public void deleteById(int theid);
}
| [
"[email protected]"
]
| |
a663920df8c9e881dd015265c3a8654d2c6c0f35 | a6505156da9ec9800302c2790af6f240cfd3b68b | /viikko5/LaskinFX8/src/main/java/laskin/Sovelluslogiikka.java | 6ea2948519ecb0ee94966e38fc5ac7e6168cfe91 | []
| no_license | Jakoviz/ohtu-viikkopalautukset | 8bf24635c1fbbe78fb69d5e944b056c83dac3370 | 464ed54e823033666caf07bcf73888211ea63bf7 | refs/heads/master | 2020-09-03T23:12:16.665203 | 2019-12-14T08:15:19 | 2019-12-14T08:15:19 | 219,597,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 379 | java | package laskin;
public class Sovelluslogiikka {
private int tulos;
public void plus(int luku) {
tulos += luku;
}
public void setTulos(int tulos) {
this.tulos = tulos;
}
public void miinus(int luku) {
tulos -= luku;
}
public void nollaa() {
tulos = 0;
}
public int tulos() {
return tulos;
}
} | [
"[email protected]"
]
| |
b6c21eadd6b3db03a62963df426c9e2c515c06b0 | 40ad96ae34368d288ff2309b9f5f9b8a24bd0761 | /Java+/Spring+/Spring4+/PropertySource/src/SpringConfig.java | 1e9be4c1930f7015781adb38083bf808afa27731 | []
| no_license | Testudinate/yaal_examples | efffeca2b31eb3a845c55c58769377b89b9f381f | cb576ebb3d981ca7f1a59a2d871ef6d8e519e969 | refs/heads/master | 2020-12-25T21:12:57.271788 | 2015-11-11T20:23:27 | 2015-11-11T20:23:27 | 46,030,837 | 1 | 0 | null | 2015-11-12T05:09:42 | 2015-11-12T05:09:42 | null | UTF-8 | Java | false | false | 1,043 | java | import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySources({
@PropertySource("classpath:my.properties"),
/**
* Можно задать путь к файлу свойств через свойства JVM: -Dconf=file:${user.dir}/resources/city2.properties
* Если свойство "conf" не задано, будет использовано значение по-умолчанию.
*/
@PropertySource("${conf:file:${user.dir}/resources/city1.properties}")
})
public class SpringConfig {
/**
* To resolve ${} in @Value
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
| [
"[email protected]"
]
| |
1c9210af962923a90fd37af4f3f857f31b120b73 | cf9dc80838da21508691420940c460c55dd1fec0 | /Movie.java | ec892e08ec91bf7068cf8b803dd051a66668e3a4 | []
| no_license | stephcairns/Lab4 | 744fe76fe6a52d53ee977ac9a5d27001cffc6fa7 | f0e0ce3fa3e8cddfbf095175a716af18f2199ad0 | refs/heads/master | 2020-04-01T12:02:49.843715 | 2018-10-15T22:18:40 | 2018-10-15T22:18:40 | 153,188,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,116 | java | import java.util.List;
public class Movie
{
private String title;
private int year;
private List<String> directors;
private List<String> producers;
private List<String> actors;
public Movie(String title, int year, List<String> directors,
List<String> producers, List<String> actors)
{
this.title = title;
this.year = year;
this.directors = directors;
this.producers = producers;
this.actors = actors;
}
public List<String> getActors()
{
return actors;
}
public List<String> getDirectors()
{
return directors;
}
public List<String> getProducers()
{
return producers;
}
public String getTitle()
{
return title;
}
public int getYear()
{
return year;
}
public String toString()
{
return "Name: " + title
+ "\nYear: " + year
+ "\nDirected by: " + directors
+ "\nProduced by: " + producers
+ "\nActors: " + actors
+ "\n";
}
} | [
"[email protected]"
]
| |
5710c22b96a360398049b544f5ccb2285b6f6b4a | a128f19f6c10fc775cd14daf740a5b4e99bcd2fb | /middleheaven-domain/src/main/java/org/middleheaven/domain/criteria/IsIdenticalToOtherInstanceCriterion.java | 73a0c5cbefd5dac979d3a6fdc6c5575632a91028 | []
| no_license | HalasNet/middleheaven | c8bfa6199cb9b320b9cfd17b1f8e4961e3d35e6e | 15e3e91c338e359a96ad01dffe9d94e069070e9c | refs/heads/master | 2021-06-20T23:25:09.978612 | 2017-08-12T21:35:56 | 2017-08-12T21:37:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 590 | java | package org.middleheaven.domain.criteria;
import org.middleheaven.util.criteria.Criterion;
public class IsIdenticalToOtherInstanceCriterion implements Criterion {
private Object instance;
public IsIdenticalToOtherInstanceCriterion(Object instance) {
this.instance = instance;
}
public Object getInstance(){
return instance;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Criterion simplify() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isJunction() {
return false;
}
}
| [
"[email protected]"
]
| |
8f5e69c3b8cb07f3c627b0b76c54036c47e82d31 | 53732cb61cb3b19fae2949214c57a013019e72d1 | /payments-core/build/tmp/kapt3/stubs/release/com/stripe/android/EphemeralKeyUpdateListener.java | eb65395c1c669ea5b7f199fdb30211536455eb71 | [
"MIT"
]
| permissive | spanoop11/StripeAppstore | acf8e181a5f56c8ebea094789bfa62b2e59cb7ae | d79cb5a004cd5dd33080fc3b5fbbb5c789659eb4 | refs/heads/master | 2022-07-28T18:43:03.110334 | 2022-03-10T13:28:56 | 2022-03-10T13:28:56 | 429,658,721 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,488 | java | package com.stripe.android;
import java.lang.System;
/**
* Represents a listener for Ephemeral Key Update events.
*/
@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000 \n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\b\n\u0002\b\u0002\bf\u0018\u00002\u00020\u0001J\u0010\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u0005H&J\u0018\u0010\u0006\u001a\u00020\u00032\u0006\u0010\u0007\u001a\u00020\b2\u0006\u0010\t\u001a\u00020\u0005H&\u00a8\u0006\n"}, d2 = {"Lcom/stripe/android/EphemeralKeyUpdateListener;", "", "onKeyUpdate", "", "stripeResponseJson", "", "onKeyUpdateFailure", "responseCode", "", "message", "payments-core_release"})
public abstract interface EphemeralKeyUpdateListener {
/**
* Called when a key update request from your server comes back successfully.
*
* @param stripeResponseJson the raw JSON String returned from Stripe's servers
*/
public abstract void onKeyUpdate(@org.jetbrains.annotations.NotNull()
java.lang.String stripeResponseJson);
/**
* Called when a key update request from your server comes back with an error.
*
* @param responseCode the error code returned from Stripe's servers
* @param message the error message returned from Stripe's servers
*/
public abstract void onKeyUpdateFailure(int responseCode, @org.jetbrains.annotations.NotNull()
java.lang.String message);
} | [
"[email protected]"
]
| |
92b877e05d79e51831479de9788968b9f8a4ab5e | 068faf74690a2364c64560908f48fd00ae990065 | /wukong-common/src/main/java/com/wukong/common/utils/JDPhone.java | 64fbf4378c70f5e2a0471e4e2a86c967fe68bd53 | []
| no_license | mambo-wang/WuKong | 11293e5a0e074f25bb6ac59f741fddf441013cbd | 65134d99ae5ef25b35cff3e238eb86e5702a88f1 | refs/heads/master | 2022-12-12T10:21:15.248133 | 2021-05-19T03:04:02 | 2021-05-19T03:04:02 | 245,640,296 | 4 | 1 | null | 2022-12-06T00:34:40 | 2020-03-07T13:44:57 | Java | UTF-8 | Java | false | false | 4,873 | java | package com.wukong.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wukong.common.model.GoodsVO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.concurrent.*;
public class JDPhone {
//创建线程池
static ExecutorService threadPool = Executors.newFixedThreadPool(20);
//创建原生阻塞队列 队列最大容量为1000
static BlockingQueue<String> queue=new ArrayBlockingQueue<String>(1000);
public static void main(String[] args) throws IOException, InterruptedException {
//监视队列大小的线程
threadPool.execute(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获得队列当前的大小
int size = queue.size();
System.out.println("当前队列中有"+size+"个pid");
}
}
});
//开启10个线程去解析手机列表页获得的pids
for (int i = 1; i <=10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
while (true){
String pid=null;
try {
//从队列中取出pid
pid = queue.take();
GoodsVO product = parsePid(pid);
System.out.println(product);
//存入数据库
} catch (Exception e) {
e.printStackTrace();
try {
//出现异常则放回队列
queue.put(pid);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
});
}
//分页查找手机数据 共100页
for (int i = 1; i <=100 ; i++) {
//京东分页page为 1 3 5 7 ..... 对应第一页 第二页....
String url="https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&page="+(2*i-1);
String html = HttpClientUtils.doGet(url);
parseIndex(html);
}
}
//解析手机列表页
private static void parseIndex(String html) throws InterruptedException {
Document document = Jsoup.parse(html);
//手机列表
Elements elements = document.select("#J_goodsList>ul>li");
if(elements!=null||elements.size()!=0){
for (Element element : elements) {
//获得每个li的pid
String pid = element.attr("data-pid");
//将pid放入队列中
queue.put(pid);
}
}
}
//解析每个手机的页面 获得某个手机的详细数据
private static GoodsVO parsePid(String pid) throws IOException {
//拼接url 进入手机详情页
String productUrl="https://item.jd.com/"+pid+".html";
String productHtml = HttpClientUtils.doGet(productUrl);
Document document = Jsoup.parse(productHtml);
GoodsVO product = new GoodsVO();
//获得手机标题
if(document.select("div.sku-name").size()>0){
String title = document.select("div.sku-name").get(0).text();
product.setTitle(title);
}
String url = document.select("#spec-n1 img").attr("src");
//获得手机品牌
String brand = document.select("#parameter-brand li").attr("title");
//获得手机名称
String pname = document.select("[class=parameter2 p-parameter-list] li:first-child").attr("title");
product.setName(brand + " " + pname);
product.setTitle(pname);
//拼接价格页面url 经过测试 返回Json数据 jd对IP进行了限制,加入pduid为随机数,是为了可以获取更多数据,但是依然只能爬取部分
String priceUrl="https://p.3.cn/prices/mgets?pduid="+Math.random()+"&skuIds=J_"+pid;
String priceJson = HttpClientUtils.doGet(priceUrl);
System.out.println(priceJson);
JSONArray list = JSON.parseArray(priceJson);
String price = list.getJSONObject(0).getString("p");
product.setPrice(Double.valueOf(price));
product.setDeleted("n");
product.setImage(url);
product.setDetail(pname);
return product;
}
} | [
"[email protected]"
]
| |
40944583682aa5ba7827bdf19637211bfe1d9ec1 | 8889a4676a56809d92a3e2300da9072a8b1ea481 | /src/test/java/com/loyaltyprimemultipartnerapp/cucumber/steps/api/TransactionRedemptionLopSteps.java | 9daf77b057ba8b87bb62fea7ad7d847f91252015 | []
| no_license | gautam518/serenity | 4bc5e0161a84a4400cb4db6f452ab95cb572dc66 | 92b735cb31cb1e59c40080f5e93186111ba02f38 | refs/heads/master | 2023-08-03T08:19:12.478388 | 2021-09-09T10:26:27 | 2021-09-09T10:26:27 | 404,586,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,509 | java | package com.loyaltyprimemultipartnerapp.cucumber.steps.api;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.junit.Assert;
import com.loyaltyprimemultipartnerapp.utlis.AIPsJsonBody;
import com.loyaltyprimemultipartnerapp.utlis.ExcelReader;
import com.loyaltyprimemultipartnerapp.utlis.ReuseableSpecifications;
import com.loyaltyprimemultipartnerapp.utlis.TestUtils;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import net.serenitybdd.rest.SerenityRest;
public class TransactionRedemptionLopSteps {
private String clientKey;// Source key
private String receiptId;
private String debitorId;
private String description;
private String amount;
private Response response = null; // Response
private Response responseSM = null;
private Response responseTX = null;
HttpHeaders headers;
String strapiBody;
private String TrxId;
private String TrxDate;
public static String getsourceKey() {
return _sourceKey;
}
private static String _sourceKey;
public static String getTrxDate() {return _TrxDate;}
private static String _TrxDate;
public static String getRcptId() {return _RcptId;}
private static String _RcptId;
public Properties LoadProperties() {
try {
InputStream inStream = getClass().getClassLoader().getResourceAsStream("config.properties");
Properties prop = new Properties();
prop.load(inStream);
return prop;
} catch (Exception e) {
System.out.println("File not found exception thrown for config.properties file.");
return null;
}
}
@Given("Member wants to enrollment on PCV{int} for redemption")
public void member_wants_to_enrollment_on_PCV_for_redemption(Integer int1) {
clientKey = LoadProperties().getProperty("enkey") + "_SRC" + TestUtils.getRandomValue();
_sourceKey = clientKey;
}
@When("Member performs enrollment on PCV{int} for redemption")
public void member_performs_enrollment_on_PCV_for_redemption(Integer int1) {
String strSince = TestUtils.getDateTime();
String strType = LoadProperties().getProperty("membertype");
String strTier = LoadProperties().getProperty("tier");
String strPromoterId = LoadProperties().getProperty("promoterId");
String strAlternateIds = LoadProperties().getProperty("enkey") + "_SRC_AltId" +TestUtils.getRandomValue()+ TestUtils.getRandomNumber();
String strUserId = clientKey;
String strPrefix = LoadProperties().getProperty("prefix");
String strFirstName = LoadProperties().getProperty("firstname");
String strBirth = LoadProperties().getProperty("birth");
String strEmail = LoadProperties().getProperty("email");
String strPhone = LoadProperties().getProperty("phone");
String strAddress1 = LoadProperties().getProperty("address1");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.EnrollmentAPIBody(strSince, strType, "MUR", "ACTIVE", "Test", "", strTier, clientKey,
strFirstName, strPrefix, strPhone, strAddress1, strEmail, strUserId, strAlternateIds, strPromoterId, "",
strBirth);
responseSM = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/memberships");
}
@Then("Member should be created in pcv{int} for redemption with statuscode {int}")
public void member_should_be_created_in_pcv_for_redemption_with_statuscode(Integer int1, Integer int2) {
Assert.assertEquals(HttpStatus.SC_OK, responseSM.getStatusCode());
JsonPath jsonPathEvaluator = responseSM.jsonPath();
Boolean strSuccess = jsonPathEvaluator.get("success");
Assert.assertEquals(true, strSuccess);
}
@When("The member performs transaction on PCV{int} for redemption")
public void the_member_performs_transaction_on_PCV_for_redemption(Integer int1) throws InterruptedException {
String strTxKey = "TXRED";
TrxId = strTxKey + "_" + TestUtils.getRandomValue();
TrxDate = TestUtils.getDateTime();
String price = "20";
String quantity = "1";
String channelkey = "";
String productKey = "";
String productKey2 ="";
String channelKey2 = "";
String productKey3 ="";
String channelKey3 = "";
// get dymanically the productid and channelKey here
Response responseProductData;
responseProductData = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).log().all()
.when().get("/api/v10/promos/product/data");
JsonPath jsonPathEval = responseProductData.jsonPath();
String _getProductKey = jsonPathEval.get("data[0].key");
String _getChannelKey = jsonPathEval.get("data[0].channelKey");
String _getProductKey2 = jsonPathEval.get("data[1].key");
String _getChannelKey2 = jsonPathEval.get("data[1].channelKey");
String _getProductKey3 = jsonPathEval.get("data[2].key");
String _getChannelKey3 = jsonPathEval.get("data[2].channelKey");
channelkey = _getChannelKey;
productKey = _getProductKey;
channelKey2 = _getChannelKey2;
productKey2 = _getProductKey2;
channelKey3 = _getChannelKey3;
productKey3 = _getProductKey3;
clientKey = getsourceKey();// get the key value here from the first class
String partnerId=LoadProperties().getProperty("partnerId");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.TransactionAPIBody(TrxId, clientKey, TrxDate,partnerId, price, quantity, productKey, channelkey,
productKey2, channelKey2, productKey3, channelKey3);
responseTX = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/tx");
System.out.println("Transaction added for redemption:" + responseTX.asString());
Thread.sleep(2000);
}
@Then("Then transaction should be successful with status code {int}")
public void then_transaction_should_be_successful_with_status_code(Integer int1) {
Assert.assertEquals(HttpStatus.SC_OK, responseTX.getStatusCode());
System.out.println("Transaction Redeption:" + responseTX.asString());
}
@Given("Member call the point redemption")
public void member_call_the_point_redemption() {
clientKey = getsourceKey();
System.out.println("The client ky:" + clientKey);
}
@When("The member perfom point redemption with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_with_details_MembereTrx_and_rownumber(Integer rownumber)
throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
_TrxDate=TrxDate;
receiptId = testDataRdeem.get(rownumber).get("ReceiptId") + "_" + TestUtils.getRandomValue();
_RcptId=receiptId;
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(100);
}
@Then("Member should able to do point redemption successfully with status code {int}")
public void member_should_able_to_do_point_redemption_successfully_with_status_code(Integer statuscode) {
Assert.assertEquals(statuscode.intValue(), response.getStatusCode());
JsonPath jsonPathEvaluator = response.jsonPath();
String getCleientId = jsonPathEvaluator.get("data.membershipKey");
System.out.println("clientID received from Response " + getCleientId);
Assert.assertEquals(clientKey, getCleientId);
boolean getStatus = jsonPathEvaluator.get("success");
Assert.assertEquals(getStatus, true);
System.out.println("TxId received from Response " + getStatus);
}
@Then("The redemption detail should be displayed in member account statement")
public void the_redemption_detail_should_be_displayed_in_member_account_statement() {
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).log().all().when()
.get("/api/v10/deposits/" + clientKey + "/statement?type=BONUS");
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode());
JsonPath jsonPathEvaluator = response.jsonPath();
boolean getStatus = jsonPathEvaluator.get("success");
Assert.assertEquals(getStatus, true);
debitorId = LoadProperties().getProperty("debitorId");
String strReciptId=receiptId+"_"+debitorId;
// match the redemption id here
String getAmountRedem = null;
List aList = response.jsonPath().getList("data.bookings.receiptId.uniqueId");
for (int i = 0; i < aList.size(); i++) {
System.out.print(aList.get(i));
if (aList.get(i).equals(strReciptId)) {
getAmountRedem = aList.get(i).toString();
System.out.println("receiptId value" + getAmountRedem);
}
}
Assert.assertEquals(getAmountRedem,strReciptId);
}
@When("The member perfom point redemption with details receiptid{string} date{string} debitorId{string} amount{int} and description{string}")
public void the_member_perfom_point_redemption_with_details_receiptid_date_debitorId_amount_and_description(
String receiptid, String strdate, String debitorId, Integer amount, String description) {
String receiptId = receiptid+"_" + TestUtils.getRandomValue();
String date=strdate;
clientKey = getsourceKey();
debitorId = LoadProperties().getProperty("debitorId");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, date,debitorId, amount.toString(), description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
}
@Given("Member call the point redemption with blank receiptid")
public void member_call_the_point_redemption_with_blank_receiptid()
throws InvalidFormatException, IOException, InterruptedException {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption when the receiptid is passed as blank in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_when_the_receiptid_is_passed_as_blank_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = "";
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Then("Member should not able to do point redemption with status code {int}")
public void member_should_not_able_to_do_point_redemption_with_status_code(Integer statuscode) {
Assert.assertEquals(statuscode.intValue(), response.getStatusCode());
/*JsonPath jsonPathEvaluator = response.jsonPath();
boolean getStatus = jsonPathEvaluator.get("success");
Assert.assertEquals(getStatus, false);
System.out.println("Response of API " + getStatus);*/
}
@Given("Member call the point redemption for any value of receiptid")
public void member_call_the_point_redemption_for_any_value_of_receiptid() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perform point redemption when any value of receiptid is passed in the system with details MembereTrx and rownumber {int}")
public void the_member_perform_point_redemption_when_any_value_of_receiptid_is_passed_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId") + "_" + TestUtils.getRandomValue();
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Then("Member should able to do point redemption with status code {int}")
public void member_should_able_to_do_point_redemption_with_status_code(Integer statuscode) {
Assert.assertEquals(statuscode.intValue(), response.getStatusCode());
JsonPath jsonPathEvaluator = response.jsonPath();
boolean getStatus = jsonPathEvaluator.get("success");
Assert.assertEquals(getStatus, true);
System.out.println("Response of API " + getStatus);
}
@Given("Member call the point redemption without receiptid")
public void member_call_the_point_redemption_without_receiptid() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perform point redemption without receiptid in the system with details MembereTrx and rownumber {int}")
public void the_member_perform_point_redemption_without_receiptid_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = "without";
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Given("Member call the transaction redemption when type is not passed")
public void member_call_the_transaction_redemption_when_type_is_not_passed(){
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption without type in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_without_type_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(10000);
}
@Given("Member call the point redemption with non numeric value")
public void member_call_the_point_redemption_with_non_numeric_value() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perform point redemption when amount is passed as alphabet in the system with details MembereTrx and rownumber {int}")
public void the_member_perform_point_redemption_when_amount_is_passed_as_alphabet_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = "baab";
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(10000);
}
@Given("Member call the point redemption when amount is zero")
public void member_call_the_point_redemption_when_amount_is_zero(){
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption with amount as zero in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_with_amount_as_zero_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = "0";
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(10000);
}
@Given("Member call the point redemption without amount")
public void member_call_the_point_redemption_without_amount() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption when amount is not passed in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_when_amount_is_not_passed_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = "without";
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(10000);
}
@Given("Member call the point redemption when debitorId is blank")
public void member_call_the_point_redemption_when_debitorId_is_blank(){
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption when debitorId is passed as blank in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_when_debitorId_is_passed_as_blank_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId")+"_"+TestUtils.getRandomValue();
debitorId = "";
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(10000);
}
@Given("Member call the point redemption without debitorId")
public void member_call_the_point_redemption_without_debitorId() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perform point reversal when debitorId is not passed in the system with details MembereTrx and rownumber {int}")
public void the_member_perform_point_reversal_when_debitorId_is_not_passed_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = "Rex"+"X_"+TestUtils.getRandomAlphaNumbericValue()+TestUtils.getRandomNumber();
debitorId ="without";
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Given("Member call the point redemption when date is blank")
public void member_call_the_point_redemption_when_date_is_blank(){
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption when date is blank in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_when_date_is_blank_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
TrxDate = "";
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
clientKey = getsourceKey();
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Given("Member call the point redemption with invalid date")
public void member_call_the_point_redemption_with_invalid_date() {
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption with invalid date in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_with_invalid_date_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
TrxDate = "25-02-2021";
receiptId = testDataRdeem.get(rownumber).get("ReceiptId");
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
clientKey = getsourceKey();
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=BONUS");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
@Given("Member call the point redemption with invalid type")
public void member_call_the_point_redemption_with_invalid_type(){
clientKey = getsourceKey();
System.out.println("Member key :" + clientKey);
}
@When("The member perfom point redemption when type is passed as volume in the system with details MembereTrx and rownumber {int}")
public void the_member_perfom_point_redemption_when_type_is_passed_as_volume_in_the_system_with_details_MembereTrx_and_rownumber(
Integer rownumber) throws InvalidFormatException, IOException, InterruptedException {
ExcelReader reader = new ExcelReader();
List<Map<String, String>> testDataRdeem = reader.getData("src/test/resources/testdata/MemTransaction.xlsx",
"RedeemTx");
clientKey = getsourceKey();
TrxDate = TestUtils.getDateTime();
receiptId = testDataRdeem.get(rownumber).get("ReceiptId")+"E_"+TestUtils.getRandomNumber();
debitorId = LoadProperties().getProperty("debitorId");
amount = testDataRdeem.get(rownumber).get("Amount");
description = testDataRdeem.get(rownumber).get("Description");
AIPsJsonBody apibody = new AIPsJsonBody();
strapiBody = apibody.RedeeemAPIBody(receiptId, TrxDate, debitorId, amount, description);
response = SerenityRest.given().spec(ReuseableSpecifications.getGenericRequestSpec()).body(strapiBody).log()
.all().when().post("/api/v10/deposits/" + clientKey + "/redeem?type=VOLUME");
System.out.println("Member redemption response:" + response.asString());
Thread.sleep(1000);
}
}
| [
"[email protected]"
]
| |
c65f8ed2e82a2200d465e6b0347888bf8b2ccb81 | 5b038080c6d7e84fdafec8a44c303d4986932f82 | /src/main/java/com/elementars/eclient/mixin/mixins/MixinBlockFire.java | 9971dc458283a45a693880643f34d60ddcce0ee6 | []
| no_license | Droid-D3V/XULU_Buildable_SRC | 9739a41a0daaef7a4d89f3b89379d0540849f856 | e5baa6f22730c79cbff969cb322d938d2168eb20 | refs/heads/master | 2023-08-28T09:10:14.384563 | 2021-11-05T16:43:39 | 2021-11-05T16:43:39 | 417,858,652 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,153 | java | package com.elementars.eclient.mixin.mixins;
import com.elementars.eclient.Xulu;
import com.elementars.eclient.module.misc.Avoid;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* @author Elementars
* @version Xulu v1.2.0
* @since 7/24/2020 - 9:49 PM
*/
@Mixin(BlockFire.class)
public class MixinBlockFire {
@Inject(method = "getCollisionBoundingBox", at = @At("HEAD"), cancellable = true)
private void getCollision(IBlockState blockState, IBlockAccess worldIn, BlockPos pos, CallbackInfoReturnable<AxisAlignedBB> cir) {
if (Xulu.MODULE_MANAGER.getModule(Avoid.class).isToggled() && Avoid.fire.getValue()) {
cir.setReturnValue(Block.FULL_BLOCK_AABB);
cir.cancel();
}
}
}
| [
"[email protected]"
]
| |
b5586a3bb657a1a73f9fe4ca20c8da1644b7992b | f7a8c7ac7b0b560ac3f295288957169c86c0a9b6 | /lib_title/build/generated/not_namespaced_r_class_sources/debug/generateDebugRFile/out/androidx/drawerlayout/R.java | 1c4dbff7d48a3e8a937d0ee756d4eae1b32e47b1 | []
| no_license | HeroLBJ/DaChengCar | 93027d7a29f12f9b1fa0e2bc5550260962e41c92 | b3172f632351a6fcac397273b1553719b2202b36 | refs/heads/master | 2020-05-07T13:43:27.036761 | 2019-04-29T06:08:18 | 2019-04-29T06:08:18 | 180,559,875 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,666 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.drawerlayout;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static int alpha = 0x7f040028;
public static int font = 0x7f040083;
public static int fontProviderAuthority = 0x7f040085;
public static int fontProviderCerts = 0x7f040086;
public static int fontProviderFetchStrategy = 0x7f040087;
public static int fontProviderFetchTimeout = 0x7f040088;
public static int fontProviderPackage = 0x7f040089;
public static int fontProviderQuery = 0x7f04008a;
public static int fontStyle = 0x7f04008b;
public static int fontVariationSettings = 0x7f04008c;
public static int fontWeight = 0x7f04008d;
public static int ttcIndex = 0x7f040126;
}
public static final class color {
private color() {}
public static int notification_action_color_filter = 0x7f06003e;
public static int notification_icon_bg_color = 0x7f06003f;
public static int ripple_material_light = 0x7f060049;
public static int secondary_text_default_material_light = 0x7f06004b;
}
public static final class dimen {
private dimen() {}
public static int compat_button_inset_horizontal_material = 0x7f08004c;
public static int compat_button_inset_vertical_material = 0x7f08004d;
public static int compat_button_padding_horizontal_material = 0x7f08004e;
public static int compat_button_padding_vertical_material = 0x7f08004f;
public static int compat_control_corner_material = 0x7f080050;
public static int compat_notification_large_icon_max_height = 0x7f080051;
public static int compat_notification_large_icon_max_width = 0x7f080052;
public static int notification_action_icon_size = 0x7f08005c;
public static int notification_action_text_size = 0x7f08005d;
public static int notification_big_circle_margin = 0x7f08005e;
public static int notification_content_margin_start = 0x7f08005f;
public static int notification_large_icon_height = 0x7f080060;
public static int notification_large_icon_width = 0x7f080061;
public static int notification_main_column_padding_top = 0x7f080062;
public static int notification_media_narrow_margin = 0x7f080063;
public static int notification_right_icon_size = 0x7f080064;
public static int notification_right_side_padding_top = 0x7f080065;
public static int notification_small_icon_background_padding = 0x7f080066;
public static int notification_small_icon_size_as_large = 0x7f080067;
public static int notification_subtext_size = 0x7f080068;
public static int notification_top_pad = 0x7f080069;
public static int notification_top_pad_large_text = 0x7f08006a;
}
public static final class drawable {
private drawable() {}
public static int notification_action_background = 0x7f090060;
public static int notification_bg = 0x7f090061;
public static int notification_bg_low = 0x7f090062;
public static int notification_bg_low_normal = 0x7f090063;
public static int notification_bg_low_pressed = 0x7f090064;
public static int notification_bg_normal = 0x7f090065;
public static int notification_bg_normal_pressed = 0x7f090066;
public static int notification_icon_background = 0x7f090067;
public static int notification_template_icon_bg = 0x7f090068;
public static int notification_template_icon_low_bg = 0x7f090069;
public static int notification_tile_bg = 0x7f09006a;
public static int notify_panel_notification_icon_bg = 0x7f09006b;
}
public static final class id {
private id() {}
public static int action_container = 0x7f0c0008;
public static int action_divider = 0x7f0c000a;
public static int action_image = 0x7f0c000b;
public static int action_text = 0x7f0c0011;
public static int actions = 0x7f0c0012;
public static int async = 0x7f0c0016;
public static int blocking = 0x7f0c0017;
public static int chronometer = 0x7f0c001b;
public static int forever = 0x7f0c0029;
public static int icon = 0x7f0c002c;
public static int icon_group = 0x7f0c002d;
public static int info = 0x7f0c0030;
public static int italic = 0x7f0c0031;
public static int line1 = 0x7f0c0034;
public static int line3 = 0x7f0c0035;
public static int normal = 0x7f0c003b;
public static int notification_background = 0x7f0c003c;
public static int notification_main_column = 0x7f0c003d;
public static int notification_main_column_container = 0x7f0c003e;
public static int right_icon = 0x7f0c0044;
public static int right_side = 0x7f0c0045;
public static int tag_transition_group = 0x7f0c0060;
public static int tag_unhandled_key_event_manager = 0x7f0c0061;
public static int tag_unhandled_key_listeners = 0x7f0c0062;
public static int text = 0x7f0c0063;
public static int text2 = 0x7f0c0064;
public static int time = 0x7f0c0068;
public static int title = 0x7f0c0069;
}
public static final class integer {
private integer() {}
public static int status_bar_notification_info_maxnum = 0x7f0d0005;
}
public static final class layout {
private layout() {}
public static int notification_action = 0x7f0f001d;
public static int notification_action_tombstone = 0x7f0f001e;
public static int notification_template_custom_big = 0x7f0f001f;
public static int notification_template_icon_group = 0x7f0f0020;
public static int notification_template_part_chronometer = 0x7f0f0021;
public static int notification_template_part_time = 0x7f0f0022;
}
public static final class string {
private string() {}
public static int status_bar_notification_info_overflow = 0x7f15002a;
}
public static final class style {
private style() {}
public static int TextAppearance_Compat_Notification = 0x7f1600ec;
public static int TextAppearance_Compat_Notification_Info = 0x7f1600ed;
public static int TextAppearance_Compat_Notification_Line2 = 0x7f1600ee;
public static int TextAppearance_Compat_Notification_Time = 0x7f1600ef;
public static int TextAppearance_Compat_Notification_Title = 0x7f1600f0;
public static int Widget_Compat_NotificationActionContainer = 0x7f160158;
public static int Widget_Compat_NotificationActionText = 0x7f160159;
}
public static final class styleable {
private styleable() {}
public static int[] ColorStateListItem = { 0x7f040028, 0x101031f, 0x10101a5 };
public static int ColorStateListItem_alpha = 0;
public static int ColorStateListItem_android_alpha = 1;
public static int ColorStateListItem_android_color = 2;
public static int[] FontFamily = { 0x7f040085, 0x7f040086, 0x7f040087, 0x7f040088, 0x7f040089, 0x7f04008a };
public static int FontFamily_fontProviderAuthority = 0;
public static int FontFamily_fontProviderCerts = 1;
public static int FontFamily_fontProviderFetchStrategy = 2;
public static int FontFamily_fontProviderFetchTimeout = 3;
public static int FontFamily_fontProviderPackage = 4;
public static int FontFamily_fontProviderQuery = 5;
public static int[] FontFamilyFont = { 0x1010532, 0x101053f, 0x1010570, 0x1010533, 0x101056f, 0x7f040083, 0x7f04008b, 0x7f04008c, 0x7f04008d, 0x7f040126 };
public static int FontFamilyFont_android_font = 0;
public static int FontFamilyFont_android_fontStyle = 1;
public static int FontFamilyFont_android_fontVariationSettings = 2;
public static int FontFamilyFont_android_fontWeight = 3;
public static int FontFamilyFont_android_ttcIndex = 4;
public static int FontFamilyFont_font = 5;
public static int FontFamilyFont_fontStyle = 6;
public static int FontFamilyFont_fontVariationSettings = 7;
public static int FontFamilyFont_fontWeight = 8;
public static int FontFamilyFont_ttcIndex = 9;
public static int[] GradientColor = { 0x101020b, 0x10101a2, 0x10101a3, 0x101019e, 0x1010512, 0x1010513, 0x10101a4, 0x101019d, 0x1010510, 0x1010511, 0x1010201, 0x10101a1 };
public static int GradientColor_android_centerColor = 0;
public static int GradientColor_android_centerX = 1;
public static int GradientColor_android_centerY = 2;
public static int GradientColor_android_endColor = 3;
public static int GradientColor_android_endX = 4;
public static int GradientColor_android_endY = 5;
public static int GradientColor_android_gradientRadius = 6;
public static int GradientColor_android_startColor = 7;
public static int GradientColor_android_startX = 8;
public static int GradientColor_android_startY = 9;
public static int GradientColor_android_tileMode = 10;
public static int GradientColor_android_type = 11;
public static int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static int GradientColorItem_android_color = 0;
public static int GradientColorItem_android_offset = 1;
}
}
| [
"[email protected]"
]
| |
730303357f373518cfdd82a0305222ca053530bd | 828111a9183c38e87ba650b1fb09a2b2c98f6195 | /Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/saml/extraction/AttributeTypeHelper.java | 0afcefc0cc08e331f649dec42090824ae465aed1 | []
| no_license | sahilshaikh89/CONNECT-Legacy | 6a7f080087bd17420e0716305a1231a7825e7d8d | 9b3b820bd151be403ba5e165dbf560061ccc5d6f | refs/heads/master | 2021-01-19T10:12:21.372914 | 2012-02-20T20:14:26 | 2012-02-20T20:14:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,825 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.hhs.fha.nhinc.saml.extraction;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import org.apache.xerces.dom.ElementNSImpl;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.AttributeStatementType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.AttributeType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.ConditionsType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.EvidenceType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.AuthnStatementType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.AuthzDecisionStatementType;
import com.sun.xml.wss.saml.internal.saml20.jaxb20.NameIDType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.CeType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.PersonNameType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthnStatementType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceAssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceConditionsType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlSignatureKeyInfoType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlSignatureType;
import gov.hhs.fha.nhinc.common.nhinccommon.UserType;
/**
*
* @author mweaver
*/
public class AttributeTypeHelper {
private static Log log = LogFactory.getLog(AttributeTypeHelper.class);
private static final String EMPTY_STRING = "";
/**
* This method takes an attribute and extracts the string value of the
* attribute. If the attribute has multiple values, then it concatenates
* all of the values.
*
* @param attrib The attribute containing the string value.
* @return The string value (or if there are multiple values, the concatenated string value.)
*/
public static String extractAttributeValueString(AttributeType attrib) {
// this method was rewritten for GATEWAY-426
StringBuffer strBuf = new StringBuffer();
if (attrib != null) {
List attrVals = attrib.getAttributeValue();
for (Object o : attrVals) {
if (o instanceof org.w3c.dom.Element) {
org.w3c.dom.Element elem = (org.w3c.dom.Element) o;
strBuf.append(elem.getTextContent());
// we break here because per the nhin specification, there should only be one attribute value.
break;
} else if (o instanceof String) {
strBuf.append((String) o + " ");
// we DO NOT break here despite the nhin specification because the previous algorithm for handling these Strings handled multiple values. Until I understand
// why the string values are treated differently I am not going to change this logic.
}
}
}
return strBuf.toString().trim();
}
/**
* This method takes an attribute and extracts the base64Encoded value from the first
* attribute value.
*
* @param attrib The attribute containing the string value.
* @return The string value (or if there are multiple values, the concatenated string value.)
*/
public static byte[] extractFirstAttributeValueBase64Binary(AttributeType attrib) {
byte[] retValue = null;
List attrVals = attrib.getAttributeValue();
if ((attrVals != null) &&
(attrVals.size() > 0)) {
if (attrVals.get(0) instanceof byte[]) {
retValue = (byte[]) attrVals.get(0);
}
}
return retValue;
}
/**
* The value of the UserName attribute is assumed to be a user's name in
* plain text. The name parts are extracted in this method as the first
* word constitutes the first name, the last word constitutes the last name
* and all other text in between these words constitute the middle name.
* @param attrib The Attribute that has the user name as its value
* @param assertOut The Assertion element being written to
*/
public static void extractNameParts(AttributeType attrib, AssertionType assertOut) {
log.debug("Entering SamlTokenExtractor.extractNameParts...");
// Assumption is that before the 1st space reflects the first name,
// after the last space is the last name, anything between is the middle name
List attrVals = attrib.getAttributeValue();
if ((attrVals != null) &&
(attrVals.size() >= 1)) {
PersonNameType personName = assertOut.getUserInfo().getPersonName();
// Although SAML allows for multiple attribute values, the NHIN Specification
// states that for a name there will be one attribute value. So we will
// only look at the first one. If there are more, the first is the only one
// that will be used.
//-----------------------------------------------------------------------------
String completeName = extractAttributeValueString(attrib);
personName.setFullName(completeName);
log.debug("Assertion.userInfo.personName.FullName = " + completeName);
String[] nameTokens = completeName.split("\\s");
ArrayList<String> nameParts = new ArrayList<String>();
//remove blank tokens
for (String tok : nameTokens) {
if (tok.trim() != null && tok.trim().length() > 0) {
nameParts.add(tok);
}
}
if (nameParts.size() > 0) {
if (!nameParts.get(0).isEmpty()) {
personName.setGivenName(nameParts.get(0));
nameParts.remove(0);
log.debug("Assertion.userInfo.personName.givenName = " + personName.getGivenName());
}
}
if (nameParts.size() > 0) {
if (!nameParts.get(nameParts.size() - 1).isEmpty()) {
personName.setFamilyName(nameParts.get(nameParts.size() - 1));
nameParts.remove(nameParts.size() - 1);
log.debug("Assertion.userInfo.personName.familyName = " + personName.getFamilyName());
}
}
if (nameParts.size() > 0) {
StringBuffer midName = new StringBuffer();
for (String name : nameParts) {
midName.append(name + " ");
}
// take off last blank character
midName.setLength(midName.length() - 1);
personName.setSecondNameOrInitials(midName.toString());
log.debug("Assertion.userInfo.personName.secondNameOrInitials = " + personName.getSecondNameOrInitials());
}
} else {
log.error("User Name attribute is empty: " + attrVals);
}
log.debug("SamlTokenExtractor.extractNameParts() -- End");
}
/**
* The value of the UserRole and PurposeOfUse attributes are formatted
* according to the specifications of an nhin:CodedElement. This method
* parses that expected structure to obtain the code, codeSystem,
* codeSystemName, and the displayName attributes of that element.
* @param attrib The Attribute that has the UserRole or PurposeOfUse as its
* value
* @param assertOut The Assertion element being written to
* @param codeId Identifies which coded element this is parsing
*/
public static CeType extractNhinCodedElement(AttributeType attrib, String codeId) {
log.debug("Entering SamlTokenExtractor.extractNhinCodedElement...");
CeType ce = new CeType();
ce.setCode(EMPTY_STRING);
ce.setCodeSystem(EMPTY_STRING);
ce.setCodeSystemName(EMPTY_STRING);
ce.setDisplayName(EMPTY_STRING);
List attrVals = attrib.getAttributeValue();
//log.debug("extractNhinCodedElement: " + attrib.getName() + " has " + attrVals.size() + " values");
if ((attrVals != null) &&
(attrVals.size() > 0)) {
log.debug("AttributeValue is: " + attrVals.get(0).getClass());
// According to the NHIN specifications - there should be exactly one value.
// If there is more than one. We will take only the first one.
//---------------------------------------------------------------------------
NodeList nodelist = null;
if (attrVals.get(0) instanceof ElementNSImpl) {
ElementNSImpl elem = (ElementNSImpl) attrVals.get(0);
nodelist = elem.getChildNodes();
} else {
log.error("The value for the " + codeId + " attribute is a: " + attrVals.get(0).getClass() + " expected a ElementNSImpl");
}
if ((nodelist != null) &&
(nodelist.getLength() > 0)) {
int numNodes = nodelist.getLength();
for (int idx = 0; idx < numNodes; idx++) {
if (nodelist.item(idx) instanceof Node) {
//log.debug("Processing index:" + idx + " node as " + nodelist.item(idx).getNodeName());
Node node = (Node) nodelist.item(idx);
NamedNodeMap attrMap = node.getAttributes();
if ((attrMap != null) &&
(attrMap.getLength() > 0)) {
int numMapNodes = attrMap.getLength();
for (int attrIdx = 0; attrIdx < numMapNodes; attrIdx++) {
//log.debug("Processing attribute index:" + attrIdx + " as " + attrMap.item(attrIdx));
Node attrNode = attrMap.item(attrIdx);
if ((attrNode != null) &&
(attrNode.getNodeName() != null) &&
(!attrNode.getNodeName().isEmpty())) {
if (attrNode.getNodeName().equalsIgnoreCase(NhincConstants.CE_CODE_ID)) {
ce.setCode(attrNode.getNodeValue());
log.debug(codeId + ": ce.Code = " + ce.getCode());
}
if (attrNode.getNodeName().equalsIgnoreCase(NhincConstants.CE_CODESYS_ID)) {
ce.setCodeSystem(attrNode.getNodeValue());
log.debug(codeId + ": ce.CodeSystem = " + ce.getCodeSystem());
}
if (attrNode.getNodeName().equalsIgnoreCase(NhincConstants.CE_CODESYSNAME_ID)) {
ce.setCodeSystemName(attrNode.getNodeValue());
log.debug(codeId + ": ce.CodeSystemName = " + ce.getCodeSystemName());
}
if (attrNode.getNodeName().equalsIgnoreCase(NhincConstants.CE_DISPLAYNAME_ID)) {
ce.setDisplayName(attrNode.getNodeValue());
log.debug(codeId + ": ce.DisplayName = " + ce.getDisplayName());
}
} else {
log.debug("Attribute name can not be processed");
}
} // for (int attrIdx = 0; attrIdx < numMapNodes; attrIdx++) {
} else {
log.debug("Attribute map is null");
}
} else {
log.debug("Expected AttributeValue to have a Node child");
}
} // for (int idx = 0; idx < numNodes; idx++) {
} else {
log.error("The AttributeValue for " + codeId + " should have a Child Node");
}
} else {
log.error("Attributes for " + codeId + " are invalid: " + attrVals);
}
log.debug("Exiting SamlTokenExtractor.extractNhinCodedElement...");
return ce;
}
}
| [
"[email protected]"
]
| |
4594013e669583fe4af35f575567ba590add1226 | fe8f32dee394f1cfb8b48c284b22f8e7e93da25b | /3/CarType.java | eb53f7db3695d3a2b26f003e26191081af0145e2 | []
| no_license | Nirakar80/Java-Programming-2 | a6b10ede5fc249c224be4d7f778933de78b64b81 | 5b009b23420d1c72939025e64d152b68cf1229ad | refs/heads/master | 2022-05-03T22:28:50.336006 | 2019-10-21T18:27:32 | 2019-10-21T18:27:32 | 159,383,471 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 65 | java |
public enum CarType
{
HONDA, TOYOTA, PORSCHE, JAGUAR
}
| [
"[email protected]"
]
| |
74c4be6aea168886d4feecb41971ac8e0bfaa746 | 218344fe7b7d0abb0c5fb06837e07acfb0d6fbcc | /Algorithms/Graphs/Bfs.java | ff5b1847e6e28879454c9641de15f7487ad6174b | []
| no_license | AkashSalunkhe-eng/Data-Structures-And-Algorithms | 9c348168d411b60c5f16c13fe18dc1675f50a2c3 | 0f86e44d16edd76f0f85e343792f6b5b1643117c | refs/heads/main | 2023-09-01T14:20:34.869310 | 2021-10-18T16:54:07 | 2021-10-18T16:54:07 | 421,917,075 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,225 | java | package Algorithms.Graphs;
public class Bfs {
public static int adj[][];
public static int visited[];
public static int n;
static void bfs(int node){
int q[] = new int[n];
int f=-1,r=-1;
q[++r] = node;
visited[node] = 1;
while(f!=r){
node = q[++f];
System.out.print(node+1);
for(int i=0;i<n;i++){
if(adj[node][i] == 1 && visited[i]==0){
visited[i] =1;
q[++r] = i;
}
}
}
}
public static void main(String[] args) {
// n = > no of nodes to be declared as 4
n = 4;
adj = new int[n][n];
visited = new int[4];
// adjacency matrix creation
adj[0][1] = 1;
adj[0][2] = 1;
adj[0][3] = 1;
adj[1][0] = 1;
adj[1][2] = 1;
adj[2][0] = 1;
adj[2][1] = 1;
adj[3][0] = 1;
bfs(0);
visited = new int[4];
System.out.println();
bfs(1);
visited = new int[4];
System.out.println();
bfs(2);
visited = new int[4];
System.out.println();
bfs(3);
}
}
| [
"[email protected]"
]
| |
1746347a391f7442b5dea74a46b5d4f737ab897f | f5648d2dec1e2025157132ea9b5655079ecc1bd5 | /src/app/MyFirstGAEProjectServlet.java | 90c180891e70aabb07f5ffad385253c6242af1d7 | []
| no_license | TamuzHod/tag2 | dabe6cfa9a86fd01cdecd705e18c349b6ae7dde8 | 9e8ea23081269f09e10daa80a688435f990e5bf9 | refs/heads/master | 2021-01-10T15:05:25.618138 | 2015-05-26T05:22:37 | 2015-05-26T05:22:37 | 36,273,895 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 332 | java | package app;
import java.io.IOException;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class MyFirstGAEProjectServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("it worked");
}
}
| [
"[email protected]"
]
| |
a7e41a9b339a4ef225af47f0978fcbea565dde9c | 0a8bb7482bbada77c4f6418d52bd6c0f9dbbe7a8 | /src/main/java/br/com/abim/bestmeal/web/rest/errors/CustomParameterizedException.java | f05ae7aaa70d1ee812e1f637539ad94a115febfb | []
| no_license | RenatoFarofa/BeastMeal_OLD | 6a98d4d420391506694ac4980a4b425da2e29079 | dfbed298159f30f618db545c70d7a723e2c52328 | refs/heads/master | 2022-01-12T23:50:43.091561 | 2019-05-12T01:52:32 | 2019-05-12T01:52:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,738 | java | package br.com.abim.bestmeal.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import java.util.HashMap;
import java.util.Map;
import static org.zalando.problem.Status.BAD_REQUEST;
/**
* Custom, parameterized exception, which can be translated on the client side.
* For example:
*
* <pre>
* throw new CustomParameterizedException("myCustomError", "hello", "world");
* </pre>
*
* Can be translated with:
*
* <pre>
* "error.myCustomError" : "The server says {{param0}} to {{param1}}"
* </pre>
*/
public class CustomParameterizedException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
private static final String PARAM = "param";
public CustomParameterizedException(String message, String... params) {
this(message, toParamMap(params));
}
public CustomParameterizedException(String message, Map<String, Object> paramMap) {
super(ErrorConstants.PARAMETERIZED_TYPE, "Parameterized Exception", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap));
}
public static Map<String, Object> toParamMap(String... params) {
Map<String, Object> paramMap = new HashMap<>();
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
paramMap.put(PARAM + i, params[i]);
}
}
return paramMap;
}
public static Map<String, Object> toProblemParameters(String message, Map<String, Object> paramMap) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", message);
parameters.put("params", paramMap);
return parameters;
}
}
| [
"[email protected]"
]
| |
3c49e04ff002df87030bee34f99e0e0d94be3baa | 4473e6229ef7cc8cf5ae36229d39dc6d8fc3ef56 | /department/src/main/java/anandh/department/types/Error.java | 57cdb6787cf671185fef3db87a2a258cb630e935 | []
| no_license | Anandharaj0930/KubernatesSample | aa16a4a2361ee090dbd932e82c3c02b34490f318 | be3de822854e11fe036a9c2593ac27d96a1ce308 | refs/heads/main | 2023-03-10T21:47:13.014437 | 2021-02-27T17:17:34 | 2021-02-27T17:17:34 | 339,932,611 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 649 | java | package anandh.department.types;
public class Error {
private String statusCode;
private String statusMsg;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMsg() {
return statusMsg;
}
public void setStatusMsg(String statusMsg) {
this.statusMsg = statusMsg;
}
@Override
public String toString() {
return "Error{" +
"statusCode='" + statusCode + '\'' +
", statusMsg='" + statusMsg + '\'' +
'}';
}
}
| [
"[email protected]"
]
| |
c52a5d49bc8ade0dab1fd7741722aafc73056ea4 | 80bbf0fce94f1e28e50b687279be822202c2d95d | /ConcertoPlayer/app/src/main/java/com/music/concertoplayer/utils/AssetsUtil.java | fc8846a3ae143d715a9867c879e8bd29eaaa60f8 | []
| no_license | actorpub/product | b94d2aeed10d5d8505f0bfc1232af6917c3acd44 | 6e877c3f966261dba7c825ea8885bb6c80450bd8 | refs/heads/master | 2020-03-22T12:55:46.109151 | 2018-07-21T02:34:58 | 2018-07-21T02:34:58 | 140,071,342 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,300 | java | package com.music.concertoplayer.utils;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by chen on 2018/5/23.
*/
public class AssetsUtil {
public static void doCopy(Context context, String assetsPath, String desPath) throws IOException {
String[] srcFiles = context.getAssets().list(assetsPath);//for directory
for (String srcFileName : srcFiles) {
String outFileName = desPath + File.separator + assetsPath + File.separator + srcFileName;
if (new File(outFileName).exists()) {
continue;
}
String inFileName = assetsPath + File.separator + srcFileName;
if (assetsPath.equals("")) {// for first time
inFileName = srcFileName;
}
Log.e("tag","========= assets: "+ assetsPath+" filename: "+srcFileName +" infile: "+inFileName+" outFile: "+outFileName);
try {
InputStream inputStream = context.getAssets().open(inFileName);
copyAndClose(inputStream, new FileOutputStream(outFileName));
} catch (IOException e) {//if directory fails exception
e.printStackTrace();
new File(outFileName).mkdir();
doCopy(context,inFileName, outFileName);
}
}
}
private static void closeQuietly(OutputStream out){
try{
if(out != null) out.close();;
}catch (IOException ex){
ex.printStackTrace();
}
}
private static void closeQuietly(InputStream is){
try{
if(is != null){
is.close();
}
}catch (IOException ex){
ex.printStackTrace();
}
}
private static void copyAndClose(InputStream is, OutputStream out) throws IOException{
copy(is,out);
closeQuietly(is);
closeQuietly(out);
}
private static void copy(InputStream is, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int n = 0;
while(-1 != (n = is.read(buffer))){
out.write(buffer,0,n);
}
}
}
| [
"[email protected]"
]
| |
43c732042be6921437ea0d0912665f20be731aed | d9f02bed95daf72513132f786830f3f8bc96982f | /spring_assessment/src/main/java/com/tavant/spring_assessment/utils/LowerClassNameResolver.java | 0101c75e25e3062a3f517c52ec0089a052ec6de8 | []
| no_license | anurajsinha08/practical_assessment | 7b14cdc225d23309c27e6e13422f4dac7c899fd1 | 3f1db956898b2fc3744069db8c9574e7b7981a37 | refs/heads/master | 2023-03-03T07:32:56.260700 | 2021-02-13T07:16:33 | 2021-02-13T07:16:33 | 338,516,181 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 718 | java | package com.tavant.spring_assessment.utils;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
public class LowerClassNameResolver extends TypeIdResolverBase{
@Override
public String idFromValue(Object value) {
// TODO Auto-generated method stub
return value.getClass().getSimpleName().toLowerCase();
}
@Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
// TODO Auto-generated method stub
return idFromValue(value);
}
@Override
public Id getMechanism() {
// TODO Auto-generated method stub
return JsonTypeInfo.Id.CUSTOM;
}
}
| [
"[email protected]"
]
| |
7ac3740d1847566a74344967ff6660d381773604 | bda2f258dbd69d88f76c987b416323a4d3fcc6cc | /app/src/main/java/com/tarena/myenginedemo/CoolParticleSampleActivity.java | 6d33f100e3fd35ac1cc0bf8bb3f656e1126d051d | []
| no_license | piglite/MyEngineDemo | fa65ac2cf4f465f3ab4f9120e47fda2ee981b44d | 77ff422ad8b3e7241f762a2869a81090a58ac7bc | refs/heads/master | 2020-06-17T17:34:10.325917 | 2017-06-13T09:54:15 | 2017-06-13T09:54:15 | 94,159,610 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 7,490 | java | package com.tarena.myenginedemo;
import android.opengl.GLES20;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.particle.SpriteParticleSystem;
import org.andengine.entity.particle.emitter.PointParticleEmitter;
import org.andengine.entity.particle.initializer.AccelerationParticleInitializer;
import org.andengine.entity.particle.initializer.BlendFunctionParticleInitializer;
import org.andengine.entity.particle.initializer.ColorParticleInitializer;
import org.andengine.entity.particle.initializer.ExpireParticleInitializer;
import org.andengine.entity.particle.initializer.RotationParticleInitializer;
import org.andengine.entity.particle.initializer.VelocityParticleInitializer;
import org.andengine.entity.particle.modifier.AlphaParticleModifier;
import org.andengine.entity.particle.modifier.ColorParticleModifier;
import org.andengine.entity.particle.modifier.ScaleParticleModifier;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.adt.color.Color;
import java.io.IOException;
public class CoolParticleSampleActivity extends SimpleBaseGameActivity {
BuildableBitmapTextureAtlas atlas;
ITextureRegion region;
@Override
public EngineOptions onCreateEngineOptions() {
Camera camera = new Camera(0, 0, 800, 480);
EngineOptions op = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new FillResolutionPolicy(), camera);
op.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
op.getRenderOptions().setDithering(true);
op.getRenderOptions().getConfigChooserOptions().setRequestedAlphaSize(8);
op.getRenderOptions().getConfigChooserOptions().setRequestedRedSize(8);
op.getRenderOptions().getConfigChooserOptions().setRequestedGreenSize(8);
op.getRenderOptions().getConfigChooserOptions().setRequestedBlueSize(8);
return op;
}
@Override
protected void onCreateResources() throws IOException {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
atlas = new BuildableBitmapTextureAtlas(getTextureManager(), 32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
region = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlas, this, "particle_fire.png");
try {
atlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
} catch (ITextureAtlasBuilder.TextureAtlasBuilderException e) {
e.printStackTrace();
}
atlas.load();
;
}
@Override
protected Scene onCreateScene() {
Scene scene = new Scene();
scene.setBackground(new Background(Color.BLACK));
{
SpriteParticleSystem particleSystem = new SpriteParticleSystem(
new PointParticleEmitter(0, 480), 6, 10, 200, region, getVertexBufferObjectManager()
);
particleSystem.addParticleInitializer(new BlendFunctionParticleInitializer<Sprite>(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE));
//生成粒子时为粒子提供一个初速度,其中水平方向的速度为(15,22)之间,保证粒子向屏幕右侧移动;垂直方向速度为(60,90)之间,保证粒子向屏幕下方移动
particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(15, 22, -60, -90));
//如果没有AccelerationParticleInitializer的话,那么创建出来的粒子将以恒定不变的速度持续移动11.5秒(ExpireParticleInitializer决定的)
//在有AccelerationParticleInitializer的情况下,横向速度每秒增加5,纵向速度每秒增加15
particleSystem.addParticleInitializer(new AccelerationParticleInitializer<Sprite>(5, 15));
//生成粒子时让粒子有一个0~360之间的旋转角度
particleSystem.addParticleInitializer(new RotationParticleInitializer<Sprite>(0.0f, 360.0f));
//生成粒子时粒子的颜色为红色
particleSystem.addParticleInitializer(new ColorParticleInitializer<Sprite>(1.0f, 0.0f, 0.0f));
particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(11.5f));
//粒子生成之后,在0~11.5秒之间从原始大小的一半放大到原始大小的一倍
particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 11.5f, 0.5f, 2.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(2.5f, 3.5f, 1.0f, 0.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(3.5f, 4.5f, 0.0f, 1.0f));
//粒子生成后,在0~11.5秒之间从原始的红色逐渐的变成蓝色
particleSystem.addParticleModifier(new ColorParticleModifier<Sprite>(0.0f, 11.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(4.5f, 11.5f, 1.0f, 0.0f));
scene.attachChild(particleSystem);
}
{
SpriteParticleSystem particleSystem = new SpriteParticleSystem(new PointParticleEmitter
(800 - 32, 480), 8, 12, 200, region, this.getVertexBufferObjectManager());
particleSystem.addParticleInitializer(new BlendFunctionParticleInitializer<Sprite>(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE));
particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-15, -22, -60, -90));
particleSystem.addParticleInitializer(new AccelerationParticleInitializer<Sprite>(-5, 15));
particleSystem.addParticleInitializer(new RotationParticleInitializer<Sprite>(0.0f, 360.0f));
particleSystem.addParticleInitializer(new ColorParticleInitializer<Sprite>(0.0f, 0.0f, 1.0f));
particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(11.5f));
particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 5, 0.5f, 2f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(2.5f, 3.5f, 1.0f, 0.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(3.5f, 4.5f, 0.0f, 1.0f));
particleSystem.addParticleModifier(new ColorParticleModifier<Sprite>(0.0f, 11.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f));
particleSystem.addParticleModifier(new AlphaParticleModifier<Sprite>(4.5f, 11.5f, 1.0f, 0.0f));
scene.attachChild(particleSystem);
}
return scene;
}
}
| [
"[email protected]"
]
| |
1d8234bef1332704aaf859be72f97418eaf43fb2 | 022ad9d2fd938baf66401cda15420aeb3cfff0c8 | /src/main/java/net/sf/cram/encoding/ByteArrayLenEncoding.java | cd0abb9e0ab92c29cfa14b885478af18f6a450b4 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | vadimzalunin/crammer | b88af1afbd3e61dbfa332b83b635f55cd42792e0 | 0b0e911a53b5583b1cbffc60efc343b22da51afa | refs/heads/master | 2020-12-24T14:26:20.560733 | 2013-03-26T13:01:01 | 2013-03-26T13:01:01 | 1,546,766 | 18 | 1 | null | 2012-10-06T02:23:23 | 2011-03-30T15:41:18 | Java | UTF-8 | Java | false | false | 3,672 | java | package net.sf.cram.encoding;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Map;
import net.sf.cram.DataSeriesType;
import net.sf.cram.EncodingID;
import net.sf.cram.EncodingParams;
import net.sf.cram.io.BitInputStream;
import net.sf.cram.io.BitOutputStream;
import net.sf.cram.io.ByteBufferUtils;
import net.sf.cram.io.ExposedByteArrayOutputStream;
public class ByteArrayLenEncoding implements Encoding<byte[]> {
public final static EncodingID ID = EncodingID.BYTE_ARRAY_LEN;
private Encoding<Integer> lenEncoding;
private Encoding<byte[]> byteEncoding;
public ByteArrayLenEncoding() {
}
@Override
public EncodingID id() {
return ID;
}
public static EncodingParams toParam(EncodingParams lenParams,
EncodingParams byteParams) {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte) lenParams.id.ordinal());
ByteBufferUtils.writeUnsignedITF8(lenParams.params.length, buf);
buf.put(lenParams.params);
buf.put((byte) byteParams.id.ordinal());
ByteBufferUtils.writeUnsignedITF8(byteParams.params.length, buf);
buf.put(byteParams.params);
buf.flip();
byte[] data = new byte[buf.limit()];
buf.get(data);
EncodingParams params = new EncodingParams(ID, data);
return params;
}
public byte[] toByteArray() {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte) lenEncoding.id().ordinal());
byte[] lenBytes = lenEncoding.toByteArray();
ByteBufferUtils.writeUnsignedITF8(lenBytes.length, buf);
buf.put(lenBytes);
buf.put((byte) byteEncoding.id().ordinal());
byte[] byteBytes = lenEncoding.toByteArray();
ByteBufferUtils.writeUnsignedITF8(byteBytes.length, buf);
buf.put(byteBytes);
buf.flip();
byte[] array = new byte[buf.limit()];
buf.get(array);
return array;
}
public void fromByteArray(byte[] data) {
ByteBuffer buf = ByteBuffer.wrap(data);
EncodingFactory f = new EncodingFactory();
EncodingID lenID = EncodingID.values()[buf.get()];
lenEncoding = f.createEncoding(DataSeriesType.INT, lenID);
int len = ByteBufferUtils.readUnsignedITF8(buf);
byte[] bytes = new byte[len];
buf.get(bytes);
lenEncoding.fromByteArray(bytes);
EncodingID byteID = EncodingID.values()[buf.get()];
byteEncoding = f.createEncoding(DataSeriesType.BYTE_ARRAY, byteID);
len = ByteBufferUtils.readUnsignedITF8(buf);
bytes = new byte[len];
buf.get(bytes);
byteEncoding.fromByteArray(bytes);
}
@Override
public BitCodec<byte[]> buildCodec(Map<Integer, InputStream> inputMap,
Map<Integer, ExposedByteArrayOutputStream> outputMap) {
return new ByteArrayLenCodec(
lenEncoding.buildCodec(inputMap, outputMap),
byteEncoding.buildCodec(inputMap, outputMap));
}
private static class ByteArrayLenCodec implements BitCodec<byte[]> {
private BitCodec<Integer> lenCodec;
private BitCodec<byte[]> byteCodec;
public ByteArrayLenCodec(BitCodec<Integer> lenCodec,
BitCodec<byte[]> byteCodec) {
super();
this.lenCodec = lenCodec;
this.byteCodec = byteCodec;
}
@Override
public byte[] read(BitInputStream bis) throws IOException {
int len = lenCodec.read(bis);
return byteCodec.read(bis, len);
}
@Override
public byte[] read(BitInputStream bis, int len) throws IOException {
throw new RuntimeException("Not implemented.");
}
@Override
public long write(BitOutputStream bos, byte[] object)
throws IOException {
long len = lenCodec.write(bos, object.length);
len += byteCodec.write(bos, object);
return len;
}
@Override
public long numberOfBits(byte[] object) {
return lenCodec.numberOfBits(object.length)
+ byteCodec.numberOfBits(object);
}
}
}
| [
"[email protected]"
]
| |
aa79a33c854b1b8b8d5656135f806d43866d723b | b8079179faed8ade9e3a26fbdc319a1d2906365c | /src/com/ibm/focus/importers/StringUtilsCustom.java | c6178e14462d48448582c4fcab395d611533476e | []
| no_license | kalpanal/CTDModeler | 65bb975edc6cb306f3e901abc96c39060b4a770b | 112e3378a327fde8e9238dd01d00f2fa4940f859 | refs/heads/master | 2021-05-11T13:58:36.850917 | 2018-03-09T14:52:34 | 2018-03-09T14:52:34 | 117,690,714 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,473 | java | package com.ibm.focus.importers;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
public class StringUtilsCustom {
public static String getDataSheetName(String dataSourceFullPath) throws Exception {
String sheetName = null;
if(dataSourceFullPath != null || (!dataSourceFullPath.isEmpty())){
ArrayList<Integer> listofPositionsOfColon = occurrencesPos(dataSourceFullPath, ":");
sheetName = dataSourceFullPath.substring(dataSourceFullPath.indexOf(":", listofPositionsOfColon.get(1))+1);
}
return sheetName;
}
/*C:\Kalpana\TD Bank\datasheets\DocDelivery.xlsx: Pos-printing;3 */
public static String getFileNameWithPath(String fullPathWithRowIndex) throws Exception {
String fullPathWithOutRowIndex = null;
if((fullPathWithRowIndex != null || (!fullPathWithRowIndex.isEmpty())) && (fullPathWithRowIndex.indexOf(";") > 0)) {
fullPathWithOutRowIndex = fullPathWithRowIndex.substring(0,fullPathWithRowIndex.indexOf(";"));
}else{
fullPathWithOutRowIndex = fullPathWithRowIndex;
}
return fullPathWithOutRowIndex;
}
public static String getFileNameWithOutSheet(String fullpathWithSheetName) throws Exception {
String fullPathWithOutSheetName = null;
if(fullpathWithSheetName != null || (!fullpathWithSheetName.isEmpty())){
ArrayList<Integer> listofPositionsOfColon = occurrencesPos(fullpathWithSheetName, ":");
fullPathWithOutSheetName = fullpathWithSheetName.substring(0,fullpathWithSheetName.indexOf(":", listofPositionsOfColon.get(1)));
}
return fullPathWithOutSheetName;
}
public static String getSheetNameAlone(String fullpathWithSheetName) throws Exception {
String fullPathWithOutSheetName = null;
if(fullpathWithSheetName != null || (!fullpathWithSheetName.isEmpty())){
fullPathWithOutSheetName = fullpathWithSheetName.substring(fullpathWithSheetName.indexOf(":")+1);
}
return fullPathWithOutSheetName.trim();
}
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
final boolean ignoreCase = true;
int substrLength = substr.length();
int strLength = str.length();
ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();
for(int i = 0; i < strLength - substrLength + 1; i++) {
if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) {
occurrenceArr.add(i);
}
}
return occurrenceArr;
}
}
| [
"[email protected]"
]
| |
6de8002ec43a616b7331b2d8c575bba2b3211fb3 | 13f21b2923050db1d01cc75b588ec2a6da0a284a | /dumpclass.java | 922aef19c915711580b38dff65d78dd1690b8dad | []
| no_license | NandiniBanapur/TestVagrantNandini | 4717b606d50818234742fa919b6fbc15bbd0d1de | 84862d69c2d241d1086b15d605b2d92fdf61eea1 | refs/heads/master | 2021-05-16T20:42:47.637899 | 2020-03-27T16:32:56 | 2020-03-27T16:32:56 | 250,462,066 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java |
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class dumpclass
{
public static void main(String[] args)
{
ItemList items=new ItemList();
Item i=new Item();
i.setcategory("TOI");
i.setfrequency(Frequency.Daily);
i.setprice(0.75);
Item i2=new Item();
i2.setcategory("MILK");
i2.setfrequency(Frequency.Monthly);
i2.setprice(30);
items.AddItem(i);
items.AddItem(i2);
System.out.println(items.TotalMonthlyExpenditureOnSubscriptions());
}
}
| [
"[email protected]"
]
| |
a02f46e4bdea6cd3f91eedddf79c46388dbfe0f7 | 4895c6035dbeb9fce57d533dd3aa1f90a37753cd | /src/main/java/tasks/task5/pack/util/ConsoleEntity.java | 5cd6f6c6943d879670df166b2857f8a88a40c17c | []
| no_license | Simbianna/JSON-Database | ba926e045246df9fd05b7d7e922743a880b7fb11 | 6b1277f41d4dfb1830499541d73582239bba87ae | refs/heads/master | 2023-04-22T06:56:49.074737 | 2021-05-08T10:15:10 | 2021-05-08T10:15:10 | 339,685,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,193 | java | package tasks.task5.pack.util;
import tasks.task5.pack.command.CommandType;
public class ConsoleEntity {
private CommandType type;
private String key;
private String value;
public ConsoleEntity(CommandType type, String key, String value) {
this.type = type;
this.key = key;
this.value = value;
}
public ConsoleEntity(CommandType type, String key) {
this.type = type;
this.key = key;
}
public ConsoleEntity(CommandType type) {
this.type = type;
}
public static ConsoleEntity getErrorConsoleEntity(String json){
return new ConsoleEntity(CommandType.ERROR, json);
}
public static ConsoleEntity getUnknownConsoleEntity(){
return new ConsoleEntity(CommandType.UNKNOWN);
}
public CommandType getType() {
return type;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public void setType(CommandType type) {
this.type = type;
}
public void setKey(String key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
}
| [
"[email protected]"
]
| |
086a2d4f2f5f57030c5e0ddf1de7e9995b83cca3 | f0568343ecd32379a6a2d598bda93fa419847584 | /modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/FlashRedirectOverlayCreative.java | a12abc125898310e0998ef679482848559e620b5 | [
"Apache-2.0"
]
| permissive | frankzwang/googleads-java-lib | bd098b7b61622bd50352ccca815c4de15c45a545 | 0cf942d2558754589a12b4d9daa5902d7499e43f | refs/heads/master | 2021-01-20T23:20:53.380875 | 2014-07-02T19:14:30 | 2014-07-02T19:14:30 | 21,526,492 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,138 | java | /**
* FlashRedirectOverlayCreative.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201308;
/**
* An overlay {@code Creative} that loads a Flash asset from a specified
* URL
* and is served via VAST 2.0 XML. Overlays cover part of
* the video content
* they are displayed on top of.
*/
public class FlashRedirectOverlayCreative extends com.google.api.ads.dfp.axis.v201308.BaseFlashRedirectCreative implements java.io.Serializable {
/* The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional. */
private long[] companionCreativeIds;
/* A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional. */
private com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls;
/* A comma separated key=value list of parameters that will be
* supplied to
* the creative, written into the VAST {@code AdParameters}
* node.
* If the {@link #apiFramework} is {@link ApiFramework#VPAID},
* the value does not need to be a comma separated key-value list (and
* can instead be any arbitrary string). This attribute is optional. */
private java.lang.String customParameters;
/* The API framework of the asset. This attribute is optional. */
private com.google.api.ads.dfp.axis.v201308.ApiFramework apiFramework;
/* Minimum suggested duration in milliseconds. This attribute
* is optional. */
private java.lang.Integer duration;
/* The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional. */
private com.google.api.ads.dfp.axis.v201308.Size flashAssetSize;
/* An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only. */
private java.lang.String vastPreviewUrl;
public FlashRedirectOverlayCreative() {
}
public FlashRedirectOverlayCreative(
java.lang.Long advertiserId,
java.lang.Long id,
java.lang.String name,
com.google.api.ads.dfp.axis.v201308.Size size,
java.lang.String previewUrl,
com.google.api.ads.dfp.axis.v201308.AppliedLabel[] appliedLabels,
com.google.api.ads.dfp.axis.v201308.DateTime lastModifiedDateTime,
com.google.api.ads.dfp.axis.v201308.BaseCustomFieldValue[] customFieldValues,
java.lang.String creativeType,
java.lang.String destinationUrl,
java.lang.String flashUrl,
java.lang.String fallbackUrl,
java.lang.String fallbackPreviewUrl,
long[] companionCreativeIds,
com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls,
java.lang.String customParameters,
com.google.api.ads.dfp.axis.v201308.ApiFramework apiFramework,
java.lang.Integer duration,
com.google.api.ads.dfp.axis.v201308.Size flashAssetSize,
java.lang.String vastPreviewUrl) {
super(
advertiserId,
id,
name,
size,
previewUrl,
appliedLabels,
lastModifiedDateTime,
customFieldValues,
creativeType,
destinationUrl,
flashUrl,
fallbackUrl,
fallbackPreviewUrl);
this.companionCreativeIds = companionCreativeIds;
this.trackingUrls = trackingUrls;
this.customParameters = customParameters;
this.apiFramework = apiFramework;
this.duration = duration;
this.flashAssetSize = flashAssetSize;
this.vastPreviewUrl = vastPreviewUrl;
}
/**
* Gets the companionCreativeIds value for this FlashRedirectOverlayCreative.
*
* @return companionCreativeIds * The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional.
*/
public long[] getCompanionCreativeIds() {
return companionCreativeIds;
}
/**
* Sets the companionCreativeIds value for this FlashRedirectOverlayCreative.
*
* @param companionCreativeIds * The IDs of the companion creatives that are associated with
* this creative.
* This attribute is optional.
*/
public void setCompanionCreativeIds(long[] companionCreativeIds) {
this.companionCreativeIds = companionCreativeIds;
}
public long getCompanionCreativeIds(int i) {
return this.companionCreativeIds[i];
}
public void setCompanionCreativeIds(int i, long _value) {
this.companionCreativeIds[i] = _value;
}
/**
* Gets the trackingUrls value for this FlashRedirectOverlayCreative.
*
* @return trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional.
*/
public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] getTrackingUrls() {
return trackingUrls;
}
/**
* Sets the trackingUrls value for this FlashRedirectOverlayCreative.
*
* @param trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will
* be pinged
* when the event happens. This attribute is optional.
*/
public void setTrackingUrls(com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls) {
this.trackingUrls = trackingUrls;
}
public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry getTrackingUrls(int i) {
return this.trackingUrls[i];
}
public void setTrackingUrls(int i, com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry _value) {
this.trackingUrls[i] = _value;
}
/**
* Gets the customParameters value for this FlashRedirectOverlayCreative.
*
* @return customParameters * A comma separated key=value list of parameters that will be
* supplied to
* the creative, written into the VAST {@code AdParameters}
* node.
* If the {@link #apiFramework} is {@link ApiFramework#VPAID},
* the value does not need to be a comma separated key-value list (and
* can instead be any arbitrary string). This attribute is optional.
*/
public java.lang.String getCustomParameters() {
return customParameters;
}
/**
* Sets the customParameters value for this FlashRedirectOverlayCreative.
*
* @param customParameters * A comma separated key=value list of parameters that will be
* supplied to
* the creative, written into the VAST {@code AdParameters}
* node.
* If the {@link #apiFramework} is {@link ApiFramework#VPAID},
* the value does not need to be a comma separated key-value list (and
* can instead be any arbitrary string). This attribute is optional.
*/
public void setCustomParameters(java.lang.String customParameters) {
this.customParameters = customParameters;
}
/**
* Gets the apiFramework value for this FlashRedirectOverlayCreative.
*
* @return apiFramework * The API framework of the asset. This attribute is optional.
*/
public com.google.api.ads.dfp.axis.v201308.ApiFramework getApiFramework() {
return apiFramework;
}
/**
* Sets the apiFramework value for this FlashRedirectOverlayCreative.
*
* @param apiFramework * The API framework of the asset. This attribute is optional.
*/
public void setApiFramework(com.google.api.ads.dfp.axis.v201308.ApiFramework apiFramework) {
this.apiFramework = apiFramework;
}
/**
* Gets the duration value for this FlashRedirectOverlayCreative.
*
* @return duration * Minimum suggested duration in milliseconds. This attribute
* is optional.
*/
public java.lang.Integer getDuration() {
return duration;
}
/**
* Sets the duration value for this FlashRedirectOverlayCreative.
*
* @param duration * Minimum suggested duration in milliseconds. This attribute
* is optional.
*/
public void setDuration(java.lang.Integer duration) {
this.duration = duration;
}
/**
* Gets the flashAssetSize value for this FlashRedirectOverlayCreative.
*
* @return flashAssetSize * The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional.
*/
public com.google.api.ads.dfp.axis.v201308.Size getFlashAssetSize() {
return flashAssetSize;
}
/**
* Sets the flashAssetSize value for this FlashRedirectOverlayCreative.
*
* @param flashAssetSize * The size of the flash asset. Note that this may differ from
* {@link #size}
* if the asset is not expected to fill the entire
* video player. This attribute
* is optional.
*/
public void setFlashAssetSize(com.google.api.ads.dfp.axis.v201308.Size flashAssetSize) {
this.flashAssetSize = flashAssetSize;
}
/**
* Gets the vastPreviewUrl value for this FlashRedirectOverlayCreative.
*
* @return vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only.
*/
public java.lang.String getVastPreviewUrl() {
return vastPreviewUrl;
}
/**
* Sets the vastPreviewUrl value for this FlashRedirectOverlayCreative.
*
* @param vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response
* specific
* to this creative. This attribute is read-only.
*/
public void setVastPreviewUrl(java.lang.String vastPreviewUrl) {
this.vastPreviewUrl = vastPreviewUrl;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof FlashRedirectOverlayCreative)) return false;
FlashRedirectOverlayCreative other = (FlashRedirectOverlayCreative) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.companionCreativeIds==null && other.getCompanionCreativeIds()==null) ||
(this.companionCreativeIds!=null &&
java.util.Arrays.equals(this.companionCreativeIds, other.getCompanionCreativeIds()))) &&
((this.trackingUrls==null && other.getTrackingUrls()==null) ||
(this.trackingUrls!=null &&
java.util.Arrays.equals(this.trackingUrls, other.getTrackingUrls()))) &&
((this.customParameters==null && other.getCustomParameters()==null) ||
(this.customParameters!=null &&
this.customParameters.equals(other.getCustomParameters()))) &&
((this.apiFramework==null && other.getApiFramework()==null) ||
(this.apiFramework!=null &&
this.apiFramework.equals(other.getApiFramework()))) &&
((this.duration==null && other.getDuration()==null) ||
(this.duration!=null &&
this.duration.equals(other.getDuration()))) &&
((this.flashAssetSize==null && other.getFlashAssetSize()==null) ||
(this.flashAssetSize!=null &&
this.flashAssetSize.equals(other.getFlashAssetSize()))) &&
((this.vastPreviewUrl==null && other.getVastPreviewUrl()==null) ||
(this.vastPreviewUrl!=null &&
this.vastPreviewUrl.equals(other.getVastPreviewUrl())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getCompanionCreativeIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getCompanionCreativeIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCompanionCreativeIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getTrackingUrls() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getTrackingUrls());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getTrackingUrls(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getCustomParameters() != null) {
_hashCode += getCustomParameters().hashCode();
}
if (getApiFramework() != null) {
_hashCode += getApiFramework().hashCode();
}
if (getDuration() != null) {
_hashCode += getDuration().hashCode();
}
if (getFlashAssetSize() != null) {
_hashCode += getFlashAssetSize().hashCode();
}
if (getVastPreviewUrl() != null) {
_hashCode += getVastPreviewUrl().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(FlashRedirectOverlayCreative.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "FlashRedirectOverlayCreative"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companionCreativeIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "companionCreativeIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("trackingUrls");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "trackingUrls"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ConversionEvent_TrackingUrlsMapEntry"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("customParameters");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "customParameters"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("apiFramework");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "apiFramework"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ApiFramework"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("duration");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "duration"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("flashAssetSize");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashAssetSize"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("vastPreviewUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "vastPreviewUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| [
"[email protected]"
]
| |
436b4ac255c56e09fab9d6d209e0ac16a4eafeae | 52d705c66ecdaa5e5de1ace7167a58009a6e0aa0 | /one-time-examples/underwriting-BPMN-and-CMMN/src/main/java/org/camunda/showcase/underwritingBPMN_CMMN/LoggerDelegate.java | 35aee2b664d1eb9e25532ddbf842b54d3cc5fc39 | [
"Apache-2.0"
]
| permissive | omineiro/code | 7f7062a6435014e279983748c9bdfbf0f69a55a3 | 612e1eccbf2a7cf7c6b2677a77b734e4e3a19972 | refs/heads/master | 2020-04-13T11:29:03.912452 | 2018-12-23T22:39:33 | 2018-12-23T22:39:33 | 163,175,868 | 1 | 0 | Apache-2.0 | 2018-12-26T12:06:21 | 2018-12-26T12:06:21 | null | UTF-8 | Java | false | false | 1,044 | java | package org.camunda.showcase.underwritingBPMN_CMMN;
import java.util.logging.Logger;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
/**
* This is an empty service implementation illustrating how to use a plain Java
* class as a BPMN 2.0 Service Task delegate.
*/
public class LoggerDelegate implements JavaDelegate {
private final Logger LOGGER = Logger.getLogger(LoggerDelegate.class.getName());
public void execute(DelegateExecution execution) throws Exception {
LOGGER.info("\n\n ... LoggerDelegate invoked by "
+ "processDefinitionId=" + execution.getProcessDefinitionId()
+ ", activtyId=" + execution.getCurrentActivityId()
+ ", activtyName='" + execution.getCurrentActivityName() + "'"
+ ", processInstanceId=" + execution.getProcessInstanceId()
+ ", businessKey=" + execution.getProcessBusinessKey()
+ ", executionId=" + execution.getId()
+ " \n\n");
}
}
| [
"[email protected]"
]
| |
b07d27752f2fd999c4d5a128bbda1de82e21ac16 | bddb65c69dffd58c3fa4ac3b4bfe768558ec8f73 | /extension/src/main/java/com/hframework/peacock/controller/base/HttpProtocolExecutor.java | 082eeb96cf6a19e67084c1d7ae32912541a45c03 | []
| no_license | sonygrq2014/peacock | 59d620ae07483db2028b2b631224742db2ab03e8 | 24b1ce0f2831c111b370a7c3dca1b0b21a19d26c | refs/heads/master | 2022-01-04T16:48:43.164148 | 2019-09-02T09:29:03 | 2019-09-02T09:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,276 | java | package com.hframework.peacock.controller.base;
import com.hframework.beans.exceptions.BusinessException;
import com.hframework.common.client.http.HttpClient;
import com.hframework.common.util.UrlHelper;
import com.hframework.peacock.controller.base.descriptor.ThirdApiDescriptor;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Executor;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class HttpProtocolExecutor extends AbstractProtocolExecutor{
private static Logger logger = LoggerFactory.getLogger(HttpProtocolExecutor.class);
private static ScheduledExecutorService blockMonitorScheduler = Executors.newScheduledThreadPool(1);
static {
blockMonitorScheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//DefaultConnectionKeepAliveStrategy 默认实现
Executor.closeIdleConnections();
}
}, 3, 3, TimeUnit.SECONDS);
}
public HttpProtocolExecutor(ThirdApiDescriptor apiDescriptor, ThirdApiConfigureRegistry registry) {
super(apiDescriptor, registry);
}
/**
* 协议按照descriptor进行API调用
*
* @param parameters
* @param nodes
* @return
*/
@Override
public String execute(Map<String, Object> parameters, Map<String, Object> nodes) throws Exception {
String result;
Map<String, String> stringParameters = getStringMapByObjMap(parameters);
if(apiDescriptor.isGetMethod()) {
result = HttpClient.doGet(registry.getDomain(getDomainId()) + apiDescriptor.getPath(), stringParameters);
}else if(apiDescriptor.getRequestType().hasJsonBody()) {
String url = getFinalUrl(registry.getDomain(getDomainId()) + apiDescriptor.getPath(), stringParameters);
String json = getJson(nodes);
result = HttpClient.doJsonPost(url, json);
}else if(apiDescriptor.getRequestType().hasXmlBody()) {
String url = getFinalUrl(registry.getDomain(getDomainId()) + apiDescriptor.getPath(), stringParameters);
String xml = getXml(nodes);
result = HttpClient.doXmlPost(url, xml);
}else if(apiDescriptor.getRequestType().hasTxtBody()) {
throw new BusinessException("unsupport txt body post !");
}else {
result = HttpClient.doPost(registry.getDomain(getDomainId()) + apiDescriptor.getPath(), stringParameters);
}
logger.info("http response=>{}", result);
return result;
}
}
| [
"[email protected]"
]
| |
855938aca0cdff2fccd9c8fad1ce47b6f6315f2b | b6b83183cf720cda988154da4d87f1b0955173fb | /app/src/main/java/rtu/group/adaptive/renthouse/Starter.java | 89d468cd75b8a059d9d35db00df5b4a3154fa26c | []
| no_license | dostonhamrakulov/Rent-House-Adaptive-App | c48cb0c3231d7782fdcc0201c469e669b39a83a5 | 46f80d3b32a2fd5978fa3ea1e74530391e063397 | refs/heads/master | 2021-05-08T12:05:50.236363 | 2019-02-10T14:18:33 | 2019-02-10T14:18:33 | 119,919,777 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,747 | java | package rtu.group.adaptive.renthouse;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Starter extends AppCompatActivity {
/*
* Created by Doston Hamrakulov
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starter);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
public void moveInserting(View view){
startActivity(new Intent(Starter.this, Inserting.class));
}
public void moveDisplaying(View view){
startActivity(new Intent(Starter.this, Displaying.class));
}
public void moveSearchHouse(View view){
startActivity(new Intent(Starter.this, SearchHouse.class));
}
public void give_instruction(View view){
AlertDialog.Builder alert_builder = new AlertDialog.Builder(this);
alert_builder.setMessage("Adaptive rent house application is developed by a group.")
.setCancelable(false)
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = alert_builder.create();
alert.setTitle("Information");
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main_action, menu);
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
universalBox("Sorry, there is no any option for setting!!!");
return true;
}
switch(id){
case R.id.id_about_us:
universalBox("This app has been developed for fun, not commercial purpose!\n\n" +
"Developer: Doston\n" +
"Email: [email protected]");
return true;
case R.id.id_contact_us:
universalBox("Website: idoston.com\n" +
"Email: [email protected]");
return true;
case R.id.id_exit_app:
Exit_alert();
return true;
}
return super.onOptionsItemSelected(item);
}
public void Exit_alert(){
AlertDialog.Builder alert_builder = new AlertDialog.Builder(this);
alert_builder.setMessage("Do you want to close this app?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(Starter.this, "Good bye!!!", Toast.LENGTH_SHORT).show();
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = alert_builder.create();
alert.setTitle("Alert!!!");
alert.show();
}
public void universalBox(String msg){
AlertDialog.Builder alert_builder = new AlertDialog.Builder(this);
alert_builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = alert_builder.create();
alert.show();
}
}
| [
"[email protected]"
]
| |
495906ab4d16efa20f818fab0cb1a7d0441594a1 | 1f19aec2ecfd756934898cf0ad2758ee18d9eca2 | /u-1/u-13/u-13-f6055.java | e640f4a893e5876d1378f867b659ec3a003788c1 | []
| no_license | apertureatf/perftest | f6c6e69efad59265197f43af5072aa7af8393a34 | 584257a0c1ada22e5486052c11395858a87b20d5 | refs/heads/master | 2020-06-07T17:52:51.172890 | 2019-06-21T18:53:01 | 2019-06-21T18:53:01 | 193,039,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117
5002791850994 | [
"[email protected]"
]
| |
58bb4a1f65db1303ac718af25ea34d9f8dbcf36c | c885ef92397be9d54b87741f01557f61d3f794f3 | /tests-without-trycatch/Math-6/org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer/BBC-F0-opt-50/4/org/apache/commons/math3/optim/nonlinear/vector/jacobian/GaussNewtonOptimizer_ESTest.java | 64bc6247c19650c4477fd5fcd31ba72d193e939c | [
"CC-BY-4.0",
"MIT"
]
| permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 2,567 | java | /*
* This file was automatically generated by EvoSuite
* Tue Oct 19 19:40:23 GMT 2021
*/
package org.apache.commons.math3.optim.nonlinear.vector.jacobian;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.apache.commons.math3.optim.ConvergenceChecker;
import org.apache.commons.math3.optim.PointVectorValuePair;
import org.apache.commons.math3.optim.SimpleVectorValueChecker;
import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class GaussNewtonOptimizer_ESTest extends GaussNewtonOptimizer_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
GaussNewtonOptimizer gaussNewtonOptimizer0 = new GaussNewtonOptimizer(true, (ConvergenceChecker<PointVectorValuePair>) null);
// Undeclared exception!
// try {
gaussNewtonOptimizer0.doOptimize();
// fail("Expecting exception: IllegalArgumentException");
// } catch(IllegalArgumentException e) {
// //
// // null is not allowed
// //
// verifyException("org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer", e);
// }
}
@Test(timeout = 4000)
public void test1() throws Throwable {
SimpleVectorValueChecker simpleVectorValueChecker0 = new SimpleVectorValueChecker(0.0, 0.0);
GaussNewtonOptimizer gaussNewtonOptimizer0 = new GaussNewtonOptimizer(false, simpleVectorValueChecker0);
// Undeclared exception!
// try {
gaussNewtonOptimizer0.doOptimize();
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.math3.optim.nonlinear.vector.MultivariateVectorOptimizer", e);
// }
}
@Test(timeout = 4000)
public void test2() throws Throwable {
SimpleVectorValueChecker simpleVectorValueChecker0 = new SimpleVectorValueChecker(0.0, (-722.460047924594));
GaussNewtonOptimizer gaussNewtonOptimizer0 = new GaussNewtonOptimizer(simpleVectorValueChecker0);
assertEquals(0.0, gaussNewtonOptimizer0.getChiSquare(), 0.01);
}
}
| [
"[email protected]"
]
| |
0e32387cb72361502440121fcb87a6c725fd52bf | dbe0e9003b6ffd329c3b5708123b98580b96bbcc | /example/src/main/java/nl/reinkrul/cqrslight/micronaut/ItemAddedEvent.java | 8e7573c0efff3c0a82bb09c6d41bc5019db260b1 | [
"Unlicense"
]
| permissive | reinkrul/cqrslight-micronaut | 570a86859ea6114b235df63be15488ff729a46f4 | 59a5eb35efb36614c2f02729882698e31b6b7798 | refs/heads/master | 2020-06-21T05:28:28.622303 | 2019-07-18T06:48:52 | 2019-07-18T06:48:52 | 197,355,994 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 366 | java | package nl.reinkrul.cqrslight.micronaut;
import io.micronaut.context.event.ApplicationEvent;
public class ItemAddedEvent extends ApplicationEvent {
private final String name;
public ItemAddedEvent(final Object source, final String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
}
| [
"[email protected]"
]
| |
0e7e916e6bd0c9cc8e2026cb4c7e5ab59b4c4ec4 | ade43c95a131bc9f33b8f99e8b0053b5bc1393e8 | /src/OWON_VDS_v1.0.24/com/owon/uppersoft/vds/core/comm/ICommunicateManager.java | fab0a0e13393e36f811c5e543fd155e6f4daf34e | []
| no_license | AbirFaisal/RealScope | 7ba7532986ea1ee11683b4bd96f746e800ea144a | f80ff68a8e9d61d7bec12b464b637decb036a3f0 | refs/heads/master | 2020-03-30T04:21:38.344659 | 2018-10-03T17:54:16 | 2018-10-03T17:54:16 | 150,738,973 | 7 | 0 | null | null | null | null | UTF-8 | Java | false | false | 857 | java | package com.owon.uppersoft.vds.core.comm;
/**
* ICommunicateManager,将比较底层的通用数据传输接口分离为单独的类
*
*/
public interface ICommunicateManager {
/**
* 对远程端在出现传输出错后,可以用来尝试恢复并重新连接
*
* 使用基于通信类的该方法可以避免涉及通信方式的细节信息如端口ip等, 也不需要在重新连接中设置这些,方便使用
*/
boolean tryRescue();
int retryTimes();
/**
* 在具体的实现中,根据实现的连接状态判断;
*
* 在统一的SourceManager/BufferredSourceManager中,使用特定变量判断
*
* @return
*/
boolean isConnected();
/**
* 写指令
*/
int write(byte[] arr, int len);
/**
* 接收单独指令
*/
int acceptResponse(byte[] arr, int len);
} | [
"[email protected]"
]
| |
eef8dadeb7b68777bf77a4f7496487fd8f522a66 | dd18a1a2ba5a47775f1615e6a8edd3d01222780d | /src/cn/cche/exception/DAOException.java | b4795ee83d4f311b2e68304dcef4b0bf4486423f | []
| no_license | mynacche/ccheBlog | abde6c687db4e30057d90ab01c761165460d8b8f | 4470e342864717ec177a6518576a1f96b4878107 | refs/heads/master | 2020-05-19T10:24:59.933066 | 2013-09-18T10:37:32 | 2013-09-18T10:37:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 586 | java | package cn.cche.exception;
public class DAOException extends RuntimeException {
private static final long serialVersionUID = 1939686586971715397L;
public DAOException() {
super();
}
public DAOException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public DAOException(String message, Throwable cause) {
super(message, cause);
}
public DAOException(String message) {
super(message);
}
public DAOException(Throwable cause) {
super(cause);
}
}
| [
"[email protected]"
]
| |
fe99f31bc0f07396d5ac31c04d6bf19786d1a79c | a597bfa007dbd41f71906798518c5d11bd3d5f31 | /Project_1/app/src/main/java/com/example/project_1/registerUser.java | 9ba8eced8b63047e62867606eb9190b0f7a136ad | []
| no_license | robo-codes/Heroku_ML_deployment | 484608d48bf15810219e672fdc9d708d57d25dfa | 6e476237855e2811ed060f78d357072698cdc0b4 | refs/heads/main | 2023-04-14T18:08:02.421938 | 2021-04-13T06:28:20 | 2021-04-13T06:28:20 | 356,546,930 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,057 | java | package com.example.project_1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaCodec;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import java.util.regex.Pattern;
public class registerUser extends AppCompatActivity {
private Button registerUser;
private EditText editTextTextEmailAddress4, editTextTextEmailAddress3, editTextTextEmailAddress2, editTextTextPassword2;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
Switch LogIn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
mAuth = FirebaseAuth.getInstance();
registerUser = (Button) findViewById(R.id.button2);
registerUser.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button2:
registerUser();
break;
}
}
});
editTextTextEmailAddress4 = (EditText) findViewById(R.id.editTextTextEmailAddress4);
editTextTextEmailAddress3 = (EditText) findViewById(R.id.editTextTextEmailAddress3);
editTextTextEmailAddress2 = (EditText) findViewById(R.id.editTextTextEmailAddress2);
editTextTextPassword2 = (EditText) findViewById(R.id.editTextTextPassword2);
progressBar = (ProgressBar) findViewById(R.id.progressBar2);
LogIn = (Switch) findViewById((R.id.switch3));
LogIn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
startActivity(new Intent(registerUser.this, MainActivity.class));
}
}
});
}
private void registerUser() {
String email = editTextTextEmailAddress2.getText().toString().trim();
String password = editTextTextPassword2.getText().toString().trim();
String fullName = editTextTextEmailAddress4.getText().toString().trim();
String PatientOrDoctor = editTextTextEmailAddress3.getText().toString().trim();
if(fullName.isEmpty()){
editTextTextEmailAddress4.setError("Full name is required");
editTextTextEmailAddress4.requestFocus();
return;
}
if(PatientOrDoctor.isEmpty()) {
editTextTextEmailAddress3.setError("Are you the doctor or the patient?");
editTextTextEmailAddress3.requestFocus();
return;
}
if(email.isEmpty()) {
editTextTextEmailAddress2.setError("Please provide your email address !");
editTextTextEmailAddress2.requestFocus();
return;
}
if(!(Patterns.EMAIL_ADDRESS.matcher(email).matches())) {
editTextTextEmailAddress2.setError("Please enter a valid Email !");
editTextTextEmailAddress2.requestFocus();
return;
}
if(password.isEmpty()) {
editTextTextPassword2.setError("Password is required");
editTextTextPassword2.requestFocus();
return;
}
if(password.length() < 6) {
editTextTextPassword2.setError("Please enter more than 6 characters.");
editTextTextPassword2.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
user user = new user(fullName, PatientOrDoctor, email);
FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(registerUser.this,"user has been registered successfully !", Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(registerUser.this,"failed to register! Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(registerUser.this, "failed to register! Please try again.", Toast.LENGTH_SHORT).show();
}
}
}));
}
} | [
"[email protected]"
]
| |
44ea893f51f1d8f8cd5f37d05e26605d9024b132 | 63241be0c697e981dad89188f5c696f077272a2d | /src/swComunicacion/views/Opcion2.java | 6517d159c0f468e47f8bfe644ecd2d6040691aba | [
"MIT"
]
| permissive | enjalamu/SW-Comunication | 56ad1554434292e57e0cf7098ab6744935770f9f | a7e79c4656e4c14b5d95cc61192b56ea13b3029c | refs/heads/master | 2020-06-25T11:34:12.855885 | 2016-11-23T21:59:31 | 2016-11-23T21:59:31 | 74,616,896 | 0 | 0 | null | 2016-11-23T21:54:35 | 2016-11-23T21:54:34 | null | UTF-8 | Java | false | false | 9,460 | java | package swComunicacion.views;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JTextArea;
import swComunicacion.Controller;
import swComunicacion.Observer;
public class Opcion2 extends JFrame implements Observer{
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private LinkedList<Boolean> bBotones;
private LinkedList<JButton> botones;
private JPanel contentPane;
private Timer timer;
private JButton btnW;
private JButton btnE;
private JButton btnR;
private JButton btnT;
private JButton btnY;
private JButton btnU;
private JButton btnI;
private JButton btnO;
private JButton btnP;
private JButton btnA;
private JButton btnS;
private JButton btnD;
private JButton btnF;
private JButton btnG;
private JButton btnH;
private JButton btnJ;
private JButton btnK;
private JButton btnL;
private JButton btnEnie;
private JButton btnZ;
private JButton btnX;
private JButton btnC;
private JButton btnV;
private JButton btnB;
private JButton btnN;
private JButton btnM;
private JButton btnEspacio;
private int frecuencia = 500;
private ToolbarSup t;
private Controller c;
public Opcion2(Controller controlador) {
this.c = controlador;
setTitle("Opcion 2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 574, 379);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
botones = new LinkedList<JButton>();
bBotones = new LinkedList<Boolean>();
JPanel panel = new JPanel();
t = new ToolbarSup(c);
contentPane.add(t, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
bBotones.add(true);
for(int i=1; i<29;i++){
bBotones.add(false);
}
textArea = new JTextArea();
textArea.setEditable(true);
textArea.setFocusable(false);
textArea.setBounds(10, 11, 529, 60);
panel.add(textArea);
JButton btnQ = new JButton("Q");
btnQ.setBounds(10, 82, 44, 44);
btnQ.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(0)==true)
textArea.append("q");
if(bBotones.get(1)==true)
textArea.append("w");
if(bBotones.get(2)==true)
textArea.append("e");
if(bBotones.get(3)==true)
textArea.append("r");
if(bBotones.get(4)==true)
textArea.append("t");
if(bBotones.get(5)==true)
textArea.append("y");
if(bBotones.get(6)==true)
textArea.append("u");
if(bBotones.get(7)==true)
textArea.append("i");
if(bBotones.get(8)==true)
textArea.append("o");
if(bBotones.get(9)==true)
textArea.append("p");
if(bBotones.get(10)==true)
textArea.append("a");
if(bBotones.get(11)==true)
textArea.append("s");
if(bBotones.get(12)==true)
textArea.append("d");
if(bBotones.get(13)==true)
textArea.append("f");
if(bBotones.get(14)==true)
textArea.append("g");
if(bBotones.get(15)==true)
textArea.append("h");
if(bBotones.get(16)==true)
textArea.append("j");
if(bBotones.get(17)==true)
textArea.append("k");
if(bBotones.get(18)==true)
textArea.append("l");
if(bBotones.get(19)==true)
textArea.append("\u00D1");
if(bBotones.get(20)==true)
textArea.append("z");
if(bBotones.get(21)==true)
textArea.append("x");
if(bBotones.get(22)==true)
textArea.append("c");
if(bBotones.get(23)==true)
textArea.append("v");
if(bBotones.get(24)==true)
textArea.append("b");
if(bBotones.get(25)==true)
textArea.append("n");
if(bBotones.get(26)==true)
textArea.append("m");
if(bBotones.get(27)==true)
textArea.setText(textArea.getText().substring(0, (textArea.getText().length()-1)));
if(bBotones.get(28)==true){
textArea.append("\u0020");
}
timer.restart();
}
});
panel.add(btnQ);
botones.add(btnQ);
btnW = new JButton("W");
btnW.setBounds(63, 82, 44, 44);
btnW.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(2)==true)
textArea.append("w");
timer.restart();
}
});
panel.add(btnW);
botones.add(btnW);
btnE = new JButton("E");
btnE.setBounds(117, 82, 44, 44);
btnE.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(3)==true)
textArea.append("e");
timer.restart();
}
});
panel.add(btnE);
botones.add(btnE);
btnR = new JButton("R");
btnR.setBounds(171, 82, 44, 44);
btnR.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(4)==true)
textArea.append("r");
timer.restart();
}
});
panel.add(btnR);
botones.add(btnR);
btnT = new JButton("T");
btnT.setBounds(225, 82, 44, 44);
btnT.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(5)==true)
textArea.append("t");
timer.restart();
}
});
panel.add(btnT);
botones.add(btnT);
btnY = new JButton("Y");
btnY.setBounds(279, 82, 44, 44);
btnY.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
timer.stop();
if(bBotones.get(6)==true)
textArea.append("y");
timer.restart();
}
});
panel.add(btnY);
botones.add(btnY);
btnU = new JButton("U");
btnU.setBounds(333, 82, 44, 44);
panel.add(btnU);
botones.add(btnU);
btnI = new JButton("I");
btnI.setBounds(387, 82, 44, 44);
panel.add(btnI);
botones.add(btnI);
btnO = new JButton("O");
btnO.setBounds(441, 82, 44, 44);
panel.add(btnO);
botones.add(btnO);
btnP = new JButton("P");
btnP.setBounds(495, 82, 44, 44);
panel.add(btnP);
botones.add(btnP);
btnA = new JButton("A");
btnA.setBounds(10, 137, 44, 44);
panel.add(btnA);
botones.add(btnA);
btnS = new JButton("S");
btnS.setBounds(62, 137, 44, 44);
panel.add(btnS);
botones.add(btnS);
btnD = new JButton("D");
btnD.setBounds(116, 137, 44, 44);
panel.add(btnD);
botones.add(btnD);
btnF = new JButton("F");
btnF.setBounds(170, 137, 44, 44);
panel.add(btnF);
botones.add(btnF);
btnG = new JButton("G");
btnG.setBounds(224, 137, 44, 44);
panel.add(btnG);
botones.add(btnG);
btnH = new JButton("H");
btnH.setBounds(276, 137, 43, 44);
panel.add(btnH);
botones.add(btnH);
btnJ = new JButton("J");
btnJ.setBounds(327, 137, 44, 44);
panel.add(btnJ);
botones.add(btnJ);
btnK = new JButton("K");
btnK.setBounds(381, 137, 44, 44);
panel.add(btnK);
botones.add(btnK);
btnL = new JButton("L");
btnL.setBounds(435, 137, 44, 44);
panel.add(btnL);
botones.add(btnL);
btnEnie = new JButton("\u00D1");
btnEnie.setBounds(489, 137, 44, 44);
panel.add(btnEnie);
botones.add(btnEnie);
btnZ = new JButton("Z");
btnZ.setBounds(63, 192, 44, 44);
panel.add(btnZ);
botones.add(btnZ);
btnX = new JButton("X");
btnX.setBounds(117, 192, 44, 44);
panel.add(btnX);
botones.add(btnX);
btnC = new JButton("C");
btnC.setBounds(171, 192, 44, 44);
panel.add(btnC);
botones.add(btnC);
btnV = new JButton("V");
btnV.setBounds(225, 192, 44, 44);
panel.add(btnV);
botones.add(btnV);
btnB = new JButton("B");
btnB.setBounds(279, 192, 44, 44);
panel.add(btnB);
botones.add(btnB);
btnN = new JButton("N");
btnN.setBounds(335, 192, 44, 44);
panel.add(btnN);
botones.add(btnN);
btnM = new JButton("M");
btnM.setBounds(389, 192, 44, 44);
panel.add(btnM);
botones.add(btnM);
JButton button = new JButton("BORRAR");
button.setBounds(441, 192, 89, 44);
panel.add(button);
botones.add(button);
System.out.println(botones.size());
btnEspacio = new JButton("ESPACIO");
btnEspacio.setBounds(148, 248, 257, 44);
panel.add(btnEspacio);
this.setVisible(true);
botones.add(btnEspacio);
System.out.println(botones.size());
timer = new Timer (frecuencia, new ActionListener ()
{ int act =0;
public void actionPerformed(ActionEvent e)
{
//bBotones.set(act, true);
for(int i=0; i<botones.size();i++){
if(bBotones.get(i) == true){
botones.get(i).setBackground(Color.GREEN);
bBotones.set(act, false);
act=i+1;
bBotones.set(act, false);
}
else if(bBotones.get(i) == false){
botones.get(i).setBackground(null);
bBotones.set(i, false);
}
}
// bBotones.set(act-1, false);
// if ((act+1)>=29)act=0;
// bBotones.set((act), true);
//bBotones.set(act+1, true);
}
});
timer.start();
//this.btnA.requestFocus();
this.c.addObserver(this);
}
public void onCambioOpcion(boolean opc) {
// TODO Auto-generated method stub
if(!opc)
this.setVisible(false);
}
}
| [
"[email protected]"
]
| |
0200d4ce4b042659b57929ea2b5f526cdf4f9ce0 | 4a33bea299d5eba07d8ec65c26224f781c0a6c89 | /app/src/main/java/com/example/datahajiumroh/Hadits27.java | 16103b0634ab69e1c82e32ff3375921c9e642830 | []
| no_license | SafiraRakhsanda/DataHajiUmroh | 4fcce54a75387ac61887caf12ceb9ec0195d26e7 | 08a333be4fc78132659312f7f2f413c794eee80e | refs/heads/master | 2021-01-16T01:49:23.098187 | 2020-04-11T12:07:01 | 2020-04-11T12:07:01 | 242,931,171 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,987 | java | package com.example.datahajiumroh;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
public class Hadits27 extends AppCompatActivity {
private Context mContext;
private RelativeLayout mRelative;
private Button mButton;
private PopupWindow mPopup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mencari_pertemanan);
mContext = getApplicationContext();
mRelative = findViewById(R.id.rlhadits27);
mButton = findViewById(R.id.tirmidzi2738);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View customView = inflater.inflate(R.layout.hadits27, null);
mPopup = new PopupWindow(
customView,
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
if (Build.VERSION.SDK_INT >= 21) {
mPopup.setElevation(5.0f);
}
ImageButton closeButton = customView.findViewById(R.id.close34);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPopup.dismiss();
}
});
mPopup.showAtLocation(mRelative, Gravity.CENTER, 0, 0);
}
});
}
}
| [
"[email protected]"
]
| |
7002e7fa9f07d9123ce6b8f759cdd6f38dc6bcb4 | a2a1790aa8caa8da2c7f997b6fb0b67d438fa320 | /src/forms/CambiarPasswordForm.java | 25a0c6d86b077c937e817413049da0c0e8874362 | []
| no_license | jelices/PracticaSI3 | 38c451f4bd94f3a02a59d1d73a158d05d70a1806 | 9eb7e049239d5a31e7c10f9408e51aed082d22e7 | refs/heads/master | 2020-05-18T04:28:17.970005 | 2013-10-01T04:53:40 | 2013-10-01T04:53:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,051 | java | package forms;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class CambiarPasswordForm extends ActionForm {
private String passwordPrevio;
private String passwordNuevo;
private String passwordNuevo2;
public String getPasswordPrevio(){
return this.passwordPrevio;
}
public void setPasswordPrevio(String passwordPrevio){
this.passwordPrevio = passwordPrevio;
}
public String getPasswordNuevo(){
return this.passwordNuevo;
}
public void setPasswordNuevo(String passwordNuevo){
this.passwordNuevo = passwordNuevo;
}
public String getPasswordNuevo2(){
return this.passwordNuevo2;
}
public void setPasswordNuevo2(String passwordNuevo2){
this.passwordNuevo2 = passwordNuevo2;
}
public void reset(ActionMapping map, HttpServletRequest req){
this.passwordPrevio = "";
this.passwordNuevo="";
this.passwordNuevo2="";
}
}
| [
"[email protected]"
]
| |
4bdd7093f04a85d95abbebaff7033675cf948698 | c7258b3a2385303764c48565906539c81c420893 | /src/model/ArcZero.java | 2c3c2685d55a667831a747aea3133d0d8ebb9e62 | []
| no_license | xdanielsb/Petri | 25d64628ba5b704b2b6df4471b9fca63559c1005 | 3671e020f4699d26dfc488950704fb277ad5204d | refs/heads/master | 2020-08-04T12:29:42.672602 | 2019-11-26T13:31:18 | 2019-11-26T13:31:18 | 212,137,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 487 | java | package model;
/**
* Class that represents a special Arc whose is crossable,
* if the number of jetons in the place is equal to zero.
* @see Arc
*/
public class ArcZero extends Arc{
public ArcZero(Place _p) {
super(_p);
}
public boolean isCrossable() {
return this.getP().getNumJetons()==0;
}
@Override
public void remove() {
// does not change any state
}
@Override
public String toString() {
String str = "(j = "+this.getP().getNumJetons() +")";
return str;
}
}
| [
"[email protected]"
]
| |
1ddbb05848a9fcd3c628b45add44aa53e6159597 | ef5f867e24bff0033368420aeec9098e11437bad | /nenu-common-api/src/main/java/cn/xiaoyh/service/PeopleClientService.java | 12efeb7d9839adbad900e36c6264386f1f829bd0 | []
| no_license | zhangr648/nenu_lab_system | 1f8131ce58adfdbb9cb0df5a1f19d7bbe95ff606 | 30f6f6f0ee7de9d62865aae5531bfc8435773fcb | refs/heads/dev1.0 | 2023-03-17T07:17:44.055823 | 2021-03-20T11:46:07 | 2021-03-20T11:46:07 | 338,599,625 | 0 | 2 | null | 2021-03-21T02:47:37 | 2021-02-13T15:04:03 | Java | UTF-8 | Java | false | false | 671 | java | package cn.xiaoyh.service;
import cn.xiaoyh.pojo.People;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@FeignClient(value = "PROVIDER-TEST", fallbackFactory = PeopleServiceFallbackFactory.class)
public interface PeopleClientService {
@PostMapping("/people/add")
boolean insertPeople(People people);
@GetMapping("/people/{id}")
People queryById(@PathVariable("id") Long id);
@GetMapping("people/list")
List<People> queryAll();
}
| [
"[email protected]"
]
| |
17436b70669186cbf9c0bcb880723fa547c7b647 | 82b9ac6972aa276479ff106a69ce2dc6cfdf643e | /src/codechef/MARCH18B/Minion_Chef_and_Bananas.java | 047ea83e75789299f487656137b7ecb4cd13df93 | []
| no_license | kiransringeri/Problems | 38846305bd3fb07bc3f8f56e7ee6c738b6bed54c | d2a7544da625f5664bd75b1436cd7fd9cecf7ee6 | refs/heads/master | 2021-07-05T15:08:14.043391 | 2019-04-23T06:03:14 | 2019-04-23T06:03:14 | 121,850,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,144 | java | package codechef.MARCH18B;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
* Problem definition :
* Status : Fine according to me, but codechef gives ERROR
*
* @author kiran
*
*/
public class Minion_Chef_and_Bananas {
public static void main(String[] args) {
/*
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
N ≤ H ≤ 10^9
1 ≤ Ai ≤ 10^9 for each valid i
*/
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for(int a=0; a < t; a++) {
int n = scanner.nextInt();
int h = scanner.nextInt();
int []pile = new int[n];
int maxPileSize = 0;
for(int i=0; i<n; i++) {
pile[i] = scanner.nextInt();
if(pile[i] > maxPileSize)
maxPileSize = pile[i];
}
int val = solve(n, h, pile, maxPileSize);
System.out.println(val);
}
scanner.close();
/*
int t = 10;
long totalTime = 0;
for(int i=0; i < t; i++) {
int n = 100000;
int limit = 1000000000;
Random rand = new Random();
int h = n - 1;
while(h < n) {
h = rand.nextInt(limit);
}
int []pile = new int[n];
int maxPileSize = 0;
for(int j=0; j < n ; j++) {
rand = new Random();
while(pile[j] == 0) {
pile[j] = rand.nextInt(limit);
if(maxPileSize < pile[j])
maxPileSize = pile[j];
}
}
System.out.println("n="+n+", h="+h);
long st = System.currentTimeMillis();
solve(n, h, pile, maxPileSize);
long et = System.currentTimeMillis();
long time = et-st;
totalTime += time;
System.out.println("Test Casse: "+i+", time="+time+" ms");
}
System.out.println("Total time="+totalTime+" ms");
*/
}
private static int solve(int n, int h, int []pile, int maxPileSize) {
if(h == n || n == 1) {
// If number of hours is same as number of piles, then value = items in maximum pile
return maxPileSize;
}else {
Arrays.sort(pile);
int []picks = new int[n];
picks[n-1] = n;
int counter = 0;
for(int i=n-2; i >=0; i--) {
picks[i] = n;
for(int j=i+1; j<n; j++) {
picks[i] += Math.ceil((double)pile[j]/pile[i]) - 1;
}
if(picks[i] > h) {
// The previous one
return pile[i+1];
}else if(picks[i] == h) {
// Current one
return pile[i];
}
counter ++;
// if(counter % 5000 == 0)
// System.out.println("Completed: " + (100*counter/n)+" %");
}
return pile[0];
}
}
}
| [
"[email protected]"
]
| |
a662eb9d9dd273bdb19836ce27af1841d8e485e3 | 8be81d059bda4e490af22324464d8db75e660fd1 | /src/main/java/br/sigo/aplicacao/config/package-info.java | 58de66db8f62e564a84b7c99de4853ba212c185a | []
| no_license | robekson/sigo-new | a402af751c3b6aacf5e07be1f69d6df2dde1c360 | 66800463e42cf6dbf236f30b3dcfdf4b254849e5 | refs/heads/master | 2023-03-28T11:41:14.619952 | 2021-03-30T14:31:13 | 2021-03-30T14:31:13 | 336,265,563 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 83 | java | /**
* Spring Framework configuration files.
*/
package br.sigo.aplicacao.config;
| [
"[email protected]"
]
| |
e7f9586d882d0eaba303525615d937dd3dd85211 | 0b657fbc76dcbb2544b01e8dbbe83e30289c142f | /501/20210318.java | 86edde0b5d2d959fe4c94ada8fae1ef34a00bca4 | []
| no_license | MaCoredroid/leetcode | 68cbd343ea4a99067a497d9c034e5ab1ca3525e6 | 58080590f3a4f4d1f8082474a3ec344b87b18b4d | refs/heads/master | 2022-03-11T07:17:45.908007 | 2022-02-08T01:41:24 | 2022-02-08T01:41:24 | 227,243,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,605 | java | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> ret=new ArrayList<>();
int base,count,maxCount;
public int[] findMode(TreeNode root) {
while(root!=null){
if(root.left==null){
update(root.val);
root=root.right;
}else{
TreeNode rightmost=root.left;
while(rightmost.right!=null&&rightmost.right!=root){
rightmost=rightmost.right;
}
if(rightmost.right==root){
rightmost.right=null;
update(root.val);
root=root.right;
}else{
rightmost.right=root;
root=root.left;
}
}
}
int[] ans=new int[ret.size()];
for(int i=0;i<ret.size();i++){
ans[i]=ret.get(i);
}
return ans;
}
private void update(int val){
if(val!=base){
base=val;
count=1;
}else{
count++;
}
if(count==maxCount){
ret.add(val);
}else if(count>maxCount){
ret=new ArrayList<>();
ret.add(val);
maxCount=count;
}
}
} | [
"[email protected]"
]
| |
bd738d5647f7790fe1bf3cc6f42671cdc7d8fb08 | 780c9c68e7525cfa67a6a0a569b3567101c120fd | /beauty-project/robot/src/main/java/com/meixiang/beauty/webapp/robot/util/MessageUtil.java | 61ff0fd287b70211f4bb9afc357c2e3d38454cb7 | []
| no_license | yuexiadieying/beauty | 4705ab2c2474a15884cbaeaab8ed1a36d44c7244 | 1e0a910eccea47c9edf48704843ba931e8fbf76d | refs/heads/master | 2022-12-23T19:32:26.398543 | 2019-08-01T01:24:45 | 2019-08-01T01:24:45 | 199,824,461 | 0 | 0 | null | 2022-12-16T01:17:21 | 2019-07-31T09:30:40 | HTML | UTF-8 | Java | false | false | 5,110 | java | package com.meixiang.beauty.webapp.robot.util;
import com.meixiang.beauty.sys.entity.Article;
import com.meixiang.beauty.sys.entity.MusicMessage;
import com.meixiang.beauty.sys.entity.NewsMessage;
import com.meixiang.beauty.sys.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MessageUtil {
/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_TEXT = "text";
/**
* 返回消息类型:文本
*/
public static final String RESP_MESSAGE_TYPE_VIEW = "VIEW";
/**
* 返回消息类型:音乐
*/
public static final String RESP_MESSAGE_TYPE_MUSIC = "music";
/**
* 返回消息类型:图文
*/
public static final String RESP_MESSAGE_TYPE_NEWS = "news";
/**
* 请求消息类型:文本
*/
public static final String REQ_MESSAGE_TYPE_TEXT = "text";
/**
* 请求消息类型:图片
*/
public static final String REQ_MESSAGE_TYPE_IMAGE = "image";
/**
* 请求消息类型:链接
*/
public static final String REQ_MESSAGE_TYPE_LINK = "link";
/**
* 请求消息类型:地理位置
*/
public static final String REQ_MESSAGE_TYPE_LOCATION = "LOCATION";
/**
* 请求消息类型:音频
*/
public static final String REQ_MESSAGE_TYPE_VOICE = "voice";
/**
* 请求消息类型:推送
*/
public static final String REQ_MESSAGE_TYPE_EVENT = "event";
/**
* 事件类型:subscribe(订阅)
*/
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
/**
* 事件类型:unsubscribe(取消订阅)
*/
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
/**
* 事件类型:CLICK(自定义菜单点击事件)
*/
public static final String EVENT_TYPE_CLICK = "CLICK";
/**
* 转发给多客服
* */
public static final String TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service";
/**
* 二维码用户已关注时的事件推送
* */
public static final String EVENT_TYPE_SCAN = "SCAN";
/**
* 事件类型:subscribe(订阅)
*/
public static final String SCAN = "SCAN";
/**
* 多客服会话结束事件
* */
public static final String KF_CLOSE = "kf_close_session";
/**
* 点击菜单链接
* */
public static final String EVENT_TYPE_VIEW = "VIEW";
/**
* 解析微信发来的请求(XML)
*
* @param request
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 将解析结果存储在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 从request中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList)
map.put(e.getName(), e.getText());
// 释放资源
inputStream.close();
inputStream = null;
return map;
}
/**
* 文本消息对象转换成xml
*
* @param textMessage 文本消息对象
* @return xml
*/
public static String textMessageToXml(TextMessage textMessage) {
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 音乐消息对象转换成xml
*
* @param musicMessage 音乐消息对象
* @return xml
*/
public static String musicMessageToXml(MusicMessage musicMessage) {
xstream.alias("xml", musicMessage.getClass());
return xstream.toXML(musicMessage);
}
/**
* 图文消息对象转换成xml
*
* @param newsMessage 图文消息对象
* @return xml
*/
public static String newsMessageToXml(NewsMessage newsMessage) {
xstream.alias("xml", newsMessage.getClass());
xstream.alias("item", new Article().getClass());
return xstream.toXML(newsMessage);
}
/**
* 扩展xstream,使其支持CDATA块
*
* @date 2015-11-04
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
}
| [
"[email protected]"
]
| |
90ddda78bf1ec810fbdf34e3a8c6ed75fd5a9c9f | 7a24c3df8915b105a7607fd7f7e9201ac8b7e4b7 | /components/org.wso2.carbon.das.jobmanager.core/src/gen/java/org/wso2/carbon/das/jobmanager/core/model/InterfaceConfig.java | e1b39eacfd7a1b60cb80068df22bbca582f46a51 | [
"Apache-2.0"
]
| permissive | NisalaNiroshana/carbon-analytics | 7788de0a0f237d31cfcbf6e415ed86657d8e5054 | 39667711453717f856b9cbefb363af3c0c3a9d46 | refs/heads/master | 2018-09-11T16:58:13.210048 | 2017-11-23T16:27:12 | 2017-11-23T16:27:12 | 111,830,601 | 0 | 0 | Apache-2.0 | 2018-06-05T13:21:32 | 2017-11-23T16:27:14 | JavaScript | UTF-8 | Java | false | false | 3,243 | java | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.das.jobmanager.core.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Represents a HTTP Interface configuration which consists of host and port of the node.
*/
@ApiModel(description = "Represents a HTTP Interface configuration which consists of host and port of the node.")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaMSF4JServerCodegen", date = "2017-10-23T12:20:42.963Z")
public class InterfaceConfig {
@JsonProperty("host")
private String host = null;
@JsonProperty("port")
private Integer port = null;
public InterfaceConfig host(String host) {
this.host = host;
return this;
}
/**
* Get host
*
* @return host
**/
@ApiModelProperty(required = true, value = "")
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public InterfaceConfig port(Integer port) {
this.port = port;
return this;
}
/**
* Get port
*
* @return port
**/
@ApiModelProperty(required = true, value = "")
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InterfaceConfig interfaceConfig = (InterfaceConfig) o;
return Objects.equals(this.host, interfaceConfig.host) &&
Objects.equals(this.port, interfaceConfig.port);
}
@Override
public int hashCode() {
return Objects.hash(host, port);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InterfaceConfig {\n");
sb.append(" host: ").append(toIndentedString(host)).append("\n");
sb.append(" port: ").append(toIndentedString(port)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
]
| |
433ff269a6bebe39b2b765aa5ddb95673f6f37c7 | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /ant_cluster/9110/tar_0.java | 87bf8a20b693c4f45e6cb9b56968ff93f2bf3721 | []
| no_license | martinezmatias/GenPat-data-C3 | 63cfe27efee2946831139747e6c20cf952f1d6f6 | b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4 | refs/heads/master | 2022-04-25T17:59:03.905613 | 2020-04-15T14:41:34 | 2020-04-15T14:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 36,926 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.taskdefs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.MagicNames;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.compilers.CompilerAdapter;
import org.apache.tools.ant.taskdefs.compilers.CompilerAdapterFactory;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.JavaEnvUtils;
import org.apache.tools.ant.util.SourceFileScanner;
import org.apache.tools.ant.util.facade.FacadeTaskHelper;
/**
* Compiles Java source files. This task can take the following
* arguments:
* <ul>
* <li>sourcedir
* <li>destdir
* <li>deprecation
* <li>classpath
* <li>bootclasspath
* <li>extdirs
* <li>optimize
* <li>debug
* <li>encoding
* <li>target
* <li>depend
* <li>verbose
* <li>failonerror
* <li>includeantruntime
* <li>includejavaruntime
* <li>source
* <li>compiler
* </ul>
* Of these arguments, the <b>sourcedir</b> and <b>destdir</b> are required.
* <p>
* When this task executes, it will recursively scan the sourcedir and
* destdir looking for Java source files to compile. This task makes its
* compile decision based on timestamp.
*
*
* @since Ant 1.1
*
* @ant.task category="java"
*/
public class Javac extends MatchingTask {
private static final String FAIL_MSG
= "Compile failed; see the compiler error output for details.";
private static final String JAVAC16 = "javac1.6";
private static final String JAVAC15 = "javac1.5";
private static final String JAVAC14 = "javac1.4";
private static final String JAVAC13 = "javac1.3";
private static final String JAVAC12 = "javac1.2";
private static final String JAVAC11 = "javac1.1";
private static final String MODERN = "modern";
private static final String CLASSIC = "classic";
private static final String EXTJAVAC = "extJavac";
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private Path src;
private File destDir;
private Path compileClasspath;
private Path compileSourcepath;
private String encoding;
private boolean debug = false;
private boolean optimize = false;
private boolean deprecation = false;
private boolean depend = false;
private boolean verbose = false;
private String targetAttribute;
private Path bootclasspath;
private Path extdirs;
private Boolean includeAntRuntime;
private boolean includeJavaRuntime = false;
private boolean fork = false;
private String forkedExecutable = null;
private boolean nowarn = false;
private String memoryInitialSize;
private String memoryMaximumSize;
private FacadeTaskHelper facade = null;
// CheckStyle:VisibilityModifier OFF - bc
protected boolean failOnError = true;
protected boolean listFiles = false;
protected File[] compileList = new File[0];
private Map/*<String,Long>*/ packageInfos = new HashMap();
// CheckStyle:VisibilityModifier ON
private String source;
private String debugLevel;
private File tmpDir;
private String updatedProperty;
private String errorProperty;
private boolean taskSuccess = true; // assume the best
private boolean includeDestClasses = true;
private CompilerAdapter nestedAdapter = null;
/**
* Javac task for compilation of Java files.
*/
public Javac() {
facade = new FacadeTaskHelper(assumedJavaVersion());
}
private String assumedJavaVersion() {
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_4)) {
return JAVAC14;
} else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_5)) {
return JAVAC15;
} else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_6)) {
return JAVAC16;
} else {
return CLASSIC;
}
}
/**
* Get the value of debugLevel.
* @return value of debugLevel.
*/
public String getDebugLevel() {
return debugLevel;
}
/**
* Keyword list to be appended to the -g command-line switch.
*
* This will be ignored by all implementations except modern
* and classic(ver >= 1.2). Legal values are none or a
* comma-separated list of the following keywords: lines, vars,
* and source. If debuglevel is not specified, by default, :none
* will be appended to -g. If debug is not turned on, this attribute
* will be ignored.
*
* @param v Value to assign to debugLevel.
*/
public void setDebugLevel(String v) {
this.debugLevel = v;
}
/**
* Get the value of source.
* @return value of source.
*/
public String getSource() {
return source != null
? source : getProject().getProperty(MagicNames.BUILD_JAVAC_SOURCE);
}
/**
* Value of the -source command-line switch; will be ignored by
* all implementations except modern, jikes and gcj (gcj uses
* -fsource).
*
* <p>If you use this attribute together with jikes or gcj, you
* must make sure that your version of jikes supports the -source
* switch.</p>
*
* <p>Legal values are 1.3, 1.4, 1.5, and 5 - by default, no
* -source argument will be used at all.</p>
*
* @param v Value to assign to source.
*/
public void setSource(String v) {
this.source = v;
}
/**
* Adds a path for source compilation.
*
* @return a nested src element.
*/
public Path createSrc() {
if (src == null) {
src = new Path(getProject());
}
return src.createPath();
}
/**
* Recreate src.
*
* @return a nested src element.
*/
protected Path recreateSrc() {
src = null;
return createSrc();
}
/**
* Set the source directories to find the source Java files.
* @param srcDir the source directories as a path
*/
public void setSrcdir(Path srcDir) {
if (src == null) {
src = srcDir;
} else {
src.append(srcDir);
}
}
/**
* Gets the source dirs to find the source java files.
* @return the source directories as a path
*/
public Path getSrcdir() {
return src;
}
/**
* Set the destination directory into which the Java source
* files should be compiled.
* @param destDir the destination director
*/
public void setDestdir(File destDir) {
this.destDir = destDir;
}
/**
* Gets the destination directory into which the java source files
* should be compiled.
* @return the destination directory
*/
public File getDestdir() {
return destDir;
}
/**
* Set the sourcepath to be used for this compilation.
* @param sourcepath the source path
*/
public void setSourcepath(Path sourcepath) {
if (compileSourcepath == null) {
compileSourcepath = sourcepath;
} else {
compileSourcepath.append(sourcepath);
}
}
/**
* Gets the sourcepath to be used for this compilation.
* @return the source path
*/
public Path getSourcepath() {
return compileSourcepath;
}
/**
* Adds a path to sourcepath.
* @return a sourcepath to be configured
*/
public Path createSourcepath() {
if (compileSourcepath == null) {
compileSourcepath = new Path(getProject());
}
return compileSourcepath.createPath();
}
/**
* Adds a reference to a source path defined elsewhere.
* @param r a reference to a source path
*/
public void setSourcepathRef(Reference r) {
createSourcepath().setRefid(r);
}
/**
* Set the classpath to be used for this compilation.
*
* @param classpath an Ant Path object containing the compilation classpath.
*/
public void setClasspath(Path classpath) {
if (compileClasspath == null) {
compileClasspath = classpath;
} else {
compileClasspath.append(classpath);
}
}
/**
* Gets the classpath to be used for this compilation.
* @return the class path
*/
public Path getClasspath() {
return compileClasspath;
}
/**
* Adds a path to the classpath.
* @return a class path to be configured
*/
public Path createClasspath() {
if (compileClasspath == null) {
compileClasspath = new Path(getProject());
}
return compileClasspath.createPath();
}
/**
* Adds a reference to a classpath defined elsewhere.
* @param r a reference to a classpath
*/
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
/**
* Sets the bootclasspath that will be used to compile the classes
* against.
* @param bootclasspath a path to use as a boot class path (may be more
* than one)
*/
public void setBootclasspath(Path bootclasspath) {
if (this.bootclasspath == null) {
this.bootclasspath = bootclasspath;
} else {
this.bootclasspath.append(bootclasspath);
}
}
/**
* Gets the bootclasspath that will be used to compile the classes
* against.
* @return the boot path
*/
public Path getBootclasspath() {
return bootclasspath;
}
/**
* Adds a path to the bootclasspath.
* @return a path to be configured
*/
public Path createBootclasspath() {
if (bootclasspath == null) {
bootclasspath = new Path(getProject());
}
return bootclasspath.createPath();
}
/**
* Adds a reference to a classpath defined elsewhere.
* @param r a reference to a classpath
*/
public void setBootClasspathRef(Reference r) {
createBootclasspath().setRefid(r);
}
/**
* Sets the extension directories that will be used during the
* compilation.
* @param extdirs a path
*/
public void setExtdirs(Path extdirs) {
if (this.extdirs == null) {
this.extdirs = extdirs;
} else {
this.extdirs.append(extdirs);
}
}
/**
* Gets the extension directories that will be used during the
* compilation.
* @return the extension directories as a path
*/
public Path getExtdirs() {
return extdirs;
}
/**
* Adds a path to extdirs.
* @return a path to be configured
*/
public Path createExtdirs() {
if (extdirs == null) {
extdirs = new Path(getProject());
}
return extdirs.createPath();
}
/**
* If true, list the source files being handed off to the compiler.
* @param list if true list the source files
*/
public void setListfiles(boolean list) {
listFiles = list;
}
/**
* Get the listfiles flag.
* @return the listfiles flag
*/
public boolean getListfiles() {
return listFiles;
}
/**
* Indicates whether the build will continue
* even if there are compilation errors; defaults to true.
* @param fail if true halt the build on failure
*/
public void setFailonerror(boolean fail) {
failOnError = fail;
}
/**
* @ant.attribute ignore="true"
* @param proceed inverse of failoferror
*/
public void setProceed(boolean proceed) {
failOnError = !proceed;
}
/**
* Gets the failonerror flag.
* @return the failonerror flag
*/
public boolean getFailonerror() {
return failOnError;
}
/**
* Indicates whether source should be
* compiled with deprecation information; defaults to off.
* @param deprecation if true turn on deprecation information
*/
public void setDeprecation(boolean deprecation) {
this.deprecation = deprecation;
}
/**
* Gets the deprecation flag.
* @return the deprecation flag
*/
public boolean getDeprecation() {
return deprecation;
}
/**
* The initial size of the memory for the underlying VM
* if javac is run externally; ignored otherwise.
* Defaults to the standard VM memory setting.
* (Examples: 83886080, 81920k, or 80m)
* @param memoryInitialSize string to pass to VM
*/
public void setMemoryInitialSize(String memoryInitialSize) {
this.memoryInitialSize = memoryInitialSize;
}
/**
* Gets the memoryInitialSize flag.
* @return the memoryInitialSize flag
*/
public String getMemoryInitialSize() {
return memoryInitialSize;
}
/**
* The maximum size of the memory for the underlying VM
* if javac is run externally; ignored otherwise.
* Defaults to the standard VM memory setting.
* (Examples: 83886080, 81920k, or 80m)
* @param memoryMaximumSize string to pass to VM
*/
public void setMemoryMaximumSize(String memoryMaximumSize) {
this.memoryMaximumSize = memoryMaximumSize;
}
/**
* Gets the memoryMaximumSize flag.
* @return the memoryMaximumSize flag
*/
public String getMemoryMaximumSize() {
return memoryMaximumSize;
}
/**
* Set the Java source file encoding name.
* @param encoding the source file encoding
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Gets the java source file encoding name.
* @return the source file encoding name
*/
public String getEncoding() {
return encoding;
}
/**
* Indicates whether source should be compiled
* with debug information; defaults to off.
* @param debug if true compile with debug information
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Gets the debug flag.
* @return the debug flag
*/
public boolean getDebug() {
return debug;
}
/**
* If true, compiles with optimization enabled.
* @param optimize if true compile with optimization enabled
*/
public void setOptimize(boolean optimize) {
this.optimize = optimize;
}
/**
* Gets the optimize flag.
* @return the optimize flag
*/
public boolean getOptimize() {
return optimize;
}
/**
* Enables dependency-tracking for compilers
* that support this (jikes and classic).
* @param depend if true enable dependency-tracking
*/
public void setDepend(boolean depend) {
this.depend = depend;
}
/**
* Gets the depend flag.
* @return the depend flag
*/
public boolean getDepend() {
return depend;
}
/**
* If true, asks the compiler for verbose output.
* @param verbose if true, asks the compiler for verbose output
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* Gets the verbose flag.
* @return the verbose flag
*/
public boolean getVerbose() {
return verbose;
}
/**
* Sets the target VM that the classes will be compiled for. Valid
* values depend on the compiler, for jdk 1.4 the valid values are
* "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "5" and "6".
* @param target the target VM
*/
public void setTarget(String target) {
this.targetAttribute = target;
}
/**
* Gets the target VM that the classes will be compiled for.
* @return the target VM
*/
public String getTarget() {
return targetAttribute != null
? targetAttribute
: getProject().getProperty(MagicNames.BUILD_JAVAC_TARGET);
}
/**
* If true, includes Ant's own classpath in the classpath.
* @param include if true, includes Ant's own classpath in the classpath
*/
public void setIncludeantruntime(boolean include) {
includeAntRuntime = Boolean.valueOf(include);
}
/**
* Gets whether or not the ant classpath is to be included in the classpath.
* @return whether or not the ant classpath is to be included in the classpath
*/
public boolean getIncludeantruntime() {
return includeAntRuntime != null ? includeAntRuntime.booleanValue() : true;
}
/**
* If true, includes the Java runtime libraries in the classpath.
* @param include if true, includes the Java runtime libraries in the classpath
*/
public void setIncludejavaruntime(boolean include) {
includeJavaRuntime = include;
}
/**
* Gets whether or not the java runtime should be included in this
* task's classpath.
* @return the includejavaruntime attribute
*/
public boolean getIncludejavaruntime() {
return includeJavaRuntime;
}
/**
* If true, forks the javac compiler.
*
* @param f "true|false|on|off|yes|no"
*/
public void setFork(boolean f) {
fork = f;
}
/**
* Sets the name of the javac executable.
*
* <p>Ignored unless fork is true or extJavac has been specified
* as the compiler.</p>
* @param forkExec the name of the executable
*/
public void setExecutable(String forkExec) {
forkedExecutable = forkExec;
}
/**
* The value of the executable attribute, if any.
*
* @since Ant 1.6
* @return the name of the java executable
*/
public String getExecutable() {
return forkedExecutable;
}
/**
* Is this a forked invocation of JDK's javac?
* @return true if this is a forked invocation
*/
public boolean isForkedJavac() {
return fork || EXTJAVAC.equalsIgnoreCase(getCompiler());
}
/**
* The name of the javac executable to use in fork-mode.
*
* <p>This is either the name specified with the executable
* attribute or the full path of the javac compiler of the VM Ant
* is currently running in - guessed by Ant.</p>
*
* <p>You should <strong>not</strong> invoke this method if you
* want to get the value of the executable command - use {@link
* #getExecutable getExecutable} for this.</p>
* @return the name of the javac executable
*/
public String getJavacExecutable() {
if (forkedExecutable == null && isForkedJavac()) {
forkedExecutable = getSystemJavac();
} else if (forkedExecutable != null && !isForkedJavac()) {
forkedExecutable = null;
}
return forkedExecutable;
}
/**
* If true, enables the -nowarn option.
* @param flag if true, enable the -nowarn option
*/
public void setNowarn(boolean flag) {
this.nowarn = flag;
}
/**
* Should the -nowarn option be used.
* @return true if the -nowarn option should be used
*/
public boolean getNowarn() {
return nowarn;
}
/**
* Adds an implementation specific command-line argument.
* @return a ImplementationSpecificArgument to be configured
*/
public ImplementationSpecificArgument createCompilerArg() {
ImplementationSpecificArgument arg =
new ImplementationSpecificArgument();
facade.addImplementationArgument(arg);
return arg;
}
/**
* Get the additional implementation specific command line arguments.
* @return array of command line arguments, guaranteed to be non-null.
*/
public String[] getCurrentCompilerArgs() {
String chosen = facade.getExplicitChoice();
try {
// make sure facade knows about magic properties and fork setting
String appliedCompiler = getCompiler();
facade.setImplementation(appliedCompiler);
String[] result = facade.getArgs();
String altCompilerName = getAltCompilerName(facade.getImplementation());
if (result.length == 0 && altCompilerName != null) {
facade.setImplementation(altCompilerName);
result = facade.getArgs();
}
return result;
} finally {
facade.setImplementation(chosen);
}
}
private String getAltCompilerName(String anImplementation) {
if (JAVAC16.equalsIgnoreCase(anImplementation)
|| JAVAC15.equalsIgnoreCase(anImplementation)
|| JAVAC14.equalsIgnoreCase(anImplementation)
|| JAVAC13.equalsIgnoreCase(anImplementation)) {
return MODERN;
}
if (JAVAC12.equalsIgnoreCase(anImplementation)
|| JAVAC11.equalsIgnoreCase(anImplementation)) {
return CLASSIC;
}
if (MODERN.equalsIgnoreCase(anImplementation)) {
String nextSelected = assumedJavaVersion();
if (JAVAC16.equalsIgnoreCase(nextSelected)
|| JAVAC15.equalsIgnoreCase(nextSelected)
|| JAVAC14.equalsIgnoreCase(nextSelected)
|| JAVAC13.equalsIgnoreCase(nextSelected)) {
return nextSelected;
}
}
if (CLASSIC.equalsIgnoreCase(anImplementation)) {
return assumedJavaVersion();
}
if (EXTJAVAC.equalsIgnoreCase(anImplementation)) {
return assumedJavaVersion();
}
return null;
}
/**
* Where Ant should place temporary files.
*
* @since Ant 1.6
* @param tmpDir the temporary directory
*/
public void setTempdir(File tmpDir) {
this.tmpDir = tmpDir;
}
/**
* Where Ant should place temporary files.
*
* @since Ant 1.6
* @return the temporary directory
*/
public File getTempdir() {
return tmpDir;
}
/**
* The property to set on compliation success.
* This property will not be set if the compilation
* fails, or if there are no files to compile.
* @param updatedProperty the property name to use.
* @since Ant 1.7.1.
*/
public void setUpdatedProperty(String updatedProperty) {
this.updatedProperty = updatedProperty;
}
/**
* The property to set on compliation failure.
* This property will be set if the compilation
* fails.
* @param errorProperty the property name to use.
* @since Ant 1.7.1.
*/
public void setErrorProperty(String errorProperty) {
this.errorProperty = errorProperty;
}
/**
* This property controls whether to include the
* destination classes directory in the classpath
* given to the compiler.
* The default value is "true".
* @param includeDestClasses the value to use.
*/
public void setIncludeDestClasses(boolean includeDestClasses) {
this.includeDestClasses = includeDestClasses;
}
/**
* Get the value of the includeDestClasses property.
* @return the value.
*/
public boolean isIncludeDestClasses() {
return includeDestClasses;
}
/**
* Get the result of the javac task (success or failure).
* @return true if compilation succeeded, or
* was not neccessary, false if the compilation failed.
*/
public boolean getTaskSuccess() {
return taskSuccess;
}
/**
* The classpath to use when loading the compiler implementation
* if it is not a built-in one.
*
* @since Ant 1.8.0
*/
public Path createCompilerClasspath() {
return facade.getImplementationClasspath(getProject());
}
/**
* Set the compiler adapter explicitly.
* @since Ant 1.8.0
*/
public void add(CompilerAdapter adapter) {
if (nestedAdapter != null) {
throw new BuildException("Can't have more than one compiler"
+ " adapter");
}
nestedAdapter = adapter;
}
/**
* Executes the task.
* @exception BuildException if an error occurs
*/
public void execute() throws BuildException {
checkParameters();
resetFileLists();
// scan source directories and dest directory to build up
// compile lists
String[] list = src.list();
for (int i = 0; i < list.length; i++) {
File srcDir = getProject().resolveFile(list[i]);
if (!srcDir.exists()) {
throw new BuildException("srcdir \""
+ srcDir.getPath()
+ "\" does not exist!", getLocation());
}
DirectoryScanner ds = this.getDirectoryScanner(srcDir);
String[] files = ds.getIncludedFiles();
scanDir(srcDir, destDir != null ? destDir : srcDir, files);
}
compile();
if (updatedProperty != null
&& taskSuccess
&& compileList.length != 0) {
getProject().setNewProperty(updatedProperty, "true");
}
}
/**
* Clear the list of files to be compiled and copied..
*/
protected void resetFileLists() {
compileList = new File[0];
packageInfos = new HashMap();
}
/**
* Scans the directory looking for source files to be compiled.
* The results are returned in the class variable compileList
*
* @param srcDir The source directory
* @param destDir The destination directory
* @param files An array of filenames
*/
protected void scanDir(File srcDir, File destDir, String[] files) {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("*.java");
m.setTo("*.class");
SourceFileScanner sfs = new SourceFileScanner(this);
File[] newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m);
if (newFiles.length > 0) {
lookForPackageInfos(srcDir, newFiles);
File[] newCompileList
= new File[compileList.length + newFiles.length];
System.arraycopy(compileList, 0, newCompileList, 0,
compileList.length);
System.arraycopy(newFiles, 0, newCompileList,
compileList.length, newFiles.length);
compileList = newCompileList;
}
}
/**
* Gets the list of files to be compiled.
* @return the list of files as an array
*/
public File[] getFileList() {
return compileList;
}
/**
* Is the compiler implementation a jdk compiler
*
* @param compilerImpl the name of the compiler implementation
* @return true if compilerImpl is "modern", "classic",
* "javac1.1", "javac1.2", "javac1.3", "javac1.4", "javac1.5" or
* "javac1.6".
*/
protected boolean isJdkCompiler(String compilerImpl) {
return MODERN.equals(compilerImpl)
|| CLASSIC.equals(compilerImpl)
|| JAVAC16.equals(compilerImpl)
|| JAVAC15.equals(compilerImpl)
|| JAVAC14.equals(compilerImpl)
|| JAVAC13.equals(compilerImpl)
|| JAVAC12.equals(compilerImpl)
|| JAVAC11.equals(compilerImpl);
}
/**
* @return the executable name of the java compiler
*/
protected String getSystemJavac() {
return JavaEnvUtils.getJdkExecutable("javac");
}
/**
* Choose the implementation for this particular task.
* @param compiler the name of the compiler
* @since Ant 1.5
*/
public void setCompiler(String compiler) {
facade.setImplementation(compiler);
}
/**
* The implementation for this particular task.
*
* <p>Defaults to the build.compiler property but can be overridden
* via the compiler and fork attributes.</p>
*
* <p>If fork has been set to true, the result will be extJavac
* and not classic or java1.2 - no matter what the compiler
* attribute looks like.</p>
*
* @see #getCompilerVersion
* @return the compiler.
* @since Ant 1.5
*/
public String getCompiler() {
String compilerImpl = getCompilerVersion();
if (fork) {
if (isJdkCompiler(compilerImpl)) {
compilerImpl = EXTJAVAC;
} else {
log("Since compiler setting isn't classic or modern, "
+ "ignoring fork setting.", Project.MSG_WARN);
}
}
return compilerImpl;
}
/**
* The implementation for this particular task.
*
* <p>Defaults to the build.compiler property but can be overridden
* via the compiler attribute.</p>
*
* <p>This method does not take the fork attribute into
* account.</p>
*
* @see #getCompiler
* @return the compiler.
*
* @since Ant 1.5
*/
public String getCompilerVersion() {
facade.setMagicValue(getProject().getProperty("build.compiler"));
return facade.getImplementation();
}
/**
* Check that all required attributes have been set and nothing
* silly has been entered.
*
* @since Ant 1.5
* @exception BuildException if an error occurs
*/
protected void checkParameters() throws BuildException {
if (src == null) {
throw new BuildException("srcdir attribute must be set!",
getLocation());
}
if (src.size() == 0) {
throw new BuildException("srcdir attribute must be set!",
getLocation());
}
if (destDir != null && !destDir.isDirectory()) {
throw new BuildException("destination directory \""
+ destDir
+ "\" does not exist "
+ "or is not a directory", getLocation());
}
if (includeAntRuntime == null && getProject().getProperty("build.sysclasspath") == null) {
log(getLocation() + "warning: 'includeantruntime' was not set, " +
"defaulting to build.sysclasspath=last; set to false for repeatable builds",
Project.MSG_WARN);
}
}
/**
* Perform the compilation.
*
* @since Ant 1.5
*/
protected void compile() {
String compilerImpl = getCompiler();
if (compileList.length > 0) {
log("Compiling " + compileList.length + " source file"
+ (compileList.length == 1 ? "" : "s")
+ (destDir != null ? " to " + destDir : ""));
if (listFiles) {
for (int i = 0; i < compileList.length; i++) {
String filename = compileList[i].getAbsolutePath();
log(filename);
}
}
CompilerAdapter adapter =
nestedAdapter != null ? nestedAdapter :
CompilerAdapterFactory.getCompiler(compilerImpl, this,
createCompilerClasspath());
// now we need to populate the compiler adapter
adapter.setJavac(this);
// finally, lets execute the compiler!!
if (adapter.execute()) {
// Success
try {
generateMissingPackageInfoClasses();
} catch (IOException x) {
// Should this be made a nonfatal warning?
throw new BuildException(x, getLocation());
}
} else {
// Fail path
this.taskSuccess = false;
if (errorProperty != null) {
getProject().setNewProperty(
errorProperty, "true");
}
if (failOnError) {
throw new BuildException(FAIL_MSG, getLocation());
} else {
log(FAIL_MSG, Project.MSG_ERR);
}
}
}
}
/**
* Adds an "compiler" attribute to Commandline$Attribute used to
* filter command line attributes based on the current
* implementation.
*/
public class ImplementationSpecificArgument extends
org.apache.tools.ant.util.facade.ImplementationSpecificArgument {
/**
* @param impl the name of the compiler
*/
public void setCompiler(String impl) {
super.setImplementation(impl);
}
}
private void lookForPackageInfos(File srcDir, File[] newFiles) {
for (int i = 0; i < newFiles.length; i++) {
File f = newFiles[i];
if (!f.getName().equals("package-info.java")) {
continue;
}
String path = FILE_UTILS.removeLeadingPath(srcDir, f).
replace(File.separatorChar, '/');
String suffix = "/package-info.java";
if (!path.endsWith(suffix)) {
log("anomalous package-info.java path: " + path, Project.MSG_WARN);
continue;
}
String pkg = path.substring(0, path.length() - suffix.length());
packageInfos.put(pkg, new Long(f.lastModified()));
}
}
/**
* Ensure that every {@code package-info.java} produced a {@code package-info.class}.
* Otherwise this task's up-to-date tracking mechanisms do not work.
* @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=43114">Bug #43114</a>
*/
private void generateMissingPackageInfoClasses() throws IOException {
for (Iterator i = packageInfos.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
String pkg = (String) entry.getKey();
Long sourceLastMod = (Long) entry.getValue();
File pkgBinDir = new File(destDir, pkg.replace('/', File.separatorChar));
pkgBinDir.mkdirs();
File pkgInfoClass = new File(pkgBinDir, "package-info.class");
if (pkgInfoClass.isFile() && pkgInfoClass.lastModified() >= sourceLastMod.longValue()) {
continue;
}
log("Creating empty " + pkgInfoClass);
OutputStream os = new FileOutputStream(pkgInfoClass);
try {
os.write(PACKAGE_INFO_CLASS_HEADER);
byte[] name = pkg.getBytes("UTF-8");
int length = name.length + /* "/package-info" */ 13;
os.write((byte) length / 256);
os.write((byte) length % 256);
os.write(name);
os.write(PACKAGE_INFO_CLASS_FOOTER);
} finally {
os.close();
}
}
}
private static final byte[] PACKAGE_INFO_CLASS_HEADER = {
(byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe, 0x00, 0x00, 0x00,
0x31, 0x00, 0x07, 0x07, 0x00, 0x05, 0x07, 0x00, 0x06, 0x01, 0x00, 0x0a,
0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x46, 0x69, 0x6c, 0x65, 0x01, 0x00,
0x11, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x69, 0x6e, 0x66,
0x6f, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x01
};
private static final byte[] PACKAGE_INFO_CLASS_FOOTER = {
0x2f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x2d, 0x69, 0x6e, 0x66,
0x6f, 0x01, 0x00, 0x10, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e,
0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x02, 0x00, 0x00, 0x01,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03,
0x00, 0x00, 0x00, 0x02, 0x00, 0x04
};
}
| [
"[email protected]"
]
| |
97f02543d1b0fc721f3ca2ece6f36baad1fa2e07 | c511b7852f9eb5b889893ad529e78ff5f0b0d9ee | /app/src/main/java/com/free/blog/library/util/JsoupUtils.java | 598a3145a4123a979728b5a8e04f29efc4f80a6d | []
| no_license | jiubadao/FreeCsdn | dbbb4735b915f9ec3c4d794ee892ae6e8a575713 | 4e04e569166797878648ce8361c9297ed90225cc | refs/heads/master | 2021-06-18T16:28:13.809642 | 2017-06-29T15:20:59 | 2017-06-29T15:20:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,631 | java | package com.free.blog.library.util;
import android.text.TextUtils;
import com.free.blog.library.config.Config;
import com.free.blog.model.entity.BlogCategory;
import com.free.blog.model.entity.BlogColumn;
import com.free.blog.model.entity.BlogItem;
import com.free.blog.model.entity.BlogRank;
import com.free.blog.model.entity.Blogger;
import com.free.blog.model.entity.Comment;
import com.free.blog.model.entity.RankItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
/**
* 网页解析
*
* @author tangqi
* @since 2015年8月9日下午08:09:57
*/
public class JsoupUtils {
private static final String BLOG_URL = "http://blog.csdn.net";
public static Blogger getBlogger(String html) {
if (TextUtils.isEmpty(html)) {
return null;
}
Document doc = Jsoup.parse(html);
String str;
try {
str = doc.getElementById("blog_userface").select("a").select("img").attr("src");
} catch (Exception e) {
e.printStackTrace();
str = "";
}
Elements headerElement = doc.getElementsByClass("header");
String title = headerElement.select("h2").text();
String description = headerElement.select("h3").text();
String imgUrl = str;
if (TextUtils.isEmpty(title)) {
return null;
}
Blogger blogger = new Blogger();
blogger.setTitle(title);
blogger.setDescription(description);
blogger.setImgUrl(imgUrl);
return blogger;
}
public static List<BlogItem> getBlogList(String category, String html, List<BlogCategory>
blogCategoryList) {
List<BlogItem> list = new ArrayList<>();
Document doc = Jsoup.parse(html);
Elements blogList = doc.getElementsByClass("article_item");
String page = doc.getElementsByClass("pagelist").select("span").text().trim();
int totalPage = getBlogTotalPage(page);
for (Element blogItem : blogList) {
BlogItem item = new BlogItem();
String title = blogItem.select("h1").text();
String icoType = blogItem.getElementsByClass("ico").get(0).className();
if (title.contains("置顶")) {
item.setTopFlag(1);
}
String description = blogItem.select("div.article_description").text();
String date = blogItem.getElementsByClass("article_manage").get(0).text();
String link = BLOG_URL + blogItem.select("h1").select("a").attr("href");
item.setTitle(title);
item.setContent(description);
item.setDate(date);
item.setLink(link);
item.setTotalPage(totalPage);
item.setCategory(category);
item.setIcoType(icoType);
list.add(item);
}
// Blog category
Elements panelElements = doc.getElementsByClass("panel");
for (Element panelElement : panelElements) {
try {
String panelHead = panelElement.select("ul.panel_head").text();
if ("文章分类".equals(panelHead)) {
Elements categoryElements = panelElement.select("ul.panel_body").select("li");
if (categoryElements != null) {
blogCategoryList.clear();
BlogCategory allBlogCategory = new BlogCategory();
allBlogCategory.setName("全部");
blogCategoryList.add(0, allBlogCategory);
for (Element categoryElement : categoryElements) {
BlogCategory blogCategory = new BlogCategory();
String name = categoryElement.select("a").text().trim().replace("【", "")
.replace("】", "");
String link = categoryElement.select("a").attr("href");
blogCategory.setName(name.trim());
blogCategory.setLink(link.trim());
blogCategoryList.add(blogCategory);
}
}
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
private static int getBlogTotalPage(String page) {
int totalPage = 0;
if (!TextUtils.isEmpty(page)) {
int pageStart = page.lastIndexOf("共");
int pageEnd = page.lastIndexOf("页");
String pageStr = page.substring(pageStart + 1, pageEnd);
try {
totalPage = Integer.parseInt(pageStr);
} catch (Exception e) {
e.printStackTrace();
}
}
return totalPage;
}
public static String getBlogContent(String html) {
if (TextUtils.isEmpty(html)) {
return null;
}
try {
Element detailElement = Jsoup.parse(html).getElementsByClass("details").get(0);
detailElement.select("script").remove();
if (detailElement.getElementById("digg") != null) {
detailElement.getElementById("digg").remove();
}
if (detailElement.getElementsByClass("tag2box") != null) {
detailElement.getElementsByClass("tag2box").remove();
}
if (detailElement.getElementsByClass("category") != null) {
detailElement.getElementsByClass("category").remove();
}
if (detailElement.getElementsByClass("bog_copyright") != null) {
detailElement.getElementsByClass("bog_copyright").remove();
}
detailElement.getElementsByClass("article_manage").remove();
detailElement.getElementsByTag("h1").tagName("h2");
for (Element element : detailElement.select("pre[name=code]")) {
element.attr("class", "brush: java; gutter: false;");
}
return detailElement.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getBlogTitle(String html) {
if (TextUtils.isEmpty(html)) {
return null;
}
Element titleElement = Jsoup.parse(html).getElementsByClass("article_title").get(0);
try {
return titleElement.select("h1").select("span").select("a").text();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Comment> getCommentList(String json, int pageIndex, int pageSize) {
List<Comment> list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("list");
int index = 0;
int len = jsonArray.length();
if (len > 20) {
index = (pageIndex * pageSize) - 20;
}
if (len < pageSize && pageIndex > 1) {
return list;
}
if ((pageIndex * pageSize) < len) {
len = pageIndex * pageSize;
}
for (int i = index; i < len; i++) {
JSONObject item = jsonArray.getJSONObject(i);
String commentId = item.getString("CommentId");
String content = item.getString("Content");
String username = item.getString("UserName");
String parentId = item.getString("ParentId");
String postTime = item.getString("PostTime");
String userface = item.getString("Userface");
Comment comment = new Comment();
comment.setCommentId(commentId);
comment.setContent(content);
comment.setUsername(username);
comment.setParentId(parentId);
comment.setPostTime(postTime);
comment.setUserface(userface);
if (parentId.equals("0")) {
// 如果parentId为0的话,表示它是评论的topic
comment.setType(Config.COMMENT_TYPE.PARENT);
} else {
comment.setType(Config.COMMENT_TYPE.CHILD);
}
list.add(comment);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
public static List<BlogColumn> getColumnList(String html, String category) {
if (TextUtils.isEmpty(html)) {
return null;
}
List<BlogColumn> columnList = new ArrayList<>();
Document doc = Jsoup.parse(html);
try {
Elements columnWrap = doc.getElementsByClass("column_wrap");
for (Element element : columnWrap) {
Elements columnElements = element.getElementsByClass("column_list");
for (Element column : columnElements) {
BlogColumn blogColumn = new BlogColumn();
Element bgElement = column.getElementsByClass("column_bg").get(0);
String bgUrl = bgElement.attr("style").replace("background-image:url(", "")
.replace(")", "");
Element aElement = column.getElementsByClass("column_list_link").get(0);
String url = StringUtils.trimLastChar(Config.BLOG_HOST) + aElement.attr("href");
String title = aElement.getElementsByClass("column_list_p").get(0).text();
String size = aElement.getElementsByClass("column_list_b_l").get(0).select("span").text();
String viewCount = aElement.getElementsByClass("column_list_b_r").get(0).select("span").text();
blogColumn.setIcon(bgUrl);
blogColumn.setUrl(url);
blogColumn.setName(title);
blogColumn.setSize(size);
blogColumn.setViewCount(viewCount);
blogColumn.setCategory(category);
columnList.add(blogColumn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return columnList;
}
public static List<BlogItem> getColumnDetail(String html, String category) {
if (TextUtils.isEmpty(html)) {
return null;
}
List<BlogItem> blogList = new ArrayList<>();
Document doc = Jsoup.parse(html);
try {
Elements detailListLi = doc.getElementsByClass("blog_l").select("ul").select("li");
String page = doc.getElementsByClass("page_nav").select("span").text();
int totalPage = getBlogTotalPage(page);
for (Element element : detailListLi) {
Element h4 = element.select("h4").get(0);
String title = h4.text();
String link = h4.select("a").attr("href");
String decs = element.getElementsByClass("detail_p").get(0).text();
Element detailBDiv = element.getElementsByClass("detail_b").get(0);
String date = detailBDiv.select("span").text();
String times = detailBDiv.select("em").text();
BlogItem blogItem = new BlogItem();
blogItem.setTitle(title);
blogItem.setLink(link);
blogItem.setContent(decs);
blogItem.setCategory(category);
blogItem.setDate(date + " " + "阅读" + "(" + times + ")");
blogItem.setIcoType(Config.BLOG_TYPE.BLOG_TYPE_ORIGINAL);
blogItem.setTotalPage(totalPage);
blogList.add(blogItem);
}
} catch (Exception e) {
e.printStackTrace();
}
return blogList;
}
public static List<BlogRank> getBlogRank(String html) {
if (TextUtils.isEmpty(html)) {
return null;
}
List<BlogRank> list = new ArrayList<>();
try {
Document doc = Jsoup.parse(html);
Elements blogRanks = doc.getElementsByClass("ranking");
for (Element rank : blogRanks) {
BlogRank blogRank = new BlogRank();
String RankTitle = rank.getElementsByClass("rank_t").text();
Elements liList = rank.select("ul").select("li");
List<RankItem> ranks = new ArrayList<>();
for (Element li : liList) {
Element aElement = li.select("label").select("a").get(0);
String url = aElement.attr("href");
String icon = aElement.select("img").attr("src");
String title = aElement.attr("title");
if (TextUtils.isEmpty(title)) {
title = li.getElementsByClass("blog_a").text();
}
if (TextUtils.isEmpty(title)) {
title = li.getElementsByClass("star_name").text();
}
String viewCount = li.select("label").select("span").select("b").text();
RankItem rankItem = new RankItem();
rankItem.setIcon(icon);
rankItem.setUrl(url);
rankItem.setName(title);
rankItem.setViewCount(viewCount);
ranks.add(rankItem);
}
blogRank.setName(RankTitle);
blogRank.setData(ranks);
list.add(blogRank);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static List<BlogItem> getHotBlog(String html, String category) {
if (TextUtils.isEmpty(html)) {
return null;
}
List<BlogItem> list = new ArrayList<>();
try {
Document doc = Jsoup.parse(html);
String page = doc.getElementsByClass("page_nav").select("span").text();
int totalPage = getBlogTotalPage(page);
Elements blogElements = doc.getElementsByClass("blog_list");
for (Element blogElement : blogElements) {
Element h3 = blogElement.getElementsByClass("tracking-ad").first();
String title = h3.select("a").text();
String url = h3.select("a").attr("href");
String desc = blogElement.getElementsByClass("blog_list_c").text();
Element detailBDiv = blogElement.getElementsByClass("blog_list_b_r").first();
String date = detailBDiv.select("label").text();
String times = detailBDiv.select("span").select("em").text();
BlogItem blogItem = new BlogItem();
blogItem.setTitle(title);
blogItem.setLink(url);
blogItem.setContent(desc);
blogItem.setTotalPage(totalPage);
blogItem.setDate(date + " " + "阅读" + "(" + times + ")");
blogItem.setCategory(category);
blogItem.setIcoType(Config.BLOG_TYPE.BLOG_TYPE_ORIGINAL);
list.add(blogItem);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
| [
"[email protected]"
]
| |
d2d750492100b44ea2ce6c27b182234152a3a547 | 452c7ee073c9b9b75817759c1f22398b05fcb75d | /src/com/dzwz/shop/dao/BaseDaoIpml.java | 6cc5d80db5b0ea656336e50b9cf0e0ae222a32bc | []
| no_license | MarvenGong/fruit-shop | 998dab73f0f515a9c11109e6c73bd07e4db4e7a3 | 9856f32b64e021c0999e6a9e8ee29b58869c2053 | refs/heads/master | 2021-01-21T20:29:04.811823 | 2017-05-26T02:20:14 | 2017-05-26T02:20:14 | 92,236,798 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,404 | java | package com.dzwz.shop.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.dzwz.shop.model.Account;
@SuppressWarnings("unchecked")
public class BaseDaoIpml<T> implements BaseDao<T> {
private Class<T> clazz;
public BaseDaoIpml() {
ParameterizedType type =(ParameterizedType) this.getClass().getGenericSuperclass();
clazz = (Class<T>) type.getActualTypeArguments()[0];
}
public SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
//获取当前线程中绑定的session
public Session getSession(){
return sessionFactory.getCurrentSession();
}
@Override
public void save(T t) {
getSession().save(t);
}
@Override
public void update(T t) {
//getSession().update(t);
this.getSession().merge(t);
System.out.println(t.toString());
}
@Override
public void delete(int id) {
String hql = "FROM "+clazz.getSimpleName()+" WHERE id=:id";
getSession().createQuery(hql)
.setInteger("id", id)
.executeUpdate();
}
@Override
public T queryByid(int id) {
return (T) getSession().get(clazz, id);
}
@Override
public List<T> query() {
String hql = "FROM "+clazz.getSimpleName();
return getSession().createQuery(hql).list();
}
}
| [
"[email protected]"
]
| |
c75b57f62c091f4c92d1eeea4a95e5a8d8519c15 | 48de71349f6555e1508426d241818e9c1a659a60 | /Exceptions_1/src/Template.java | 6e76edab209a296c85a74d1695f61460e46fa1fa | []
| no_license | SpaceManCola/Epam | 345daeb63eb0434ad481f27c86f895284860097b | 1c8261b22542cbb661c1cf82dd6f1b44122bd0eb | refs/heads/master | 2021-07-04T11:14:34.103279 | 2017-09-27T09:38:32 | 2017-09-27T09:38:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,632 | java | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
public class Template {
static String abPath = null;
public static void main(String[] args) {
replaceThemAll();
}
private static void replaceThemAll() {
if (abPath == null)
abPath = newFile();
Properties property = new Properties();
try (FileReader input = new FileReader("src/config.properties");
PrintWriter out = new PrintWriter(new FileWriter(abPath, true));
BufferedReader strFile = new BufferedReader(new FileReader("src/in.txt"));) {
property.load(input);
String workStr;
while ((workStr = strFile.readLine()) != null) {
for (Map.Entry<?, ?> entry: property.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
workStr = workStr.replaceAll("\\"+key, value);
}
out.print(workStr +" ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String newFile() {
UUID id = UUID.randomUUID();
String filename = "out_" + id.toString().replaceAll("-", "") + ".txt";
return new File(filename).getAbsolutePath();
}
}
| [
"[email protected]"
]
| |
315e5ac4e58a1889f07b79c2479e6fa92121f273 | 284870bbd07086c4b1a620517e8d131dc8cde2e5 | /dl4j-examples/src/main/java/org/deeplearning4j/examples/misc/lossfunctions/CustomLossExample.java | 18e7b551d475298e656f396cbfa4151cf417c2a4 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
]
| permissive | DavidLei08/deeplearning4j-examples | 91fe84cc5417b03d736ea34e0c2edc0ae5879d02 | de7d9676bb946b67876b64ccd97bd54d1510e46b | refs/heads/master | 2020-12-06T04:36:46.489980 | 2019-12-20T00:25:39 | 2019-12-20T00:25:39 | 232,342,812 | 1 | 0 | NOASSERTION | 2020-01-07T14:31:59 | 2020-01-07T14:31:58 | null | UTF-8 | Java | false | false | 10,820 | java | /*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.examples.misc.lossfunctions;
import org.deeplearning4j.datasets.iterator.impl.ListDataSetIterator;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.activations.impl.ActivationIdentity;
import org.nd4j.linalg.api.iter.NdIndexIterator;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.config.Nesterovs;
import org.nd4j.linalg.util.ArrayUtil;
import java.util.*;
/**
* Created by susaneraly on 11/9/16.
* This is an example that illustrates how to instantiate and use a custom loss function.
* The example is identical to the one in org.deeplearning4j.examples.feedforward.regression.RegressionSum
* except for the custom loss function
*/
public class CustomLossExample {
public static final int seed = 12345;
public static final int nEpochs = 500;
public static final int nSamples = 1000;
public static final int batchSize = 100;
public static final double learningRate = 0.001;
public static int MIN_RANGE = 0;
public static int MAX_RANGE = 3;
public static final Random rng = new Random(seed);
public static void main(String[] args) {
doTraining();
//THE FOLLOWING IS TO ILLUSTRATE A SIMPLE GRADIENT CHECK.
//It checks the implementation against the finite difference approximation, to ensure correctness
//You will have to write your own gradient checks.
//Use the code below and the following for reference.
// deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/gradientcheck/LossFunctionGradientCheck.java
doGradientCheck();
}
public static void doTraining(){
DataSetIterator iterator = getTrainingData(batchSize,rng);
//Create the network
int numInput = 2;
int numOutputs = 1;
int nHidden = 10;
MultiLayerNetwork net = new MultiLayerNetwork(new NeuralNetConfiguration.Builder()
.seed(seed)
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(learningRate, 0.95))
.list()
.layer(new DenseLayer.Builder().nIn(numInput).nOut(nHidden)
.activation(Activation.TANH)
.build())
//INSTANTIATE CUSTOM LOSS FUNCTION here as follows
//Refer to CustomLossL1L2 class for more details on implementation
.layer(new OutputLayer.Builder(new CustomLossL1L2())
.activation(Activation.IDENTITY)
.nIn(nHidden).nOut(numOutputs).build())
.build()
);
net.init();
//Train the network on the full data set and evaluate
net.setListeners(new ScoreIterationListener(100));
net.fit(iterator, nEpochs);
// Test the addition of 2 numbers (Try different numbers here)
final INDArray input = Nd4j.create(new double[] { 0.111111, 0.3333333333333 }, new int[] { 1, 2 });
INDArray out = net.output(input, false);
System.out.println(out);
}
private static DataSetIterator getTrainingData(int batchSize, Random rand){
double [] sum = new double[nSamples];
double [] input1 = new double[nSamples];
double [] input2 = new double[nSamples];
for (int i= 0; i< nSamples; i++) {
input1[i] = MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
input2[i] = MIN_RANGE + (MAX_RANGE - MIN_RANGE) * rand.nextDouble();
sum[i] = input1[i] + input2[i];
}
INDArray inputNDArray1 = Nd4j.create(input1, new int[]{nSamples,1});
INDArray inputNDArray2 = Nd4j.create(input2, new int[]{nSamples,1});
INDArray inputNDArray = Nd4j.hstack(inputNDArray1,inputNDArray2);
INDArray outPut = Nd4j.create(sum, new int[]{nSamples, 1});
DataSet dataSet = new DataSet(inputNDArray, outPut);
List<DataSet> listDs = dataSet.asList();
Collections.shuffle(listDs,rng);
return new ListDataSetIterator(listDs,batchSize);
}
public static void doGradientCheck() {
double epsilon = 1e-3;
int totalNFailures = 0;
double maxRelError = 5.0; // in %
CustomLossL1L2 lossfn = new CustomLossL1L2();
String[] activationFns = new String[]{"identity", "softmax", "relu", "tanh", "sigmoid"};
int[] labelSizes = new int[]{1, 2, 3, 4};
for (int i = 0; i < activationFns.length; i++) {
System.out.println("Running checks for "+activationFns[i]);
IActivation activation = Activation.fromString(activationFns[i]).getActivationFunction();
List<INDArray> labelList = makeLabels(activation,labelSizes);
List<INDArray> preOutputList = makeLabels(new ActivationIdentity(),labelSizes);
for (int j=0; j<labelSizes.length; j++) {
System.out.println("\tRunning check for length " + labelSizes[j]);
INDArray label = labelList.get(j);
INDArray preOut = preOutputList.get(j);
INDArray grad = lossfn.computeGradient(label,preOut,activation,null);
NdIndexIterator iterPreOut = new NdIndexIterator(preOut.shape());
while (iterPreOut.hasNext()) {
int[] next = ArrayUtil.toInts(iterPreOut.next());
//checking gradient with total score wrt to each output feature in label
double before = preOut.getDouble(next);
preOut.putScalar(next, before + epsilon);
double scorePlus = lossfn.computeScore(label, preOut, activation, null, true);
preOut.putScalar(next, before - epsilon);
double scoreMinus = lossfn.computeScore(label, preOut, activation, null, true);
preOut.putScalar(next, before);
double scoreDelta = scorePlus - scoreMinus;
double numericalGradient = scoreDelta / (2 * epsilon);
double analyticGradient = grad.getDouble(next);
double relError = Math.abs(analyticGradient - numericalGradient) * 100 / (Math.abs(numericalGradient));
if( analyticGradient == 0.0 && numericalGradient == 0.0 ) relError = 0.0;
if (relError > maxRelError || Double.isNaN(relError)) {
System.out.println("\t\tParam " + Arrays.toString(next) + " FAILED: grad= " + analyticGradient + ", numericalGrad= " + numericalGradient
+ ", relErrorPerc= " + relError + ", scorePlus=" + scorePlus + ", scoreMinus= " + scoreMinus);
totalNFailures++;
} else {
System.out.println("\t\tParam " + Arrays.toString(next) + " passed: grad= " + analyticGradient + ", numericalGrad= " + numericalGradient
+ ", relError= " + relError + ", scorePlus=" + scorePlus + ", scoreMinus= " + scoreMinus);
}
}
}
}
if(totalNFailures > 0) System.out.println("DONE:\n\tGradient check failed for loss function; total num failures = " + totalNFailures);
else System.out.println("DONE:\n\tSimple gradient check passed - This is NOT exhaustive by any means");
}
/* This function is a utility function for the gradient check above
It generate labels randomly in the right range depending on the activation function
Uses a gaussian
identity: range is anything
relu: range is non-negative
softmax: range is non-negative and adds up to 1
sigmoid: range is between 0 and 1
tanh: range is between -1 and 1
*/
public static List<INDArray> makeLabels(IActivation activation,int[]labelSize) {
//edge cases are label size of one for everything except softmax which is two
//+ve and -ve values, zero and non zero values, less than zero/greater than zero
List<INDArray> returnVals = new ArrayList<>(labelSize.length);
for (int i=0; i< labelSize.length; i++) {
int aLabelSize = labelSize[i];
Random r = new Random();
double[] someVals = new double[aLabelSize];
double someValsSum = 0;
for (int j=0; j<aLabelSize; j++) {
double someVal = r.nextGaussian();
double transformVal = 0;
switch (activation.toString()) {
case "identity":
transformVal = someVal;
case "softmax":
transformVal = someVal;
break;
case "sigmoid":
transformVal = Math.sin(someVal);
break;
case "tanh":
transformVal = Math.tan(someVal);
break;
case "relu":
transformVal = someVal * someVal + 4;
break;
default:
throw new RuntimeException("Unknown activation function");
}
someVals[j] = transformVal;
someValsSum += someVals[j];
}
if ("sigmoid".equals(activation.toString())) {
for (int j=0; j<aLabelSize; j++) {
someVals[j] /= someValsSum;
}
}
returnVals.add(Nd4j.create(someVals));
}
return returnVals;
}
}
| [
"[email protected]"
]
| |
afd85bd1bd1720990b28eb45603b1a479c84875d | 40bf69cfa2b02952c86f38f72099ef0f5def2c62 | /NewsDataSource.java | 25c86e819ff8f55b04456fbd6d213f0da53062e5 | []
| no_license | br225/Isreal_News | 3e594e8585b3dfdfeb074932c8ba7e910e91a304 | 9ae805a047052bf8cb1cbb0e822a2e17ec254df7 | refs/heads/main | 2023-08-27T07:29:59.211589 | 2021-10-03T20:17:12 | 2021-10-03T20:17:12 | 406,739,303 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,384 | java | package com.example.khalil.data.model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class NewsDataSource {
public static String address = "https://newsapi.org/v2/top-headlines?country=il&apiKey=c3166900696849579d68cad8b4acce11";
public static void getMovies() {
new Thread(() -> {
try {
URL url = new URL(address);
URLConnection con = url.openConnection();
//binary input stream to String stream: Decorator Design pattern
//no libraries:
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
//String concat in a loop:
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
System.out.println(json);
} catch (MalformedURLException e) {
System.out.println(" כתובת לא תקינה");
} catch (IOException e) {
System.out.println(" אין גישה לשרת ");
}
}).start();
}
}
| [
"[email protected]"
]
| |
d827342fe2f9f437d66bb5b1b60a0b5c497e1af3 | 114e0fcdd34d7e88b240fb08db8f0baa1bab8ced | /src/test/java/com/kamatama41/hadoop/WordCountTest.java | 6aa5da453e1b94ff4da5b79355a80c0216cc4aaf | []
| no_license | kamatama41/hadoop-example | 211c3f1469a967c99343b29b187d8f9e32abf21d | 41415049459cfe0263d328a2ed67f36ea0f75b1b | refs/heads/master | 2016-09-06T11:36:37.733312 | 2014-12-10T17:23:00 | 2014-12-10T17:23:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,663 | java | package com.kamatama41.hadoop;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver;
import org.apache.hadoop.mrunit.mapreduce.ReduceDriver;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
public class WordCountTest {
WordCount.TokenizerMapper mapper;
MapDriver<Object, Text, Text, IntWritable> mapDriver;
WordCount.IntSumReducer reducer;
ReduceDriver<Text, IntWritable, Text, IntWritable> reduceDriver;
MapReduceDriver<Object, Text, Text, IntWritable, Text, IntWritable> mapReduceDriver;
@Test
public void mapperTest() throws IOException {
// prepare
mapper = new WordCount.TokenizerMapper();
mapDriver = MapDriver.newMapDriver(mapper);
// input
mapDriver.withInput(new LongWritable(1), new Text("We must know. We will know."));
// output
mapDriver.withOutput(new Text("We"), new IntWritable(1))
.withOutput(new Text("must"), new IntWritable(1))
.withOutput(new Text("know."), new IntWritable(1))
.withOutput(new Text("We"), new IntWritable(1))
.withOutput(new Text("will"), new IntWritable(1))
.withOutput(new Text("know."), new IntWritable(1));
// invoke
mapDriver.runTest();
}
@Test
public void reducerTest() throws IOException {
// prepare
reducer = new WordCount.IntSumReducer();
reduceDriver = ReduceDriver.newReduceDriver(reducer);
// input
reduceDriver.withInput(new Text("We"), Arrays.asList(new IntWritable(1), new IntWritable(1)));
// output
reduceDriver.withOutput(new Text("We"), new IntWritable(2));
// invoke
reduceDriver.runTest();
}
@Test
public void mapreduceTest() throws IOException {
// prepare
mapper = new WordCount.TokenizerMapper();
reducer = new WordCount.IntSumReducer();
mapReduceDriver = MapReduceDriver.newMapReduceDriver(mapper, reducer);
// input
mapReduceDriver.withInput(new LongWritable(1), new Text("We must know. We will know."));
// output
mapReduceDriver.withOutput(new Text("We"), new IntWritable(2))
.withOutput(new Text("know."), new IntWritable(2))
.withOutput(new Text("must"), new IntWritable(1))
.withOutput(new Text("will"), new IntWritable(1));
// invoke
mapReduceDriver.runTest();
}
} | [
"[email protected]"
]
| |
b30904c783298ba6605247ffb8084f578d2e5226 | a5b866f5708d857347a50d6f106754c040d1acf4 | /Arrays - Exercise/src/CommonElements.java | 21181ad333f2ec061517892db587a59660d94682 | []
| no_license | StanchevaYoana/Java-Fundamentals | 3c8434cdab20a009737e0d25be2d45bc0d772e37 | 99a883c313864f52ae39026a508925f4924325d4 | refs/heads/master | 2020-06-21T20:00:54.710482 | 2019-08-05T13:50:29 | 2019-08-05T13:50:29 | 197,541,288 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 543 | java | import java.util.Arrays;
import java.util.Scanner;
public class CommonElements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] firstRow = scanner.nextLine().split(" ");
String[] secondRow = scanner.nextLine().split(" ");
for (String n : secondRow) {
for (String f : firstRow) {
if (n.equals(f)) {
System.out.print(n);
System.out.print(" ");
}
}
}
}
}
| [
"[email protected]"
]
| |
5d6e5357caa5e9bdddaf82bf9b043d0f3517e47f | 2e59128aafe91d7fc34968a5d5d478deec26a9df | /Android Uygulaması/gen/com/uygulama13/R.java | 98a84ec868d7f1af58aedde9b3587bd6f220c222 | []
| no_license | ramazankayis/Android_Uygulamasi | 4c575f37402dca3a05de6607b25979bd4542b069 | fbd118985a2459ba84baadf2f7cf25aa6a2bb927 | refs/heads/master | 2020-12-28T21:17:46.480436 | 2017-02-02T11:31:49 | 2017-02-02T11:31:49 | 80,717,803 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,939 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.uygulama13;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f050000;
public static final int activity_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int adsiz=0x7f020000;
public static final int as=0x7f020001;
public static final int bay=0x7f020002;
public static final int cc=0x7f020003;
public static final int celebi_mehmet=0x7f020004;
public static final int d1=0x7f020005;
public static final int d2=0x7f020006;
public static final int d3=0x7f020007;
public static final int ddd=0x7f020008;
public static final int fth=0x7f020009;
public static final int g1=0x7f02000a;
public static final int gerileme=0x7f02000b;
public static final int gerilme2=0x7f02000c;
public static final int giris=0x7f02000d;
public static final int hmhg=0x7f02000e;
public static final int ic_launcher=0x7f02000f;
public static final int iii=0x7f020010;
public static final int ikinci_murad=0x7f020011;
public static final int images=0x7f020012;
public static final int indir=0x7f020013;
public static final int kk=0x7f020014;
public static final int krls=0x7f020015;
public static final int mhtr=0x7f020016;
public static final int murat_huda=0x7f020017;
public static final int orhan_gazi=0x7f020018;
public static final int orhangazi_harita=0x7f020019;
public static final int osman_gazi=0x7f02001a;
public static final int osmanlikurulus=0x7f02001b;
public static final int s1=0x7f02001c;
public static final int savas1=0x7f02001d;
public static final int savas21=0x7f02001e;
public static final int tugra=0x7f02001f;
public static final int vahdeddin=0x7f020020;
public static final int vahdettin_harita=0x7f020021;
public static final int w=0x7f020022;
public static final int x=0x7f020023;
public static final int y=0x7f020024;
public static final int yildirim_beyazid=0x7f020025;
public static final int z=0x7f020026;
}
public static final class id {
public static final int RelativeLayout1=0x7f09000c;
public static final int action_settings=0x7f090010;
public static final int button1=0x7f090003;
public static final int button11=0x7f09000a;
public static final int button2=0x7f090004;
public static final int button3=0x7f090005;
public static final int button31=0x7f090002;
public static final int button32=0x7f09000f;
public static final int button4=0x7f090001;
public static final int imageView1=0x7f090008;
public static final int imageView2=0x7f090009;
public static final int imageView4=0x7f090006;
public static final int imageView5=0x7f090007;
public static final int textView=0x7f090000;
public static final int textView1=0x7f09000b;
public static final int textView2=0x7f09000d;
public static final int videoView1=0x7f09000e;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int donemler=0x7f030001;
public static final int fsm=0x7f030002;
public static final int fsm_video=0x7f030003;
public static final int genel=0x7f030004;
public static final int kurulus=0x7f030005;
public static final int padisahlar=0x7f030006;
public static final int padisahlar2=0x7f030007;
public static final int savas1=0x7f030008;
public static final int savaslar=0x7f030009;
public static final int splash=0x7f03000a;
}
public static final class menu {
public static final int main=0x7f080000;
}
public static final class raw {
public static final int video=0x7f040000;
}
public static final class string {
public static final int action_settings=0x7f060002;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| [
"RAMAZAN KAYIŞ"
]
| RAMAZAN KAYIŞ |
ec1b3c9c2dddb7fee77d8c5cd3d4917d54cf2c58 | 8b41ebb026f13cd6b64e9fa550f58a7bfec1e079 | /framework-root/framework-selenium/src/main/java/org/familysearch/products/gallery/testframework/selenium/driver/BrowserDriverFactory.java | 650989c8b191d5ef42b842aa82b5d366d7e2b711 | []
| no_license | sheelakumari/products-gallery-web-test | 836355bbd6c0a1135dbb804b8446006472cb4dcf | 71b6f92298143ec5d4e9dd06f55fe5a6e59c2a65 | refs/heads/master | 2020-04-05T21:18:24.651241 | 2014-10-28T12:43:18 | 2014-10-28T12:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,226 | java | package org.familysearch.products.gallery.testframework.selenium.driver;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
/**
* Creates drivers for browsers that run locally on the calling workstation.
*
* Note: To create browsers for Sauce Labs, use SauceBrowserDriverFactory
*
* @author stoddardbd
*/
public class BrowserDriverFactory {
private static final Logger logger = Logger.getLogger(BrowserDriverFactory.class);
public WebDriver getLocalBrowserDriver(BrowserType browserType) {
return LocalBrowserDriverFactory.getLocalBrowserDriver(browserType);
}
public WebDriver getSauceBrowserDriver(String sauceUserName, String sauceAccessKey, String browserName, String browserVersion, String os, String testName) {
return SauceBrowserDriverFactory.createSauceDriver(sauceUserName, sauceAccessKey, browserName, browserVersion, os, testName);
}
public WebDriver getSauceConnectBrowserDriver(String sauceUserName, String sauceAccessKey, String browserName, String browserVersion, String os, String testName) {
return SauceBrowserDriverFactory.createSauceConnectDriver(sauceUserName, sauceAccessKey, browserName, browserVersion, os, testName);
}
}
| [
"[email protected]"
]
| |
390106e2e04af626c9a09fabb259eb4bfb35bf27 | 22795f9dbaad1de84f747f9791a28c6173ed3bca | /koopa.dsl/koopa/templates/partials/VerbatimLine.java | 7886bd9fadaab36f15a6c2453d2d1b3db25210ff | []
| no_license | benravago/koopa | f9d1a36f61b86e3b417a574d1a5902db12c01bb3 | e03690fd834574572d95bf60ca8b9eb0effce869 | refs/heads/master | 2020-07-02T22:34:47.412406 | 2019-12-29T19:35:01 | 2019-12-29T19:35:01 | 201,689,942 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 440 | java | package koopa.templates.partials;
import koopa.templates.TemplateLogic;
public class VerbatimLine implements Part {
private final String text;
public VerbatimLine(String text) {
this.text = text;
}
@Override
public void applyTo(StringBuilder builder, String indent, TemplateLogic logic) {
builder.append(indent);
builder.append(text);
builder.append(System.lineSeparator());
}
}
| [
"[email protected]"
]
| |
58a38ccb32eedf7fe2313cc79a2f6268b963839e | 595754069887f4dfdaa4224a1bc8e8e360575fac | /版本更新/xml解析更新/UpdateVersionService.java | e60a62d94a8912c9212a8eb381b0299855f7fb54 | []
| no_license | ixinrun/AndroidSceneCode | aa87292ae190cc754c936cca504a8224fcf332a0 | 5328eae178164a182df9e60aed29762f73168374 | refs/heads/main | 2023-03-05T16:50:49.445334 | 2021-02-09T01:20:30 | 2021-02-09T01:20:30 | 337,112,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,426 | java | package com.updateversion.updateversion;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
/**
* 检测安装更新文件的助手类
*
* @author BigRun 2015/10/3
*/
public class UpdateVersionService {
private static final int UPDATE_FALSE = 0; //没有更新
private static final int UPDATE_TRUE = 1; //有更新
private static final int DOWN = 2;// 用于区分正在下载
private static final int DOWN_FINISH = 3;// 用于区分下载完成
private HashMap<String, String> hashMap;// 存储跟心版本的xml信息
private String fileSavePath;// 下载新apk的厨房地点
private String updateVersionXMLPath;// 检测更新的xml文件
private int progress;// 获取新apk的下载数据量,更新下载滚动条
private boolean cancelUpdate = false;// 是否取消下载
private Context context;
private boolean isAutoUpdate;
private ProgressBar progressBar;
private Dialog downLoadDialog;
private Handler handler = new Handler() {// 更新ui
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch ((Integer) msg.obj) {
case UPDATE_FALSE:
if(!isAutoUpdate)
Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show();
break;
case UPDATE_TRUE:
showUpdateVersionDialog();// 显示提示对话框
break;
case DOWN:
progressBar.setProgress(progress);
break;
case DOWN_FINISH:
Toast.makeText(context, "文件下载完成,正在安装更新", Toast.LENGTH_SHORT).show();
installAPK();
break;
default:
break;
}
}
};
/**
* 构造方法
*
* @param updateVersionXMLPath 比较版本的xml文件地址(服务器上的)
* @param context 上下文
*/
public UpdateVersionService(String updateVersionXMLPath, Context context,boolean isAutoUpdate) {
super();
this.updateVersionXMLPath = updateVersionXMLPath;
this.context = context;
this.isAutoUpdate = isAutoUpdate;
}
/**
* 检测是否可更新
* 主线程不能直接进行网络请求
*/
public void checkUpdate() {
new CheckUpdateThread().start();
}
/**
* 检查更新子线程
*
* @return
*/
public class CheckUpdateThread extends Thread {
@Override
public void run() {
super.run();
int versionCode = getVersionCode(context);
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
// 把version.xml放到网络上,然后获取文件信息
URL url = new URL(updateVersionXMLPath);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000); //设置访问网络超时时间
conn.setReadTimeout(5 * 1000); //设置读取数据超时时间
conn.setRequestMethod("GET"); //设置访问方式
//开始连接,调用此方法就不必再使用conn.connect()方法
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = conn.getInputStream();
// 解析XML文件。
ParseXmlService service = new ParseXmlService();
hashMap = service.parseXml(inputStream);
if (null != hashMap) {
Message message = new Message();
// 版本判断
int serverCode = Integer.valueOf(hashMap.get("versionCode"));
if (serverCode > versionCode) {
message.obj = UPDATE_TRUE;
handler.sendMessage(message);
} else {
message.obj = UPDATE_FALSE;
handler.sendMessage(message);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//从里到外,从上到下,逐个关闭
try {
if (inputStream != null)
inputStream.close(); //关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect(); //关闭连接
}
}
}
/**
* 更新提示框
*/
private void showUpdateVersionDialog() {
Log.e("versionDetial","versionDetial"+hashMap.get("versionDetial"));
// 构造对话框
Builder builder = new Builder(context);
builder.setTitle("版本更新");
builder.setMessage(hashMap.get("versionDetial"));
builder.setPositiveButton("更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 显示下载对话框
showDownloadDialog();
}
});
builder.setNegativeButton("稍后更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
/**
* 下载的提示框
*/
protected void showDownloadDialog() {
{
// 构造软件下载对话框
Builder builder = new Builder(context);
builder.setTitle("正在更新");
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.downloaddialog, null);
progressBar = (ProgressBar) v.findViewById(R.id.updateProgress);
builder.setView(v);
// 取消更新
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
downLoadDialog = builder.create();
downLoadDialog.show();
downLoadDialog.setCanceledOnTouchOutside(false);
// 现在文件
downloadApk();
}
}
/**
* 下载apk,不能占用主线程.所以另开的线程
*/
private void downloadApk() {
new DownloadApkThread().start();
}
/**
* 获取当前版本和服务器版本.如果服务器版本高于本地安装的版本.就更新
*
* @param context
* @return
*/
private int getVersionCode(Context context) {
int versionCode = 0;
try {
// 获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 安装apk文件
*/
private void installAPK() {
File apkfile = new File(fileSavePath, hashMap.get("fileName") + ".apk");
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
context.startActivity(i);
android.os.Process.killProcess(android.os.Process.myPid());// 如果不加上这句的话在apk安装完成之后点击单开会崩溃
}
/**
* 卸载应用程序(没有用到)
*/
public void uninstallAPK() {
Uri packageURI = Uri.parse("package:com.example.updateversion");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
}
/**
* 下载apk的方法
*
* @author rongsheng
*/
public class DownloadApkThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
URL url = new URL(hashMap.get("loadUrl"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10 * 1000); //设置访问网络超时时间
conn.setReadTimeout(5 * 1000); //设置读取数据超时时间
conn.setRequestMethod("GET");
conn.setRequestProperty("Charser", "GBK,utf-8;q=0.7,*;q=0.3");
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
fileSavePath = sdpath + "download";
File file = new File(fileSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(fileSavePath, hashMap.get("fileName") + ".apk");
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do {
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
Message message = new Message();
message.obj = DOWN;
handler.sendMessage(message);
if (numread <= 0) {
// 下载完成,取消下载对话框显示
downLoadDialog.dismiss();
Message message2 = new Message();
message2.obj = DOWN_FINISH;
handler.sendMessage(message2);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
conn.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| [
"[email protected]"
]
| |
edadd43754fa12b3c90dd2031b3fd4c0c67ba0de | 2fa3642eef2a0d1e1ca945da3cdd87d961abbe1b | /src/Lib1/IPPFix.java | 9f92fd4f4dfa98a5d7cb681537b087c554c23c5e | [
"MIT"
]
| permissive | Vectis99/sshs-2016-willamette | ce589a88e7f5351e49d22f30915842865bd9e94b | 101be0b8d884838043485886e3882bdf8986817c | refs/heads/master | 2021-01-10T14:35:05.609311 | 2016-03-12T04:51:48 | 2016-03-12T04:51:48 | 52,473,560 | 2 | 2 | null | 2016-02-24T22:16:21 | 2016-02-24T20:52:18 | Java | UTF-8 | Java | false | false | 3,584 | java | package Lib1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Predicate;
public class IPPFix {
//---------------------------------------------------------
objRemove<String> filter;
ArrayList<String> inputArr;
//-----------------------------------------------------------
public IPPFix(String input){
inputArr = new ArrayList<String>(Arrays.asList(input.split("")));
}
//---------------------------------------------------------------------
public void postToInfix(){
filter = new objRemove<String>();
filter.var1 = "(";
inputArr.removeIf(filter);
filter.var1 = ")";
inputArr.removeIf(filter);
filter.var1 = " ";
inputArr.removeIf(filter);
int count = 0;
for(int i = 0;i<inputArr.size();i++){
if(isOperator(inputArr.get(i))){
count ++;
}
}
while(count>0){
int sizeHold = inputArr.size();
for(int i = 0; i < sizeHold-2;i++){
String hold1,hold2,hold3;
hold1 = inputArr.get(i);
hold2 = inputArr.get(i+1);
hold3 = inputArr.get(i+2);
if(!isOperator(hold1)&&!isOperator(hold2)&&isOperator(hold3)){
inputArr.set(i, "("+hold1 + hold3 + hold2+")");
inputArr.remove(i+1);
inputArr.remove(i+1);
count--;
sizeHold -=2;
}
}
}
}
//------------------------------------------------------------------------------
public void preToInfix(){
filter = new objRemove<String>();
filter.var1 = "(";
inputArr.removeIf(filter);
filter.var1 = ")";
inputArr.removeIf(filter);
filter.var1 = " ";
inputArr.removeIf(filter);
int count = 0;
for(int i = 0;i<inputArr.size();i++){
if(isOperator(inputArr.get(i))){
count ++;
}
}
while(count>0){
int sizeHold = inputArr.size();
for(int i = 0; i < sizeHold-2;i++){
String hold1,hold2,hold3;
hold1 = inputArr.get(i);
hold2 = inputArr.get(i+1);
hold3 = inputArr.get(i+2);
if(isOperator(hold1)&&!isOperator(hold2)&&!isOperator(hold3)){
inputArr.set(i, "("+hold2 + hold1 + hold3+")");
inputArr.remove(i+1);
inputArr.remove(i+1);
count--;
sizeHold -=2;
}
}
System.out.println(inputArr);
}
}
//----------------------------------------------------------------------------------------
public static boolean isOperator(String s){
if(s.equals("/")||
s.equals("*")||
s.equals("+")||
s.equals("-")){
return true;
}
return false;
}
//------------------------------------------------------------------------------------
public class objRemove<T>implements Predicate<T>{
T var1;
@Override
public boolean test(T arg0) {
if(var1.equals(arg0)){
return true;
}
else{
return false;
}
}
}
//------------------------------------------------------------------------------------
public ArrayList<String> getArr(){
return inputArr;
}
//-----------------------------------------------------------------------------------
// create a new object "IPPFix" with the parameter in infix
// call upon the method "preToInfix" or "postToInfix"
//use "getArr() to print out the new thing.
public static void main(String[] args) {
IPPFix arr = new IPPFix("(+ (* A B) (/ C D) )");
arr.preToInfix();
System.out.println(arr.getArr());
IPPFix arr2 = new IPPFix("(A (B (C D /) +) *)");
arr2.postToInfix();
System.out.println(arr2.getArr());
}
}
| [
"[email protected]"
]
| |
16bce7ef81c9a518bab09a0647d3609fa0d9f62e | 3962c31a306829a8572101c3dd58cad62f3c2ed8 | /src/com/lanxi/weixin/serviceImpl/WeixinUserServiceImpl.java | 453dbfd0b7275dd2d6811fc2680d46002b00c4a6 | []
| no_license | LuckyMagacian/weixinlanxi | fff179d92224865c01743f70545fa102b629af7d | d7920d765b22cd28e449846779c67f1bcfa91af6 | refs/heads/master | 2021-01-09T06:43:16.808856 | 2017-10-09T11:27:41 | 2017-10-09T11:27:41 | 81,065,798 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,169 | java | package com.lanxi.weixin.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lanxi.weixin.bean.oauth.OpenidDetailBean;
import com.lanxi.weixin.mapper.WeixinUserMapper;
import com.lanxi.weixin.service.WeixinUserService;
@Service
public class WeixinUserServiceImpl implements WeixinUserService{
@Autowired
private WeixinUserMapper weixinUserMapper;
@Override
public int insertWeixinUser(OpenidDetailBean openidDetailBean) {
return weixinUserMapper.insertWeixinUser(openidDetailBean);
}
@Override
public int updateWeixinUser(OpenidDetailBean openidDetailBean) {
return weixinUserMapper.updateWeixinUser(openidDetailBean);
}
@Override
public OpenidDetailBean getWeixinUserByOpenid(String openid) {
return weixinUserMapper.getWeixinUserByOpenid(openid);
}
@Override
public void updatePointsByOpenid(OpenidDetailBean openidDetailBean) {
weixinUserMapper.updatePointsByOpenid(openidDetailBean);
}
@Override
public void updatePointsByOpenid2(OpenidDetailBean openidDetailBean) {
weixinUserMapper.updatePointsByOpenid2(openidDetailBean);
}
}
| [
"[email protected]"
]
| |
2a719c680a08d85fdf6e2d5370c2781750365dc4 | 6a8378e4578fffc4777d66f9b951357a919b99d1 | /src/dao/ItemInfoDao.java | 99230bb0ed39633f945d0d1e78ce27d5ef97b4ef | []
| no_license | lumids/project | 0eb361c2f7cc922e2ef048356e5cd8abb84ea395 | 39255fe40405e41586afcafb02da0bebdecb35e5 | refs/heads/master | 2021-01-20T18:47:57.540364 | 2016-07-04T01:32:32 | 2016-07-04T01:32:32 | 62,522,560 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,463 | java | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class ItemInfoDao {
private static ItemInfoDao instance = new ItemInfoDao();
private ItemInfoDao() {}
public static ItemInfoDao getInstance() {
return instance;
}
private Connection getConnection() {
Connection conn = null;
try { Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("java:comp/env/jdbc/OracleDB");
conn = ds.getConnection();
}catch(Exception e) {System.out.println(e.getMessage());}
return conn;
}
public int insert(ItemInfo i) {
int result = 0,itemNum = 0; Connection conn = null;
PreparedStatement pstmt = null; ResultSet rs = null;
String sql = "insert into ItemInfo values (?,?,?,?,?)";
String sql2 = "select nvl(max(itemNum),0)+1 from itemInfo";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql2);
rs = pstmt.executeQuery();
if (rs.next()) itemNum = rs.getInt(1);
i.setItemNum(itemNum);
pstmt.close();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, i.getItemNum());
pstmt.setString(2, i.getItemPic());
pstmt.setString(3, i.getItemName());
pstmt.setInt(4, i.getItemStat());
pstmt.setInt(5, i.getItemPrice());
result = pstmt.executeUpdate();
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return result;
}
public List<ItemInfo> selectAll() {
Connection conn = null;
List<ItemInfo> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from itemInfo order by itemNum desc";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
ItemInfo i = new ItemInfo();
i.setItemNum(rs.getInt("itemNum"));
i.setItemName(rs.getString("itemName"));
i.setItemPic(rs.getString("itemPic"));
i.setItemStat(rs.getInt("itemStat"));
i.setItemPrice(rs.getInt("itemPrice"));
list.add(i);
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return list;
}
/*public String selectName(int aniNum) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String name="";
AniInfo ai = new AniInfo();
String sql = "select * from aniInfo where aniNum=?";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,aniNum);
rs = pstmt.executeQuery();
if(rs.next()){
name = ai.setAniName1(rs.getString("aniName1"));
System.out.println("1 "+ ai.getAniName1());
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return name;
}
public String selectName2(int ownNum) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String name="";
AniInfo ai = new AniInfo();
String sql = "select * from aniInfo where ownNum=?";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,ownNum);
rs = pstmt.executeQuery();
if(rs.next()){
name = ai.setAniName1(rs.getString("aniName1"));
System.out.println("1 "+ ai.getAniName1());
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return name;
}*/
public ItemInfo selectImg(int itemNum) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ItemInfo ai = new ItemInfo();
String sql = "select * from ItemInfo where itemNum=?";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, itemNum);
rs = pstmt.executeQuery();
while(rs.next()){
ai.setItemPic(rs.getString("itemPic"));
ai.setItemName(rs.getString("itemName"));
ai.setItemPrice(rs.getInt("itemPrice"));
ai.setItemStat(rs.getInt("itemStat"));
ai.setItemNum(rs.getInt("itemNum"));
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return ai;
}
/*
public List<AniInfo> selectImg2(int aniNum) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<AniInfo> list = new ArrayList<>();
String sql = "select * from aniInfo where aniNum=?";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, aniNum);
rs = pstmt.executeQuery();
while(rs.next()){
AniInfo ai = new AniInfo();
ai.setAniPic1(rs.getString("aniPic1"));
ai.setAniName1(rs.getString("aniname1"));
ai.setAniNum(rs.getInt("aniNum"));
list.add(ai);
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return list;
}*/
public ItemInfo selectOne(int itemNum) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ItemInfo id = new ItemInfo();
String sql = "select * from ItemInfo where itemNum=?";
try { conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, itemNum);
rs = pstmt.executeQuery();
while(rs.next()){
id.setItemNum(rs.getInt("itemNum"));
id.setItemName(rs.getString("itemName"));
id.setItemPic(rs.getString("itemPic"));
id.setItemStat(rs.getInt("itemStat"));
id.setItemPrice(rs.getInt("itemPrice"));
}
}catch(Exception e) { System.out.println(e.getMessage());
}finally {
try {if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}catch(Exception e) {}
}
return id;
}
} | [
"[email protected]"
]
| |
8f28c548c4c278f3f06181eb8332bdd77d65b01c | 2fe2a96aca5440217bcddab4ab88827add1f6e30 | /src/test/java/net/yeputons/spbau/spring2016/torrent/protocol/FileEntryTest.java | 653eb56af6f7c89c55db89f9bd902ef7ea6b7249 | [
"MIT"
]
| permissive | ibrahim-R/spbau-java-course-torrent-term4 | 36571a12305694b12d872c0978188b293302fc1c | 12247ebdb76b3e88033a1ef5d8286e046ca94bd8 | refs/heads/master | 2020-05-29T12:23:41.430672 | 2016-05-19T15:45:41 | 2016-05-19T15:45:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 609 | java | package net.yeputons.spbau.spring2016.torrent.protocol;
public class FileEntryTest extends ProtocolEntityTest {
// CHECKSTYLE.OFF: MagicNumber
@Override
protected ProtocolEntity getObject() {
return new FileEntry(123456789, "some_file", 123456789012345L);
}
@Override
protected byte[] getSerializedObject() {
return new byte[] {
0x07, 0x5B, (byte) 0xCD, 0x15,
0, 9, 's', 'o', 'm', 'e', '_', 'f', 'i', 'l', 'e',
0, 0, 0x70, 0x48, (byte) 0x86, 0x0D, (byte) 0xDF, 0x79
};
}
// CHECKSTYLE.ON: MagicNumber
}
| [
"[email protected]"
]
| |
76e0f20eeb67eb9f92970bd0406f9612983f8d40 | bb5c5e0bbaf6c6fe8fd3f311b364f25060f338e0 | /PunktAdventure2/src/Punkt/FlammeAnimation.java | 81f0b1d548b6aa5350dbef4ec22411f8e094c160 | []
| no_license | Luggioh/Adventure2 | ac44793112898f0b4dddf203babc498d4a3bc542 | 3191e98fb365c931a5de89812a8ee9ec16172429 | refs/heads/master | 2021-01-21T23:20:16.104811 | 2017-06-24T12:40:27 | 2017-06-24T12:40:27 | 95,226,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 682 | java | package Punkt;
import java.util.Timer;
import java.util.TimerTask;
public class FlammeAnimation {
Timer flamme;
private int temp = 0;
public FlammeAnimation() {
flamme = new Timer();
flamme.scheduleAtFixedRate(new TimerTask(){
public void run() {
if(Variablen.punktX <= Variablen.flammeX && Variablen.punktX >= Variablen.flammeX -50 && Variablen.punktY <= Variablen.flammeY +85 && Variablen.punktY >= Variablen.flammeY -10){
Variablen.notGameOver = false;
}
if(temp == 0){
Variablen.flammeAni = 0;
temp++;
}
else if(temp == 1){
Variablen.flammeAni = 1;
temp--;
}
}}, 0, 300);
}
} | [
"[email protected]_W_724V_Typ_A_05011603_05_020"
]
| [email protected]_W_724V_Typ_A_05011603_05_020 |
452d3a1252b423707c53b7b1589691ad79518760 | 7003f8a6e4e0e9ac4da6311957a4dd639edbf5a2 | /src/main/java/br/com/retEnvCCe/TransformType.java | 2966047294f3e83eb27140b433b1cc4263fe2766 | []
| no_license | renangtm/frente_caixa_contabilidade | 65e2586ec2e4e10d7d0dbad70b66fda52a81c0ac | 91b1175d3adc8d1357a2cf99efac11223d4071d0 | refs/heads/master | 2022-12-10T09:59:18.687217 | 2019-11-06T05:34:12 | 2019-11-06T05:34:12 | 212,447,056 | 1 | 1 | null | 2023-08-23T17:54:30 | 2019-10-02T21:43:38 | Java | ISO-8859-1 | Java | false | false | 3,001 | java | //
// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802
// Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.
// Gerado em: 2018.07.10 às 10:09:41 AM BRT
//
package br.com.retEnvCCe;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java de TransformType complex type.
*
* <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.
*
* <pre>
* <complexType name="TransformType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence maxOccurs="unbounded" minOccurs="0">
* <element name="XPath" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* <attribute name="Algorithm" use="required" type="{http://www.w3.org/2000/09/xmldsig#}TTransformURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TransformType", propOrder = {
"xPath"
})
public class TransformType {
@XmlElement(name = "XPath")
protected List<String> xPath;
@XmlAttribute(name = "Algorithm", required = true)
protected String algorithm;
/**
* Gets the value of the xPath property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the xPath property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getXPath().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getXPath() {
if (xPath == null) {
xPath = new ArrayList<String>();
}
return this.xPath;
}
/**
* Obtém o valor da propriedade algorithm.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Define o valor da propriedade algorithm.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlgorithm(String value) {
this.algorithm = value;
}
}
| [
"[email protected]"
]
| |
7003ab6b75fa65b760218d7a09a90d3e45e0067e | 75161cfe37bd54d539d244c7a1ffe755c051fb44 | /src/main/java/com/mishkapp/minecraft/plugins/squarekit/commands/area/InfoCommand.java | 36b69270d35536f5fab36132a6e3ebc0646f4566 | []
| no_license | mishkapp/square-kit | b7fce1c24a85c8747d1dcd96ea8caea55f079aa2 | 03254e7e5d51b237ce5f62467704c923cb4b1a5a | refs/heads/master | 2020-03-19T16:45:13.227733 | 2017-03-16T11:01:32 | 2017-03-16T11:01:32 | 136,728,630 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,366 | java | package com.mishkapp.minecraft.plugins.squarekit.commands.area;
import com.mishkapp.minecraft.plugins.squarekit.AreaRegistry;
import com.mishkapp.minecraft.plugins.squarekit.areas.Area;
import com.mishkapp.minecraft.plugins.squarekit.areas.CuboidArea;
import com.mishkapp.minecraft.plugins.squarekit.areas.SphereArea;
import com.mishkapp.minecraft.plugins.squarekit.areas.handlers.Handler;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import java.util.List;
/**
* Created by mishkapp on 04.12.2016.
*/
public class InfoCommand implements CommandExecutor {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if(src instanceof Player) {
Player player = (Player) src;
String areaId = (String) args.getOne("areaId").get();
Area area = AreaRegistry.getInstance().get(areaId);
Text.Builder b = Text.builder();
b.color(TextColors.GOLD);
b.append(Text.of("================================"));
b.append(Text.NEW_LINE);
b.append(Text.of("Area ID: "));
b.append(Text.of(area.getId()));
b.append(Text.NEW_LINE);
b.append(Text.of("Is safe: "));
b.append(Text.of(area.isSafe()));
b.append(Text.NEW_LINE);
if(area instanceof CuboidArea){
b.append(Text.of("Def: "));
b.append(Text.of("cuboid "));
b.append(Text.of("[world: " + area.getWorld().getName()));
b.append(Text.of(", min: "));
b.append(Text.of(((CuboidArea) area).getAabb().getMin().toString()));
b.append(Text.of(", max: "));
b.append(Text.of(((CuboidArea) area).getAabb().getMax().toString()));
b.append(Text.of("]"));
b.append(Text.NEW_LINE);
}
if(area instanceof SphereArea){
b.append(Text.of("Def: "));
b.append(Text.of("sphere "));
b.append(Text.of("[world: " + area.getWorld().getName()));
b.append(Text.of(", center: "));
b.append(Text.of(((SphereArea) area).getCenter().toString()));
b.append(Text.of(", fi: "));
b.append(Text.of(((SphereArea) area).getFi().toString()));
b.append(Text.of("]"));
b.append(Text.NEW_LINE);
}
b.append(Text.of("Handlers: "));
b.append(Text.NEW_LINE);
List<Handler> handlers = area.getHandlers();
for(int i = 0; i < handlers.size(); i++){
b.append(Text.of(" [" + i + "] "));
b.append(Text.of(handlers.get(i).serialize()));
b.append(Text.NEW_LINE);
}
b.append(Text.of("================================"));
player.sendMessage(b.build());
}
return CommandResult.empty();
}
}
| [
"[email protected]"
]
| |
470ddcaee877dd758935edf898532cea29b5468b | f2c850553981f1f83a2320ff11233621209f54bf | /practice3/app/src/androidTest/java/ru/mirea/koskin/practice3/ExampleInstrumentedTest.java | ae4d1ec4fd950c59f561b5cd2a0da4553a75d67e | []
| no_license | asanold/mobile | 3bd1ed2c102e5d8ba0786795789f995d7b26f7b5 | 55c6739b11a63e12a4ecba66e1e8be346423f074 | refs/heads/main | 2023-05-13T16:39:14.147051 | 2021-06-02T01:48:50 | 2021-06-02T01:48:50 | 371,855,339 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 764 | java | package ru.mirea.koskin.practice3;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("ru.mirea.koskin.practice3", appContext.getPackageName());
}
} | [
"[email protected]"
]
| |
dba4ac62adef17ec18ecafebd29c603ce97f4b92 | 64e6d8b30843d33cd9873b38380e3c41548a6763 | /src/main/java/com/spider/vote/web/RestControllerExceptionHandler.java | 39571bcdab449865b2eee2ea2426231d25aee854 | []
| no_license | AlexLyr/votesystem | 121e56d859a3aec55791a838f4a0d2bea8a8cc50 | 385fd67a6fc4882e81dea28a8c87fbadbce1f386 | refs/heads/master | 2021-01-15T19:06:34.289033 | 2017-10-18T22:07:13 | 2017-10-18T22:07:13 | 99,808,991 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,945 | java | package com.spider.vote.web;
import com.spider.vote.utils.ValidationUtil;
import com.spider.vote.utils.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@ControllerAdvice(annotations = RestController.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 5)
public class RestControllerExceptionHandler {
private static Logger LOG = LoggerFactory.getLogger(RestControllerExceptionHandler.class);
@ResponseStatus(value = HttpStatus.CONFLICT)
@ExceptionHandler(UserVoteForThisDayAlreadyExistsException.class)
@ResponseBody
public ErrorInfo handleError(HttpServletRequest req, UserVoteForThisDayAlreadyExistsException e) {
return logAndGetErrorInfo(req, e, false);
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(UserVoteIncorrectDateException.class)
@ResponseBody
public ErrorInfo handleError(HttpServletRequest req, UserVoteIncorrectDateException e) {
return logAndGetErrorInfo(req, e, false);
}
@ResponseStatus(value = HttpStatus.LOCKED)
@ExceptionHandler(UserVoteTooLateException.class)
@ResponseBody
public ErrorInfo handleError(HttpServletRequest req, UserVoteTooLateException e) {
return logAndGetErrorInfo(req, e, false);
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(NotFoundException.class)
@ResponseBody
public ErrorInfo handleError(HttpServletRequest req, NotFoundException e) {
return logAndGetErrorInfo(req, e, false);
}
@ResponseStatus(value = HttpStatus.CONFLICT)
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseBody
public ErrorInfo conflict(HttpServletRequest req, DataIntegrityViolationException e) {
return logAndGetErrorInfo(req, e, true);
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) // 422
@ExceptionHandler(BindException.class)
@ResponseBody
public ErrorInfo bindValidationError(HttpServletRequest req, BindingResult result) {
return logAndGetValidationErrorInfo(req, result);
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) // 422
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ErrorInfo restValidationError(HttpServletRequest req, MethodArgumentNotValidException e) {
return logAndGetValidationErrorInfo(req, e.getBindingResult());
}
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public ErrorInfo conflict(HttpServletRequest req, IllegalArgumentException e) {
return logAndGetErrorInfo(req, e, false);
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseBody
public ErrorInfo handle404Exception(HttpServletRequest request, Exception e) {
return logAndGetErrorInfo(request, e, true);
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleException(HttpServletRequest request, Exception e) {
return logAndGetErrorInfo(request, e, true);
}
private static ErrorInfo logAndGetErrorInfo(HttpServletRequest req, Exception e, boolean logException) {
Throwable rootCause = ValidationUtil.getRootCause(e);
if (logException) {
LOG.error("Exception at request " + req.getRequestURL(), rootCause);
} else {
LOG.warn("Exception at request {}: {}", req.getRequestURL() + ": " + rootCause.toString());
}
return new ErrorInfo(req.getRequestURL(), rootCause);
}
private ErrorInfo logAndGetValidationErrorInfo(HttpServletRequest req, BindingResult result) {
String[] details = result.getAllErrors().stream()
.map(oe -> FieldError.class.cast(oe).getField() + " " + oe.getDefaultMessage())
.toArray(String[]::new);
return logAndGetErrorInfo(req, "ValidationException", details);
}
private static ErrorInfo logAndGetErrorInfo(HttpServletRequest req, String cause, String... details) {
LOG.warn("{} exception at request {}: {}", cause, req.getRequestURL(), Arrays.toString(details));
return new ErrorInfo(req.getRequestURL(), cause, details);
}
}
| [
"[email protected]"
]
| |
0238da518be3af4addc1031ecf5e1d321031055b | 432505d6bac027b1f304bf947d680b4b136986cc | /ipms/.svn/pristine/95/9569feda5ec1757a7a76cc8bd204e1f695feb6f5.svn-base | 1f73e033d9a513f00270db86a046ab837f9aeb1b | []
| no_license | 1171734424/ipms | 27c4a7aa3828c191b85d218d767b770148af70e7 | 09d5831f77365df04f5ec58ece32736492d3bb21 | refs/heads/master | 2020-04-07T15:43:44.066541 | 2018-11-21T06:04:42 | 2018-11-21T06:04:42 | 158,498,481 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,821 | package com.ideassoft.pmsinhouse.service;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import com.ideassoft.bean.OperateLog;
import com.ideassoft.core.bean.LoginUser;
import com.ideassoft.core.constants.SystemConstants;
import com.ideassoft.core.dao.GenericDAOImpl;
import com.ideassoft.util.IPUtil;
@Service
public class HouseCleanService extends GenericDAOImpl {
// 撤销保洁申请日志
public void deletecleanapplyrecordfailed(LoginUser loginUser, String remark, String type,HttpServletRequest request) throws UnknownHostException {
try {
String[] status = SystemConstants.LogModule.CLEANAPPLYSTATUS;
String sequences = getSequence("SEQ_OPERATELOG_ID");
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
String strdate = sdf.format(new Date());
//String operid = InetAddress.getLocalHost().toString();// IP地址
String operid = IPUtil.getIpAddr(request);
operid = (String) operid.subSequence(operid.indexOf("/") + 1, operid.length());
String logid = strdate + loginUser.getStaff().getBranchId() + sequences;
OperateLog operatelog = new OperateLog();
operatelog.setLogId(logid);
operatelog.setOperType(type);
operatelog.setOperModule(SystemConstants.LogModule.DELETECLEANAPPLY);
operatelog.setContent(loginUser.getStaff().getStaffName() + SystemConstants.LogModule.DELETECLEANAPPLY+status[1]);
operatelog.setRecordUser(loginUser.getStaff().getStaffId());
operatelog.setRecordTime(new Date());
operatelog.setOperIp(operid);
operatelog.setRemark(remark);
operatelog.setBranchId(loginUser.getStaff().getBranchId());
save(operatelog);
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
]
| ||
4e00c7eda2549c6e4063e70ade07b5e3e1763658 | 97e4ba8058a0ee2f356ae151288d9a66f85f78c8 | /src/main/java/com/leetcode/day0302/T19_DeleteLastNthNode.java | ddeb72a0b8fe401d48909f61ce573df99b48436c | []
| no_license | zzyssg/ainToOffer | bf5c493b2c018f47d91ea7f9680e64ae60c948c4 | 43d8a2f8f0905bc5217fc2040a7343f4cbf7ca7a | refs/heads/master | 2021-03-23T06:38:11.615481 | 2020-03-15T08:53:48 | 2020-03-15T08:53:48 | 247,432,027 | 0 | 0 | null | 2020-10-13T20:22:29 | 2020-03-15T08:56:37 | Java | UTF-8 | Java | false | false | 562 | java | package com.leetcode.day0302;
import com.buaa.day0216.ListNode;
public class T19_DeleteLastNthNode {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode node1 = head;
ListNode node2 = node1;
for (int i = 0; i < n; i++) {
if (node1 == null) {
return head;
}
node2 = node2.next;
}
while (node2.next != null) {
node1 = node1.next;
node2 = node2.next;
}
node1.next = node1.next.next;
return head;
}
}
| [
"[email protected]"
]
| |
d3ee4f74f6d99f87ad69072d15173e103b4263df | 29196e2d4adfb14ddd7c2ca8c1e60f8c10c26dad | /src/main/java/it/csi/siac/siacfinser/model/ric/ParametroRicercaSubOrdinativoIncasso.java | ab34ecc78d57de4b7cf4cf2a7fa456c67743cc8b | []
| no_license | unica-open/siacbilitf | bbeef5ceca40e9fb83d5b1176e7f54e8d84592bf | 85f3254c05c719a0016fe55cea1a105bcb6b89b2 | refs/heads/master | 2021-01-06T14:51:17.786934 | 2020-03-03T13:27:47 | 2020-03-03T13:27:47 | 241,366,581 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,023 | java | /*
*SPDX-FileCopyrightText: Copyright 2020 | CSI Piemonte
*SPDX-License-Identifier: EUPL-1.2
*/
package it.csi.siac.siacfinser.model.ric;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlType;
import it.csi.siac.siacfinser.model.FINDataDictionary;
@XmlType(namespace = FINDataDictionary.NAMESPACE)
public class ParametroRicercaSubOrdinativoIncasso implements Serializable {
private static final long serialVersionUID = -1L;
private Integer annoEsercizio;
// private String descrizione;
// private List<String> statiDaEscludere;
//Ordinativo incasso
// private BigInteger numeroOrdinativoDa;
// private BigInteger numeroOrdinativoA;
// private String statoOperativo;
// private Date dataEmissioneDa;
// private Date dataEmissioneA;
// private Date dataTrasmissioneOIL;
// private String codiceDistinta;
// private String contoDelTesoriere;
//Articolo
// private Integer annoCapitolo;
// private BigDecimal numeroCapitolo;
// private BigDecimal numeroArticolo;
// private Integer numeroUEB;
//Provvedimento
// private Integer annoProvvedimento;
// private BigDecimal numeroProvvedimento;
// private String tipoProvvedimento;
// private String codiceTipoProvvedimento;
// private String codiceStrutturaAmministrativa;
// private Integer uidStrutturaAmministrativoContabile;
// private Integer uidProvvedimento;
// private String codiceCausale;
//Provvisorio di cassa
private Integer annoProvvCassa;
private BigDecimal numeroProvvCassa;
//
public Integer getAnnoEsercizio() {
return annoEsercizio;
}
public void setAnnoEsercizio(Integer annoEsercizio) {
this.annoEsercizio = annoEsercizio;
}
public Integer getAnnoProvvCassa() {
return annoProvvCassa;
}
public void setAnnoProvvCassa(Integer annoProvvCassa) {
this.annoProvvCassa = annoProvvCassa;
}
public BigDecimal getNumeroProvvCassa() {
return numeroProvvCassa;
}
public void setNumeroProvvCassa(BigDecimal numeroProvvCassa) {
this.numeroProvvCassa = numeroProvvCassa;
}
}
| [
"[email protected]"
]
| |
4dca64c3c7d161d2a2803e36d0bff610a6b35bd1 | 0e5dd4cddb09b49912bee986ca94f80775f772d3 | /android/archComponents/Pager/app/src/main/java/com/kingmo/pager/database/AppDatabase.java | a8dd9c9319e7fd946bc4c85fb6e00bc5ec7cb141 | []
| no_license | maurice-smith/playground | c14737273f66523fb9a6a88a74392e81f4bd56f3 | c668bd9c39f7e0e4f7eaddf75eba7a1ec9b29fdb | refs/heads/master | 2021-05-15T23:47:07.394321 | 2019-11-09T01:46:42 | 2019-11-09T01:46:42 | 106,937,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 841 | java | package com.kingmo.pager.database;
import android.content.Context;
import com.kingmo.pager.database.entity.Post;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = {Post.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static final String DB_NAME = "pager_database";
private static AppDatabase instance;
public static synchronized AppDatabase getInstance(Context context) {
if (instance == null) {
instance = Room
.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME)
.build();
}
return instance;
}
public abstract PostsDao getPostDao();
public static void destroyInstance() {
instance = null;
}
}
| [
"[email protected]"
]
| |
4d9edb8c80d3001f23f94c9f8d25041146ad4be7 | 73d7b055bcedc8bb971782cda9fd196de5d99503 | /src/main/java/com/extent/util/ExtentManager.java | c393590d2fdfae6de1f9d5773841d49136d0f796 | []
| no_license | ManishaPriyadarshini/ExtentReport | 596a90f2882b9e5087e5bd07c09a72b98d8493c6 | da9465430f9bfee2b96960bbf7f8a4579116e5f8 | refs/heads/master | 2023-05-15T01:13:21.335380 | 2019-07-05T18:48:14 | 2019-07-05T18:48:14 | 195,039,858 | 0 | 0 | null | 2023-05-09T18:09:47 | 2019-07-03T11:24:34 | HTML | UTF-8 | Java | false | false | 590 | java | package com.extent.util;
import java.io.File;
import com.relevantcodes.extentreports.DisplayOrder;
import com.relevantcodes.extentreports.ExtentReports;
public class ExtentManager {
public static ExtentReports extent;
public static ExtentReports getInstance(){
if(extent==null)
{
extent = new ExtentReports(System.getProperty("user.dir")+"\\target\\reports\\extent.html",true,DisplayOrder.OLDEST_FIRST);
extent.loadConfig(new File(System.getProperty("user.dir")+"\\src\\test\\resources\\ExtentConfig\\Extentcongig.xml"));
}
return extent;
}
}
| [
"[email protected]"
]
| |
4670072f6a8f28ce5fcd524e1ac1426746b9c54c | 0a0752dd39277c619e8c89823632b0757d5051f3 | /jython/src/org/python/core/PyTuple.java | e9f74b3072567ff49ab856f21044cc4f8250b573 | [
"LicenseRef-scancode-jython"
]
| permissive | anthonycanino1/entbench | fc5386f6806124a13059a1d7f21ba1128af7bb19 | 3c664cc693d4415fd8367c8307212d5aa2f3ae68 | refs/heads/master | 2021-01-10T13:49:12.811846 | 2016-11-14T21:57:38 | 2016-11-14T21:57:38 | 52,231,403 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 15,910 | java | // Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.lang.reflect.Array;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
/**
* A builtin python tuple.
*/
@ExposedType(name = "tuple", base = PyObject.class, doc = BuiltinDocs.tuple_doc)
public class PyTuple extends PySequenceList implements List {
public static final PyType TYPE = PyType.fromClass(PyTuple.class);
private final PyObject[] array;
private volatile List<PyObject> cachedList = null;
private static final PyTuple EMPTY_TUPLE = new PyTuple();
public PyTuple() {
this(TYPE, Py.EmptyObjects);
}
public PyTuple(PyObject... elements) {
this(TYPE, elements);
}
public PyTuple(PyType subtype, PyObject[] elements) {
super(subtype);
if (elements == null) {
array = new PyObject[0];
} else {
array = new PyObject[elements.length];
System.arraycopy(elements, 0, array, 0, elements.length);
}
}
public PyTuple(PyObject[] elements, boolean copy) {
this(TYPE, elements, copy);
}
public PyTuple(PyType subtype, PyObject[] elements, boolean copy) {
super(subtype);
if (copy) {
array = new PyObject[elements.length];
System.arraycopy(elements, 0, array, 0, elements.length);
} else {
array = elements;
}
}
private static PyTuple fromArrayNoCopy(PyObject[] elements) {
return new PyTuple(elements, false);
}
List<PyObject> getList() {
if (cachedList == null) {
cachedList = Arrays.asList(array);
}
return cachedList;
}
@ExposedNew
final static PyObject tuple_new(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("tuple", args, keywords, new String[] {"sequence"}, 0);
PyObject S = ap.getPyObject(0, null);
if (new_.for_type == subtype) {
if (S == null) {
return EMPTY_TUPLE;
}
if (S instanceof PyTupleDerived) {
return new PyTuple(((PyTuple) S).getArray());
}
if (S instanceof PyTuple) {
return S;
}
return fromArrayNoCopy(Py.make_array(S));
} else {
if (S == null) {
return new PyTupleDerived(subtype, Py.EmptyObjects);
}
return new PyTupleDerived(subtype, Py.make_array(S));
}
}
/**
* Return a new PyTuple from an iterable.
*
* Raises a TypeError if the object is not iterable.
*
* @param iterable an iterable PyObject
* @return a PyTuple containing each item in the iterable
*/
public static PyTuple fromIterable(PyObject iterable) {
return fromArrayNoCopy(Py.make_array(iterable));
}
protected PyObject getslice(int start, int stop, int step) {
if (step > 0 && stop < start) {
stop = start;
}
int n = sliceLength(start, stop, step);
PyObject[] newArray = new PyObject[n];
if (step == 1) {
System.arraycopy(array, start, newArray, 0, stop - start);
return fromArrayNoCopy(newArray);
}
for (int i = start, j = 0; j < n; i += step, j++) {
newArray[j] = array[i];
}
return fromArrayNoCopy(newArray);
}
protected PyObject repeat(int count) {
if (count < 0) {
count = 0;
}
int size = size();
if (size == 0 || count == 1) {
if (getType() == TYPE) {
// Since tuples are immutable, we can return a shared copy in this case
return this;
}
if (size == 0) {
return EMPTY_TUPLE;
}
}
int newSize = size * count;
if (newSize / size != count) {
throw Py.MemoryError("");
}
PyObject[] newArray = new PyObject[newSize];
for (int i = 0; i < count; i++) {
System.arraycopy(array, 0, newArray, i * size, size);
}
return fromArrayNoCopy(newArray);
}
@Override
public int __len__() {
return tuple___len__();
}
@ExposedMethod(doc = BuiltinDocs.tuple___len___doc)
final int tuple___len__() {
return size();
}
@ExposedMethod(doc = BuiltinDocs.tuple___contains___doc)
final boolean tuple___contains__(PyObject o) {
return super.__contains__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___ne___doc)
final PyObject tuple___ne__(PyObject o) {
return super.__ne__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___eq___doc)
final PyObject tuple___eq__(PyObject o) {
return super.__eq__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___gt___doc)
final PyObject tuple___gt__(PyObject o) {
return super.__gt__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___ge___doc)
final PyObject tuple___ge__(PyObject o) {
return super.__ge__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___lt___doc)
final PyObject tuple___lt__(PyObject o) {
return super.__lt__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___le___doc)
final PyObject tuple___le__(PyObject o) {
return super.__le__(o);
}
@Override
public PyObject __add__(PyObject generic_other) {
return tuple___add__(generic_other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___add___doc)
final PyObject tuple___add__(PyObject generic_other) {
PyTuple sum = null;
if (generic_other instanceof PyTuple) {
PyTuple other = (PyTuple) generic_other;
PyObject[] newArray = new PyObject[array.length + other.array.length];
System.arraycopy(array, 0, newArray, 0, array.length);
System.arraycopy(other.array, 0, newArray, array.length, other.array.length);
sum = fromArrayNoCopy(newArray);
}
return sum;
}
@Override
public PyObject __mul__(PyObject o) {
return tuple___mul__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___mul___doc)
final PyObject tuple___mul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __rmul__(PyObject o) {
return tuple___rmul__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.tuple___rmul___doc)
final PyObject tuple___rmul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __iter__() {
return tuple___iter__();
}
@ExposedMethod(doc = BuiltinDocs.tuple___iter___doc)
public PyObject tuple___iter__() {
return new PyFastSequenceIter(this);
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.tuple___getslice___doc)
final PyObject tuple___getslice__(PyObject s_start, PyObject s_stop, PyObject s_step) {
return seq___getslice__(s_start, s_stop, s_step);
}
@ExposedMethod(doc = BuiltinDocs.tuple___getitem___doc)
final PyObject tuple___getitem__(PyObject index) {
PyObject ret = seq___finditem__(index);
if (ret == null) {
throw Py.IndexError("index out of range: " + index);
}
return ret;
}
@ExposedMethod(doc = BuiltinDocs.tuple___getnewargs___doc)
final PyTuple tuple___getnewargs__() {
return new PyTuple(new PyTuple(getArray()));
}
@Override
public PyTuple __getnewargs__() {
return tuple___getnewargs__();
}
@Override
public int hashCode() {
return tuple___hash__();
}
@ExposedMethod(doc = BuiltinDocs.tuple___hash___doc)
final int tuple___hash__() {
// strengthened hash to avoid common collisions. from CPython
// tupleobject.tuplehash. See http://bugs.python.org/issue942952
int y;
int len = size();
int mult = 1000003;
int x = 0x345678;
while (--len >= 0) {
y = array[len].hashCode();
x = (x ^ y) * mult;
mult += 82520 + len + len;
}
return x + 97531;
}
private String subobjRepr(PyObject o) {
if (o == null) {
return "null";
}
return o.__repr__().toString();
}
@Override
public String toString() {
return tuple___repr__();
}
@ExposedMethod(doc = BuiltinDocs.tuple___repr___doc)
final String tuple___repr__() {
StringBuilder buf = new StringBuilder("(");
for (int i = 0; i < array.length - 1; i++) {
buf.append(subobjRepr(array[i]));
buf.append(", ");
}
if (array.length > 0) {
buf.append(subobjRepr(array[array.length - 1]));
}
if (array.length == 1) {
buf.append(",");
}
buf.append(")");
return buf.toString();
}
public List subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size()) {
throw new IndexOutOfBoundsException();
} else if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
PyObject elements[] = new PyObject[toIndex - fromIndex];
for (int i = 0, j = fromIndex; i < elements.length; i++, j++) {
elements[i] = array[j];
}
return new PyTuple(elements);
}
public Iterator iterator() {
return new Iterator() {
private final Iterator<PyObject> iter = getList().iterator();
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
return iter.next().__tojava__(Object.class);
}
};
}
public boolean add(Object o) {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection coll) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection coll) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public Object set(int index, Object element) {
throw new UnsupportedOperationException();
}
public void add(int index, Object element) {
throw new UnsupportedOperationException();
}
public Object remove(int index) {
throw new UnsupportedOperationException();
}
public boolean addAll(int index, Collection c) {
throw new UnsupportedOperationException();
}
public ListIterator listIterator() {
return listIterator(0);
}
public ListIterator listIterator(final int index) {
return new ListIterator() {
private final ListIterator<PyObject> iter = getList().listIterator(index);
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
return iter.next().__tojava__(Object.class);
}
public boolean hasPrevious() {
return iter.hasPrevious();
}
public Object previous() {
return iter.previous().__tojava__(Object.class);
}
public int nextIndex() {
return iter.nextIndex();
}
public int previousIndex() {
return iter.previousIndex();
}
public void remove() {
throw new UnsupportedOperationException();
}
public void set(Object o) {
throw new UnsupportedOperationException();
}
public void add(Object o) {
throw new UnsupportedOperationException();
}
};
}
protected String unsupportedopMessage(String op, PyObject o2) {
if (op.equals("+")) {
return "can only concatenate tuple (not \"{2}\") to tuple";
}
return super.unsupportedopMessage(op, o2);
}
public void pyset(int index, PyObject value) {
throw Py.TypeError("'tuple' object does not support item assignment");
}
@Override
public boolean contains(Object o) {
return getList().contains(Py.java2py(o));
}
@Override
public boolean containsAll(Collection c) {
if (c instanceof PyList) {
return getList().containsAll(((PyList)c).getList());
} else if (c instanceof PyTuple) {
return getList().containsAll(((PyTuple)c).getList());
} else {
return getList().containsAll(new PyList(c));
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof PyObject) {
return _eq((PyObject)other).__nonzero__();
}
if (other instanceof List) {
return other.equals(this);
}
return false;
}
@Override
public Object get(int index) {
return array[index].__tojava__(Object.class);
}
@Override
public PyObject[] getArray() {
return array;
}
@Override
public int indexOf(Object o) {
return getList().indexOf(Py.java2py(o));
}
@Override
public boolean isEmpty() {
return array.length == 0;
}
@Override
public int lastIndexOf(Object o) {
return getList().lastIndexOf(Py.java2py(o));
}
@Override
public void pyadd(int index, PyObject element) {
throw new UnsupportedOperationException();
}
@Override
public boolean pyadd(PyObject o) {
throw new UnsupportedOperationException();
}
@Override
public PyObject pyget(int index) {
return array[index];
}
@Override
public void remove(int start, int stop) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return array.length;
}
@Override
public Object[] toArray() {
Object[] converted = new Object[array.length];
for (int i = 0; i < array.length; i++) {
converted[i] = array[i].__tojava__(Object.class);
}
return converted;
}
@Override
public Object[] toArray(Object[] converted) {
Class<?> type = converted.getClass().getComponentType();
if (converted.length < array.length) {
converted = (Object[])Array.newInstance(type, array.length);
}
for (int i = 0; i < array.length; i++) {
converted[i] = type.cast(array[i].__tojava__(type));
}
if (array.length < converted.length) {
for (int i = array.length; i < converted.length; i++) {
converted[i] = null;
}
}
return converted;
}
}
| [
"[email protected]"
]
| |
12317bc4bbfef41574c7fa308e3576bd1e30aaff | 75abd7450ce8371f434a73888990270701402f6b | /src/JianzhiOffer/Problem20.java | 1b5fb4c54019556703f95f35f7e5462dbe90378f | []
| no_license | nightchen/PracticeCode | 67d9a39c92c513f13cb6d41b3c7de139fdd85e22 | 730913ee99f3afd1cc8ced224d2892e87dddf670 | refs/heads/master | 2020-03-10T18:03:14.163526 | 2018-09-08T12:29:51 | 2018-09-08T12:29:51 | 129,470,993 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | package JianzhiOffer;
/**
* Created by nightchen on 2018/5/18.
* 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
* 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
* 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
*/
public class Problem20 {
public boolean isNumeric(char[] str) {
if(str == null || str.length == 0){
return false;
}
else{
try{
double number = Double.parseDouble(new String(str));
}catch(NumberFormatException e){
return false;
}
return true;
}
}
}
| [
"[email protected]"
]
| |
63c3186f8511371d1e62f7a7107d4ca3e94193b8 | fe30da1fd2e8345fa479fa63838459e405b25dd7 | /app/src/main/java/com/chensd/funnydemo/ui/MainActivity.java | 62c0e1cdc795029934f938d13b9eff57912d7356 | []
| no_license | chenshandong/Rxjava-retrofit-mvp | 6c6278a4341feacfb413f0332570f3b51cc97666 | 65218b516645dd6c1c806c1c46da973dcdb94c72 | refs/heads/master | 2021-01-22T02:48:31.052345 | 2017-02-06T16:05:16 | 2017-02-06T16:05:16 | 81,072,326 | 7 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,918 | java | package com.chensd.funnydemo.ui;
import android.Manifest;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.chensd.funnydemo.R;
import com.chensd.funnydemo.model.ImageInfo;
import com.chensd.funnydemo.utils.FileUtil;
import com.chensd.funnydemo.view.BaseView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import java.util.List;
import butterknife.Bind;
public class MainActivity extends BaseActivity{
@Bind(R.id.toolbar)
Toolbar toolbar;
@Bind(R.id.viewpager)
ViewPager mVp;
@Bind(R.id.tabs)
TabLayout mTabs;
private long ExitTimes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
initViewPager();
/**要求权限*/
AndPermission.with(this).requestCode(100).permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.rationale(new RationaleListener() {
@Override
public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
AndPermission.rationaleDialog(MainActivity.this, rationale).show();
}
})
.send();
}
private void initViewPager() {
mVp.setAdapter(new MyFragmentAdapter(getSupportFragmentManager()));
mTabs.setupWithViewPager(mVp);
mTabs.setTabTextColors(Color.GRAY, Color.parseColor("#56abe4"));
mTabs.setSelectedTabIndicatorColor(Color.parseColor("#56abe4"));
}
@Override
protected int getAlertLayoutId() {
return R.layout.help_dialog;
}
@Override
protected String getAlertTitle() {
return "说明";
}
private class MyFragmentAdapter extends FragmentPagerAdapter{
String[] titles = {"主页","最近使用"};
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new RecentFragment();
default:
return new MainFragment();
}
}
@Override
public int getCount() {
return titles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
@Override
public void onBackPressed() {
/** ----------按两次退出------- */
if (System.currentTimeMillis() - ExitTimes > 2000)
{
showToast("再按一次退出栋栋斗图");
ExitTimes = System.currentTimeMillis();
return;
}
super.onBackPressed();
}
@PermissionYes(100)
private void getPermissionYes(){
showToast("权限获取成功");
FileUtil.createAppDir();
}
@PermissionNo(100)
private void getPermissionNo(List<String> deniedPermissions){
showToast("权限获取失败");
// 用户否勾选了不再提示并且拒绝了权限,那么提示用户到设置中授权。
if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
// 第一种:用默认的提示语。
AndPermission.defaultSettingDialog(this, 300).show();
// 第二种:用自定义的提示语。
// AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
// .setTitle("权限申请失败")
// .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败,请您到设置页面手动授权,否则功能无法正常使用!")
// .setPositiveButton("好,去设置")
// .show();
// 第三种:自定义dialog样式。
// SettingService settingHandle = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
// 你的dialog点击了确定调用:
// settingHandle.execute();
// 你的dialog点击了取消调用:
// settingHandle.cancel();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
/**
* 转给AndPermission分析结果。
*
* @param object 要接受结果的Activity、Fragment。
* @param requestCode 请求码。
* @param permissions 权限数组,一个或者多个。
* @param grantResults 请求结果。
*/
AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
}
| [
"[email protected]"
]
| |
0ee916338b4e5a0ec0b1d1fed9135b626fde0758 | ee461488c62d86f729eda976b421ac75a964114c | /tags/HtmlUnit-2.10/src/main/java/com/gargoylesoftware/htmlunit/html/HtmlAbbreviated.java | ff8bfe859b0cc271853c0f99b1aaa4485badb34d | [
"Apache-2.0"
]
| permissive | svn2github/htmlunit | 2c56f7abbd412e6d9e0efd0934fcd1277090af74 | 6fc1a7d70c08fb50fef1800673671fd9cada4899 | refs/heads/master | 2023-09-03T10:35:41.987099 | 2015-07-26T13:12:45 | 2015-07-26T13:12:45 | 37,107,064 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,504 | java | /*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.html;
import java.util.Map;
import com.gargoylesoftware.htmlunit.SgmlPage;
/**
* Wrapper for the HTML element "abbr".
*
* @version $Revision$
* @author Ahmed Ashour
*/
public class HtmlAbbreviated extends HtmlElement {
/** The HTML tag represented by this element. */
public static final String TAG_NAME = "abbr";
/**
* Creates a new instance.
*
* @param namespaceURI the URI that identifies an XML namespace
* @param qualifiedName the qualified name of the element type to instantiate
* @param page the page that contains this element
* @param attributes the initial attributes
*/
HtmlAbbreviated(final String namespaceURI, final String qualifiedName, final SgmlPage page,
final Map<String, DomAttr> attributes) {
super(namespaceURI, qualifiedName, page, attributes);
}
}
| [
"asashour@5f5364db-9458-4db8-a492-e30667be6df6"
]
| asashour@5f5364db-9458-4db8-a492-e30667be6df6 |
ad7e3add6e955332ea8f9f69765e2c6fd5a2f53d | cccc4c9932dd4a7b3ad365adc3026d3e8df489b5 | /AbstractFactoryPatternExample/src/main/java/com/example/designpattern/abstractfactorypattern/shape/impli/Square.java | eaf1326079fcdbfd1e32a2e395c5fa826e227822 | []
| no_license | kimdaehyeok/DesignPattern | dddf10363aedd3d967728bc90137029527349ef2 | f8211f2d8c78540e35f9f78b13bca880ebd384ec | refs/heads/master | 2020-03-23T03:01:34.062572 | 2018-08-26T06:14:29 | 2018-08-26T06:14:29 | 126,334,924 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 309 | java | package com.example.designpattern.abstractfactorypattern.shape.impli;
import com.example.designpattern.abstractfactorypattern.shape.interfaces.Shape;
public class Square implements Shape
{
public void draw()
{
// TODO Auto-generated method stub
System.out.println("Inside Square");
}
}
| [
"[email protected]"
]
| |
a7f776db36c6b0cba96799dfdc3fe9e694c450ce | d01df8e1f21f8e8065995a8b13bb5152318680ce | /Playground/src/de/gfn/oca/basicsw/InstVarAusgabe.java | f2d7c9e8857346647e678de8033a6e22b2492dcc | []
| no_license | wsen/Playground230418 | caded0df52c943a70aba59af73a8bddc0e8c1f45 | 009f4f3e6281669843465d31f783f3e1dc7857be | refs/heads/master | 2021-07-10T07:44:51.606552 | 2018-09-28T22:47:36 | 2018-09-28T22:47:36 | 131,116,488 | 0 | 0 | null | 2018-04-26T11:28:43 | 2018-04-26T07:23:59 | Java | UTF-8 | Java | false | false | 704 | java | /*
* 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 de.gfn.oca.basicsw;
/**
*
* @author wsen
*/
class Printer {
int inkLevel;
}
class LaserPrinter extends Printer {
int pagesPerMin;
}
public class InstVarAusgabe {
public static void main(String[] args) {
// LaserPrinter myPrinter = new LaserPrinter();
// System.out.println(myPrinter.pagesPerMin);
// Jetzt class Printer mit CAST LaserPrinter
Printer myPrinter = new LaserPrinter();
System.out.println(((LaserPrinter)myPrinter).pagesPerMin);
}
}
| [
"[email protected]"
]
| |
b7114df32eeaee58c32b705ac6699896629a4a4c | 611b2f6227b7c3b4b380a4a410f357c371a05339 | /src/main/java/android/support/v4/widget/TextViewCompat.java | 5f3fd0ef8d6b0af51bed7490c96e980df15e3db9 | []
| no_license | obaby/bjqd | 76f35fcb9bbfa4841646a8888c9277ad66b171dd | 97c56f77380835e306ea12401f17fb688ca1373f | refs/heads/master | 2022-12-04T21:33:17.239023 | 2020-08-25T10:53:15 | 2020-08-25T10:53:15 | 290,186,830 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 23,768 | java | package android.support.v4.widget;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.annotation.StyleRes;
import android.support.v4.os.BuildCompat;
import android.text.Editable;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public final class TextViewCompat {
public static final int AUTO_SIZE_TEXT_TYPE_NONE = 0;
public static final int AUTO_SIZE_TEXT_TYPE_UNIFORM = 1;
static final TextViewCompatBaseImpl IMPL;
@RestrictTo({RestrictTo.Scope.LIBRARY_GROUP})
@Retention(RetentionPolicy.SOURCE)
public @interface AutoSizeTextType {
}
private TextViewCompat() {
}
static class TextViewCompatBaseImpl {
private static final int LINES = 1;
private static final String LOG_TAG = "TextViewCompatBase";
private static Field sMaxModeField;
private static boolean sMaxModeFieldFetched;
private static Field sMaximumField;
private static boolean sMaximumFieldFetched;
private static Field sMinModeField;
private static boolean sMinModeFieldFetched;
private static Field sMinimumField;
private static boolean sMinimumFieldFetched;
TextViewCompatBaseImpl() {
}
public void setCompoundDrawablesRelative(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
textView.setCompoundDrawables(drawable, drawable2, drawable3, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
textView.setCompoundDrawablesWithIntrinsicBounds(drawable, drawable2, drawable3, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @DrawableRes int i, @DrawableRes int i2, @DrawableRes int i3, @DrawableRes int i4) {
textView.setCompoundDrawablesWithIntrinsicBounds(i, i2, i3, i4);
}
private static Field retrieveField(String str) {
Field field;
try {
field = TextView.class.getDeclaredField(str);
try {
field.setAccessible(true);
} catch (NoSuchFieldException unused) {
}
} catch (NoSuchFieldException unused2) {
field = null;
Log.e(LOG_TAG, "Could not retrieve " + str + " field.");
return field;
}
return field;
}
private static int retrieveIntFromField(Field field, TextView textView) {
try {
return field.getInt(textView);
} catch (IllegalAccessException unused) {
Log.d(LOG_TAG, "Could not retrieve value of " + field.getName() + " field.");
return -1;
}
}
public int getMaxLines(TextView textView) {
if (!sMaxModeFieldFetched) {
sMaxModeField = retrieveField("mMaxMode");
sMaxModeFieldFetched = true;
}
if (sMaxModeField == null || retrieveIntFromField(sMaxModeField, textView) != 1) {
return -1;
}
if (!sMaximumFieldFetched) {
sMaximumField = retrieveField("mMaximum");
sMaximumFieldFetched = true;
}
if (sMaximumField != null) {
return retrieveIntFromField(sMaximumField, textView);
}
return -1;
}
public int getMinLines(TextView textView) {
if (!sMinModeFieldFetched) {
sMinModeField = retrieveField("mMinMode");
sMinModeFieldFetched = true;
}
if (sMinModeField == null || retrieveIntFromField(sMinModeField, textView) != 1) {
return -1;
}
if (!sMinimumFieldFetched) {
sMinimumField = retrieveField("mMinimum");
sMinimumFieldFetched = true;
}
if (sMinimumField != null) {
return retrieveIntFromField(sMinimumField, textView);
}
return -1;
}
public void setTextAppearance(TextView textView, @StyleRes int i) {
textView.setTextAppearance(textView.getContext(), i);
}
public Drawable[] getCompoundDrawablesRelative(@NonNull TextView textView) {
return textView.getCompoundDrawables();
}
public void setAutoSizeTextTypeWithDefaults(TextView textView, int i) {
if (textView instanceof AutoSizeableTextView) {
((AutoSizeableTextView) textView).setAutoSizeTextTypeWithDefaults(i);
}
}
public void setAutoSizeTextTypeUniformWithConfiguration(TextView textView, int i, int i2, int i3, int i4) throws IllegalArgumentException {
if (textView instanceof AutoSizeableTextView) {
((AutoSizeableTextView) textView).setAutoSizeTextTypeUniformWithConfiguration(i, i2, i3, i4);
}
}
public void setAutoSizeTextTypeUniformWithPresetSizes(TextView textView, @NonNull int[] iArr, int i) throws IllegalArgumentException {
if (textView instanceof AutoSizeableTextView) {
((AutoSizeableTextView) textView).setAutoSizeTextTypeUniformWithPresetSizes(iArr, i);
}
}
public int getAutoSizeTextType(TextView textView) {
if (textView instanceof AutoSizeableTextView) {
return ((AutoSizeableTextView) textView).getAutoSizeTextType();
}
return 0;
}
public int getAutoSizeStepGranularity(TextView textView) {
if (textView instanceof AutoSizeableTextView) {
return ((AutoSizeableTextView) textView).getAutoSizeStepGranularity();
}
return -1;
}
public int getAutoSizeMinTextSize(TextView textView) {
if (textView instanceof AutoSizeableTextView) {
return ((AutoSizeableTextView) textView).getAutoSizeMinTextSize();
}
return -1;
}
public int getAutoSizeMaxTextSize(TextView textView) {
if (textView instanceof AutoSizeableTextView) {
return ((AutoSizeableTextView) textView).getAutoSizeMaxTextSize();
}
return -1;
}
public int[] getAutoSizeTextAvailableSizes(TextView textView) {
if (textView instanceof AutoSizeableTextView) {
return ((AutoSizeableTextView) textView).getAutoSizeTextAvailableSizes();
}
return new int[0];
}
public void setCustomSelectionActionModeCallback(TextView textView, ActionMode.Callback callback) {
textView.setCustomSelectionActionModeCallback(callback);
}
}
@RequiresApi(16)
static class TextViewCompatApi16Impl extends TextViewCompatBaseImpl {
TextViewCompatApi16Impl() {
}
public int getMaxLines(TextView textView) {
return textView.getMaxLines();
}
public int getMinLines(TextView textView) {
return textView.getMinLines();
}
}
@RequiresApi(17)
static class TextViewCompatApi17Impl extends TextViewCompatApi16Impl {
TextViewCompatApi17Impl() {
}
public void setCompoundDrawablesRelative(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
boolean z = true;
if (textView.getLayoutDirection() != 1) {
z = false;
}
Drawable drawable5 = z ? drawable3 : drawable;
if (!z) {
drawable = drawable3;
}
textView.setCompoundDrawables(drawable5, drawable2, drawable, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
boolean z = true;
if (textView.getLayoutDirection() != 1) {
z = false;
}
Drawable drawable5 = z ? drawable3 : drawable;
if (!z) {
drawable = drawable3;
}
textView.setCompoundDrawablesWithIntrinsicBounds(drawable5, drawable2, drawable, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @DrawableRes int i, @DrawableRes int i2, @DrawableRes int i3, @DrawableRes int i4) {
boolean z = true;
if (textView.getLayoutDirection() != 1) {
z = false;
}
int i5 = z ? i3 : i;
if (!z) {
i = i3;
}
textView.setCompoundDrawablesWithIntrinsicBounds(i5, i2, i, i4);
}
public Drawable[] getCompoundDrawablesRelative(@NonNull TextView textView) {
boolean z = true;
if (textView.getLayoutDirection() != 1) {
z = false;
}
Drawable[] compoundDrawables = textView.getCompoundDrawables();
if (z) {
Drawable drawable = compoundDrawables[2];
Drawable drawable2 = compoundDrawables[0];
compoundDrawables[0] = drawable;
compoundDrawables[2] = drawable2;
}
return compoundDrawables;
}
}
@RequiresApi(18)
static class TextViewCompatApi18Impl extends TextViewCompatApi17Impl {
TextViewCompatApi18Impl() {
}
public void setCompoundDrawablesRelative(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
textView.setCompoundDrawablesRelative(drawable, drawable2, drawable3, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, drawable2, drawable3, drawable4);
}
public void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @DrawableRes int i, @DrawableRes int i2, @DrawableRes int i3, @DrawableRes int i4) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(i, i2, i3, i4);
}
public Drawable[] getCompoundDrawablesRelative(@NonNull TextView textView) {
return textView.getCompoundDrawablesRelative();
}
}
@RequiresApi(23)
static class TextViewCompatApi23Impl extends TextViewCompatApi18Impl {
TextViewCompatApi23Impl() {
}
public void setTextAppearance(@NonNull TextView textView, @StyleRes int i) {
textView.setTextAppearance(i);
}
}
@RequiresApi(26)
static class TextViewCompatApi26Impl extends TextViewCompatApi23Impl {
TextViewCompatApi26Impl() {
}
public void setCustomSelectionActionModeCallback(final TextView textView, final ActionMode.Callback callback) {
if (Build.VERSION.SDK_INT == 26 || Build.VERSION.SDK_INT == 27) {
textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100;
private boolean mCanUseMenuBuilderReferences;
private boolean mInitializedMenuBuilderReferences = false;
private Class mMenuBuilderClass;
private Method mMenuBuilderRemoveItemAtMethod;
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
return callback.onCreateActionMode(actionMode, menu);
}
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
recomputeProcessTextMenuItems(menu);
return callback.onPrepareActionMode(actionMode, menu);
}
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
return callback.onActionItemClicked(actionMode, menuItem);
}
public void onDestroyActionMode(ActionMode actionMode) {
callback.onDestroyActionMode(actionMode);
}
private void recomputeProcessTextMenuItems(Menu menu) {
Method method;
Context context = textView.getContext();
PackageManager packageManager = context.getPackageManager();
if (!this.mInitializedMenuBuilderReferences) {
this.mInitializedMenuBuilderReferences = true;
try {
this.mMenuBuilderClass = Class.forName("com.android.internal.view.menu.MenuBuilder");
this.mMenuBuilderRemoveItemAtMethod = this.mMenuBuilderClass.getDeclaredMethod("removeItemAt", new Class[]{Integer.TYPE});
this.mCanUseMenuBuilderReferences = true;
} catch (ClassNotFoundException | NoSuchMethodException unused) {
this.mMenuBuilderClass = null;
this.mMenuBuilderRemoveItemAtMethod = null;
this.mCanUseMenuBuilderReferences = false;
}
}
try {
if (!this.mCanUseMenuBuilderReferences || !this.mMenuBuilderClass.isInstance(menu)) {
method = menu.getClass().getDeclaredMethod("removeItemAt", new Class[]{Integer.TYPE});
} else {
method = this.mMenuBuilderRemoveItemAtMethod;
}
for (int size = menu.size() - 1; size >= 0; size--) {
MenuItem item = menu.getItem(size);
if (item.getIntent() != null && "android.intent.action.PROCESS_TEXT".equals(item.getIntent().getAction())) {
method.invoke(menu, new Object[]{Integer.valueOf(size)});
}
}
List<ResolveInfo> supportedActivities = getSupportedActivities(context, packageManager);
for (int i = 0; i < supportedActivities.size(); i++) {
ResolveInfo resolveInfo = supportedActivities.get(i);
menu.add(0, 0, i + 100, resolveInfo.loadLabel(packageManager)).setIntent(createProcessTextIntentForResolveInfo(resolveInfo, textView)).setShowAsAction(1);
}
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException unused2) {
}
}
private List<ResolveInfo> getSupportedActivities(Context context, PackageManager packageManager) {
ArrayList arrayList = new ArrayList();
if (!(context instanceof Activity)) {
return arrayList;
}
for (ResolveInfo next : packageManager.queryIntentActivities(createProcessTextIntent(), 0)) {
if (isSupportedActivity(next, context)) {
arrayList.add(next);
}
}
return arrayList;
}
private boolean isSupportedActivity(ResolveInfo resolveInfo, Context context) {
if (context.getPackageName().equals(resolveInfo.activityInfo.packageName)) {
return true;
}
if (!resolveInfo.activityInfo.exported) {
return false;
}
if (resolveInfo.activityInfo.permission == null || context.checkSelfPermission(resolveInfo.activityInfo.permission) == 0) {
return true;
}
return false;
}
private Intent createProcessTextIntentForResolveInfo(ResolveInfo resolveInfo, TextView textView) {
return createProcessTextIntent().putExtra("android.intent.extra.PROCESS_TEXT_READONLY", !isEditable(textView)).setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
}
private boolean isEditable(TextView textView) {
return (textView instanceof Editable) && textView.onCheckIsTextEditor() && textView.isEnabled();
}
private Intent createProcessTextIntent() {
return new Intent().setAction("android.intent.action.PROCESS_TEXT").setType("text/plain");
}
});
} else {
super.setCustomSelectionActionModeCallback(textView, callback);
}
}
}
@RequiresApi(27)
static class TextViewCompatApi27Impl extends TextViewCompatApi26Impl {
TextViewCompatApi27Impl() {
}
public void setAutoSizeTextTypeWithDefaults(TextView textView, int i) {
textView.setAutoSizeTextTypeWithDefaults(i);
}
public void setAutoSizeTextTypeUniformWithConfiguration(TextView textView, int i, int i2, int i3, int i4) throws IllegalArgumentException {
textView.setAutoSizeTextTypeUniformWithConfiguration(i, i2, i3, i4);
}
public void setAutoSizeTextTypeUniformWithPresetSizes(TextView textView, @NonNull int[] iArr, int i) throws IllegalArgumentException {
textView.setAutoSizeTextTypeUniformWithPresetSizes(iArr, i);
}
public int getAutoSizeTextType(TextView textView) {
return textView.getAutoSizeTextType();
}
public int getAutoSizeStepGranularity(TextView textView) {
return textView.getAutoSizeStepGranularity();
}
public int getAutoSizeMinTextSize(TextView textView) {
return textView.getAutoSizeMinTextSize();
}
public int getAutoSizeMaxTextSize(TextView textView) {
return textView.getAutoSizeMaxTextSize();
}
public int[] getAutoSizeTextAvailableSizes(TextView textView) {
return textView.getAutoSizeTextAvailableSizes();
}
}
static {
if (BuildCompat.isAtLeastOMR1()) {
IMPL = new TextViewCompatApi27Impl();
} else if (Build.VERSION.SDK_INT >= 26) {
IMPL = new TextViewCompatApi26Impl();
} else if (Build.VERSION.SDK_INT >= 23) {
IMPL = new TextViewCompatApi23Impl();
} else if (Build.VERSION.SDK_INT >= 18) {
IMPL = new TextViewCompatApi18Impl();
} else if (Build.VERSION.SDK_INT >= 17) {
IMPL = new TextViewCompatApi17Impl();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new TextViewCompatApi16Impl();
} else {
IMPL = new TextViewCompatBaseImpl();
}
}
public static void setCompoundDrawablesRelative(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
IMPL.setCompoundDrawablesRelative(textView, drawable, drawable2, drawable3, drawable4);
}
public static void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @Nullable Drawable drawable, @Nullable Drawable drawable2, @Nullable Drawable drawable3, @Nullable Drawable drawable4) {
IMPL.setCompoundDrawablesRelativeWithIntrinsicBounds(textView, drawable, drawable2, drawable3, drawable4);
}
public static void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView, @DrawableRes int i, @DrawableRes int i2, @DrawableRes int i3, @DrawableRes int i4) {
IMPL.setCompoundDrawablesRelativeWithIntrinsicBounds(textView, i, i2, i3, i4);
}
public static int getMaxLines(@NonNull TextView textView) {
return IMPL.getMaxLines(textView);
}
public static int getMinLines(@NonNull TextView textView) {
return IMPL.getMinLines(textView);
}
public static void setTextAppearance(@NonNull TextView textView, @StyleRes int i) {
IMPL.setTextAppearance(textView, i);
}
@NonNull
public static Drawable[] getCompoundDrawablesRelative(@NonNull TextView textView) {
return IMPL.getCompoundDrawablesRelative(textView);
}
public static void setAutoSizeTextTypeWithDefaults(@NonNull TextView textView, int i) {
IMPL.setAutoSizeTextTypeWithDefaults(textView, i);
}
public static void setAutoSizeTextTypeUniformWithConfiguration(@NonNull TextView textView, int i, int i2, int i3, int i4) throws IllegalArgumentException {
IMPL.setAutoSizeTextTypeUniformWithConfiguration(textView, i, i2, i3, i4);
}
public static void setAutoSizeTextTypeUniformWithPresetSizes(@NonNull TextView textView, @NonNull int[] iArr, int i) throws IllegalArgumentException {
IMPL.setAutoSizeTextTypeUniformWithPresetSizes(textView, iArr, i);
}
public static int getAutoSizeTextType(@NonNull TextView textView) {
return IMPL.getAutoSizeTextType(textView);
}
public static int getAutoSizeStepGranularity(@NonNull TextView textView) {
return IMPL.getAutoSizeStepGranularity(textView);
}
public static int getAutoSizeMinTextSize(@NonNull TextView textView) {
return IMPL.getAutoSizeMinTextSize(textView);
}
public static int getAutoSizeMaxTextSize(@NonNull TextView textView) {
return IMPL.getAutoSizeMaxTextSize(textView);
}
@NonNull
public static int[] getAutoSizeTextAvailableSizes(@NonNull TextView textView) {
return IMPL.getAutoSizeTextAvailableSizes(textView);
}
public static void setCustomSelectionActionModeCallback(@NonNull TextView textView, @NonNull ActionMode.Callback callback) {
IMPL.setCustomSelectionActionModeCallback(textView, callback);
}
}
| [
"[email protected]"
]
| |
76daf0514ad4285a7e139b53b9871a1d2af1df56 | f37f0e8ad0f62335ba481723bc4187f984aae374 | /GameDev/src/enviroment/Gamer.java | 870e2fe66b224648cdb4064754f8ab58e4c1e544 | []
| no_license | nadissu/JavaWork | 38d59fc862ee0c35c9e632c4e5954134506c07f4 | e2a5db89fc272ade1fa79b9f6f674351fe1f7949 | refs/heads/main | 2023-05-13T20:16:46.410904 | 2021-06-09T10:31:19 | 2021-06-09T10:31:19 | 363,820,869 | 42 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | package enviroment;
public class Gamer implements EntityBase{
private int gamerid;
private String firstName;
private String lastName;
private long nationalIdentity;
private int birthday;
public Gamer() {
}
public Gamer(int gamerid, String firstName, String lastName, long nationalIdentity, int birthday) {
super();
this.gamerid = gamerid;
this.firstName = firstName;
this.lastName = lastName;
this.nationalIdentity = nationalIdentity;
this.birthday = birthday;
}
public int getId() {
return gamerid;
}
public void setId(int id) {
this.gamerid = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getNationalIdentity() {
return nationalIdentity;
}
public void setNationalIdentity(long nationalIdentity) {
this.nationalIdentity = nationalIdentity;
}
public int getBirthday() {
return birthday;
}
public void setBirthday(int birthday) {
this.birthday = birthday;
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.