blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
7c3e22259e2ba447e1a376fab694b320084b6de1
Java
shtsai/algorithm
/java/PossibleBipartition.java
UTF-8
2,121
3.78125
4
[]
no_license
/* Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group. Return true if and only if it is possible to split everyone into two groups in this way. Example 1: Input: N = 4, dislikes = [[1,2],[1,3],[2,4]] Output: true Explanation: group1 [1,4], group2 [2,3] Example 2: Input: N = 3, dislikes = [[1,2],[1,3],[2,3]] Output: false Example 3: Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] Output: false Note: 1 <= N <= 2000 0 <= dislikes.length <= 10000 1 <= dislikes[i][j] <= N dislikes[i][0] < dislikes[i][1] There does not exist i != j for which dislikes[i] == dislikes[j]. */ // Solution 1: Graph // Convert dislikes to edges. // Perform dfs on graph, and check if it is possible to have every connected nodes have different color. // Time: O(e) // Space: O(e) // 08/12/2018 class Solution { public boolean possibleBipartition(int N, int[][] dislikes) { HashMap<Integer, List<Integer>> edges = new HashMap<>(); for (int i = 1; i <= N; i++) { edges.put(i, new ArrayList<Integer>()); } for (int[] d : dislikes) { edges.get(d[0]).add(d[1]); edges.get(d[1]).add(d[0]); } HashMap<Integer, Boolean> colors = new HashMap<>(); for (int i = 1; i <= N; i++) { if (!colors.containsKey(i) && !dfs(edges, colors, 1, true)) { return false; } } return true; } private boolean dfs(HashMap<Integer, List<Integer>> edges, HashMap<Integer, Boolean> colors, int n, boolean group) { if (colors.containsKey(n)) { return colors.get(n) == group; } colors.put(n, group); for (Integer e : edges.get(n)) { if (!dfs(edges, colors, e, !group)) { return false; } } return true; } }
true
142535d179a940b6755a95958e163ae0cfce8493
Java
BartP97/1665399-dojo
/labs/01-legacy-code/src/main/java/org/joyofcoding/objectcalisthenics/Primitive/Quality.java
UTF-8
151
1.703125
2
[]
no_license
package org.joyofcoding.objectcalisthenics.Primitive; /** * Created by bart-_000 on 27-3-2017. */ public class Quality { private int quality; }
true
bc9efb825217d2e78a27b00da62a0c41952ccca5
Java
ZhangYunJieZhang/micro-service
/springcloud-sentinel/src/main/java/com/zyj/springcloud/handler/BlockHandler2.java
UTF-8
2,080
2.28125
2
[]
no_license
package com.zyj.springcloud.handler; import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; import com.alibaba.csp.sentinel.slots.block.flow.FlowException; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException; import com.alibaba.csp.sentinel.slots.system.SystemBlockException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * 处理限流方式二 * 实现限流接口统一处理 */ @Component public class BlockHandler2 implements BlockExceptionHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception { System.out.println("BlockExceptioonHandler ++++++++++++++++++++++++++"+e.getRule()); Map<Integer,String> hashMap=new HashMap<>(); if(e instanceof FlowException){ hashMap.put(100,"接口限流了"); }else if(e instanceof DegradeException){ hashMap.put(101,"服务降级了"); }else if(e instanceof ParamFlowException){ hashMap.put(102,"热点参数限流了"); }else if(e instanceof SystemBlockException){ hashMap.put(103,"触发系统保护规则了"); }else if(e instanceof AuthorityException){ hashMap.put(104,"授权规则不通过"); } //返回json数据 httpServletResponse.setStatus(500); httpServletResponse.setCharacterEncoding("utf-8"); httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); new ObjectMapper().writeValue(httpServletResponse.getWriter(),hashMap); } }
true
94e365248b05ac6272743653a478dc5856b66369
Java
swyeah/decorationsystem
/src/main/java/com/sise/po/MaterialOffer.java
UTF-8
1,927
2.40625
2
[]
no_license
package com.sise.po; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; /** * @Author:swye * @Description: * @Date:Create in 20:55 2018/2/24 */ public class MaterialOffer implements Serializable { private static final long serialVersionUID = 346357563165833491L; private Integer offerId; @NotNull(message = "供应商名字不能为空") @Size(max = 100,min = 1,message = "供应商名字长度必须在1-100之间") private String offerName; @NotNull(message = "供应商电话号码不能为空") @Size(min = 11,max = 11,message = "供应商电话号码长度为11") private String offerPhone; @NotNull(message = "供应商地址不能为空") @Size(min = 1,max = 100,message = "供应商地址长度必须在1-100之间") private String offerAddress; public MaterialOffer() { } public Integer getOfferId() { return offerId; } public void setOfferId(Integer offerId) { this.offerId = offerId; } public String getOfferName() { return offerName; } public void setOfferName(String offerName) { this.offerName = offerName; } public String getOfferPhone() { return offerPhone; } public void setOfferPhone(String offerPhone) { this.offerPhone = offerPhone; } public String getOfferAddress() { return offerAddress; } public void setOfferAddress(String offerAddress) { this.offerAddress = offerAddress; } @Override public String toString() { return "MaterialOffer{" + "offerId=" + offerId + ", offerName='" + offerName + '\'' + ", offerPhone='" + offerPhone + '\'' + ", offerAddress='" + offerAddress + '\'' + '}'; } }
true
b50628895b190909774cfc06f18df98ac5730eb1
Java
google-code/anhquan
/Quiz/docs/restlet-jee/org.restlet.ext.servlet/org/restlet/ext/servlet/ServletUtils.java
UTF-8
2,931
2.140625
2
[]
no_license
/** * Copyright 2005-2010 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.ext.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.restlet.Request; import org.restlet.Response; import org.restlet.engine.http.Call; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; import org.restlet.ext.servlet.internal.ServletCall; /** * Servlet related utilities. * * @author Jerome Louvel */ public final class ServletUtils { /** * Returns the Servlet request that was used to generate the given Restlet * request. * * @param request * The Restlet request. * @return The Servlet request or null. */ public static HttpServletRequest getRequest(Request request) { HttpServletRequest result = null; if (request instanceof HttpRequest) { Call call = ((HttpRequest) request).getHttpCall(); if (call instanceof ServletCall) { result = ((ServletCall) call).getRequest(); } } return result; } /** * Returns the Servlet response that was used to generate the given Restlet * response. * * @param response * The Restlet response. * @return The Servlet request or null. */ public static HttpServletResponse getResponse(Response response) { HttpServletResponse result = null; if (response instanceof HttpResponse) { Call call = ((HttpResponse) response).getHttpCall(); if (call instanceof ServletCall) { result = ((ServletCall) call).getResponse(); } } return result; } }
true
310072532a2e7605971972f1197677d69add452d
Java
timothyb89/scoring
/src/main/java/net/frcdb/scoring/game/Group.java
UTF-8
690
2.578125
3
[]
no_license
package net.frcdb.scoring.game; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; /** * Defines a scoring group. Scoring groups define a set of scoring parameters * which will be combined and displayed on-screen in the match UI. The actual * group definition is simple and is primarily intended for ordering and naming. * @author tim */ @XStreamAlias("group") public class Group { @XStreamAsAttribute private String name; public Group() { } public Group(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
59910bdae72e01b467f95a36de75416393eb45a8
Java
liudongpu/yeshospital
/yeshospital/src/main/java/com/srnpr/yeshospital/api/app/MemberLast.java
UTF-8
1,825
2
2
[]
no_license
package com.srnpr.yeshospital.api.app; import org.apache.commons.lang.StringUtils; import com.srnpr.zapcom.basemodel.MDataMap; import com.srnpr.zapcom.topapi.RootApi; import com.srnpr.zapdata.dbdo.DbUp; import com.srnpr.zapweb.webapi.RootApiForToken; /** * 根据卡号获取用户信息 * * @author srnpr * */ public class MemberLast extends RootApiForToken<MemberLastResult, MemberLastInput> { public MemberLastResult Process(MemberLastInput inputParam, MDataMap mRequestMap) { MemberLastResult result = new MemberLastResult(); // 取出卡号对应的用户编号 if (result.upFlagTrue()) { Object object = DbUp .upTable("yh_member_extend_geracomium") .dataGet("member_code", "", new MDataMap("post_card", inputParam.getPostCard())); if (object != null&&StringUtils.isNotBlank(object.toString())) { result.setMemberCode(object.toString()); } else { result.inErrorMessage(965806001, inputParam.getPostCard()); } } if (result.upFlagTrue()) { if (StringUtils.isNotBlank(inputParam.getOrderCode())) { result.setOrderCode(inputParam.getOrderCode()); } else { String sGCode = DbUp .upTable("yh_member_extend_geracomium") .dataGet("geracomium_code", "", new MDataMap("member_code", result.getMemberCode())) .toString(); MDataMap mTourMap = DbUp .upTable("yh_tour_order_info") .oneWhere( "", "-zid", "order_status='46580001000500020001' and geracomium_code=:geracomium_code", "geracomium_code", sGCode); if (mTourMap != null && mTourMap.size() > 0) { result.setOrderCode(mTourMap.get("tour_code")); } else { result.inErrorMessage(965806002); } } } return result; } }
true
2fcada60336ba4836c99bd1aae561e171c0da92e
Java
vishwajit09/openshift
/MOBILE-APP-WS/src/main/java/com/vis/app/ws/model/ErrorMessageResponse.java
UTF-8
926
2.15625
2
[]
no_license
/** * */ package com.vis.app.ws.model; import javax.xml.bind.annotation.XmlRootElement; /** * @author Visu * */ @XmlRootElement public class ErrorMessageResponse { private String errorMessage; private String errorMessageKey; private String href; public ErrorMessageResponse() { } public ErrorMessageResponse(String errorMessage, String errorMessageKey, String href) { this.errorMessage = errorMessage; this.errorMessageKey = errorMessageKey; this.href = href; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorMessageKey() { return errorMessageKey; } public void setErrorMessageKey(String errorMessageKey) { this.errorMessageKey = errorMessageKey; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
true
bcc8aa3b7031f1733fb32bc85928038a0d8b0cc5
Java
PlatONnetwork/mtool
/common/src/main/java/com/platon/mtool/common/exception/MtoolServerException.java
UTF-8
506
2.03125
2
[]
no_license
package com.platon.mtool.common.exception; /** * mtool服务端异常 * * <p>Created by liyf. */ public class MtoolServerException extends MtoolException { private static final long serialVersionUID = 7235708326504559767L; public MtoolServerException(String message) { super(message); } public MtoolServerException(String message, Object... args) { super(message, args); } public MtoolServerException(String message, Throwable throwable) { super(message, throwable); } }
true
c201e8560a8e219aebbfdc51830072c446edc8f2
Java
LizaShak/mts-services
/build-tools/src/main/java/uk/ac/ox/ndph/mts/json_schema_generator/model/SpringCloud.java
UTF-8
441
1.8125
2
[ "MIT" ]
permissive
package uk.ac.ox.ndph.mts.json_schema_generator.model; import com.fasterxml.jackson.annotation.JsonProperty; public class SpringCloud { @JsonProperty(value = "gateway_service", required = true) private Service gatewayService; @JsonProperty(value = "discovery_service", required = true) private Service discoveryService; @JsonProperty(value = "config_server", required = true) private ConfigServer configServer; }
true
45e56fc0402fd7955aa9cd873afc9d73262ea9d7
Java
spals/appbuilder
/mapstore-core/src/main/java/net/spals/appbuilder/mapstore/core/MapStoreIndex.java
UTF-8
1,792
2.53125
3
[ "BSD-3-Clause" ]
permissive
package net.spals.appbuilder.mapstore.core; import net.spals.appbuilder.mapstore.core.model.MapQueryOptions; import net.spals.appbuilder.mapstore.core.model.MapStoreIndexName; import net.spals.appbuilder.mapstore.core.model.MapStoreKey; import net.spals.appbuilder.mapstore.core.model.MapStoreTableKey; import java.io.Closeable; import java.util.List; import java.util.Map; import java.util.Optional; /** * A service which represents an index of a {@link MapStore}. * <p> * Note that this is a separate service because not all * {@link MapStorePlugin} implementations may support indexes. * Also note, that indexes are read only. They will always * be populated automatically with writes to {@link MapStore}. * * @author tkral */ public interface MapStoreIndex extends Closeable { /** * Creates an index with the given key. * * Note that the table must already exist. * * @return true iff the creation was successful */ boolean createIndex( MapStoreIndexName indexName, MapStoreTableKey indexKey ); /** * Drops an index. * * @return true iff the drop was successful */ boolean dropIndex(MapStoreIndexName indexName); /** * Retrieves an item from the given index * with the given key. * * Returns {@link Optional#empty()} if no * item exists with the given key. */ Optional<Map<String, Object>> getItem( MapStoreIndexName indexName, MapStoreKey key ); /** * Queries all items from the given index * which match the given {@link MapStoreKey} * range key operator. */ List<Map<String, Object>> getItems( MapStoreIndexName indexName, MapStoreKey key, MapQueryOptions options ); }
true
78ffd99577d0f9ff6ed7b807d605ad7cbfabf6b1
Java
maulidta/menu-hewan
/app/src/main/java/com/example/dashboard/Page_Birds.java
UTF-8
558
1.851563
2
[]
no_license
package com.example.dashboard; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; public class Page_Birds extends Fragment { //constructor default public Page_Birds(){ }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View PageBrd = super.onCreateView(inflater, container, savedInstanceState); return PageBrd; } }
true
40d248ae681fa77101e6f1e43923786acd9d0ad3
Java
hapreanmanuel/shop
/src/test/java/ro/msg/learning/shop/order/OrderBehaviorTest.java
UTF-8
2,449
2.3125
2
[]
no_license
package ro.msg.learning.shop.order; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import ro.msg.learning.shop.domain.Address; import ro.msg.learning.shop.domain.Order; import ro.msg.learning.shop.dto.OrderCreationDto; import ro.msg.learning.shop.dto.OrderSpecifications; import ro.msg.learning.shop.dto.ShoppingCartEntry; import ro.msg.learning.shop.service.ShopService; import ro.msg.learning.shop.service.StockService; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest public class OrderBehaviorTest { private final String username = "test"; private final List<ShoppingCartEntry> wishList = Arrays.asList( new ShoppingCartEntry(1,10), new ShoppingCartEntry(2,20) ); private final Address address = Address.builder() .city("Cluj-Napoca").country("Romania").region("CJ").fullAddress("Str. Dave Mira 111").build(); @Autowired private ShopService shopService; @Autowired private StockService stockService; @Test public void orderOperations(){ log.info("====================================================================="); log.info("Running test: Order Creation and Processing"); OrderCreationDto request = new OrderCreationDto(); request.setShoppingCart(wishList); request.setAddress(address); OrderSpecifications os = shopService.createOrderSpecifications(request,username); log.info("Request: {}", os.toString()); Order order = shopService.createNewOrder(os); log.info("Created Order: {}", order.toString()); assertThat(order).isInstanceOf(Order.class); assertThat(order.isRevenued()).isEqualTo(false); assertThat(order.getLocation()).isEqualTo(null); assertThat(order.getStatus()).isEqualByComparingTo(Order.Status.PROCESSING); order = stockService.processOrder(order.getOrderId()); log.info("Processed Order: {}", order.toString()); assertThat(order.getLocation()).isNotEqualTo(null); assertThat(order.getStatus()).isEqualByComparingTo(Order.Status.COMPLETE); } }
true
b474395fdbf5b056785bc49a3887853c9265febe
Java
mpas97/cineast
/cineast-core/src/main/java/org/vitrivr/cineast/core/extraction/decode/video/VideoOutputStreamContainer.java
UTF-8
4,974
1.859375
2
[ "MIT" ]
permissive
package org.vitrivr.cineast.core.extraction.decode.video; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bytedeco.javacpp.*; import org.vitrivr.cineast.core.data.raw.images.MultiImage; import org.vitrivr.cineast.core.util.MathHelper; import static org.bytedeco.javacpp.avcodec.*; import static org.bytedeco.javacpp.avutil.*; import static org.bytedeco.javacpp.swscale.sws_freeContext; class VideoOutputStreamContainer extends AbstractAVStreamContainer { private static final Logger LOGGER = LogManager.getLogger(); int frameCounter = 0; private AVFrame rgbFrame, outFrame; private swscale.SwsContext sws_ctx; VideoOutputStreamContainer(int width, int height, int bitRate, float frameRate, avformat.AVFormatContext oc, int codec_id, AVDictionary opt) { super(oc, codec_id); if (codec.type() != avutil.AVMEDIA_TYPE_VIDEO) { LOGGER.error("Not a video codec"); return; } int[] frameRateFraction = MathHelper.toFraction(frameRate); c.bit_rate(bitRate); c.width(width); c.height(height); c.gop_size(10); c.max_b_frames(1); c.pix_fmt(avutil.AV_PIX_FMT_YUV420P); AVRational timeBase = new AVRational(); timeBase.num(frameRateFraction[1]); timeBase.den(frameRateFraction[0]); st.time_base(timeBase); c.time_base(st.time_base()); AVRational fps = new AVRational(); fps.den(frameRateFraction[1]); fps.num(frameRateFraction[0]); c.framerate(fps); if (c.codec_id() == avcodec.AV_CODEC_ID_MPEG2VIDEO) { c.max_b_frames(2); } if (c.codec_id() == avcodec.AV_CODEC_ID_MPEG1VIDEO) { c.mb_decision(2); } if (codec.id() == avcodec.AV_CODEC_ID_H264) { avutil.av_opt_set(c.priv_data(), "preset", "slow", 0); } if ((oc.oformat().flags() & avformat.AVFMT_GLOBALHEADER) != 0) { oc.oformat().flags(oc.oformat().flags() | avformat.AVFMT_GLOBALHEADER); } AVDictionary topt = new AVDictionary(); av_dict_copy(topt, opt, 0); /* open the codec */ int ret = avcodec_open2(c, codec, topt); av_dict_free(topt); if (ret < 0) { LOGGER.error("Could not open video codec: {}", ret); return; } rgbFrame = avutil.av_frame_alloc(); if (rgbFrame == null) { LOGGER.error("Could not allocate frame"); return; } rgbFrame.format(avutil.AV_PIX_FMT_RGB24); rgbFrame.width(c.width()); rgbFrame.height(c.height()); ret = avutil.av_frame_get_buffer(rgbFrame, 32); if (ret < 0) { LOGGER.error("Could not allocate video frame data"); return; } outFrame = avutil.av_frame_alloc(); if (outFrame == null) { LOGGER.error("Could not allocate frame"); return; } outFrame.format(c.pix_fmt()); outFrame.width(c.width()); outFrame.height(c.height()); ret = avutil.av_frame_get_buffer(outFrame, 32); if (ret < 0) { LOGGER.error("Could not allocate video frame data"); return; } /* copy the stream parameters to the muxer */ ret = avcodec_parameters_from_context(st.codecpar(), c); if (ret < 0) { LOGGER.error("Could not copy the stream parameters"); return; } sws_ctx = swscale.sws_getContext(c.width(), c.height(), avutil.AV_PIX_FMT_RGB24, c.width(), c.height(), c.pix_fmt(), swscale.SWS_BILINEAR, null, null, (DoublePointer) null); } void addFrame(MultiImage img) { int ret = avutil.av_frame_make_writable(outFrame); if (ret < 0) { return; } ret = avutil.av_frame_make_writable(rgbFrame); if (ret < 0) { return; } int[] pixels = img.getColors(); for (int i = 0; i < pixels.length; ++i) { rgbFrame.data(0).put(3 * i, (byte) (((pixels[i]) >> 16) & 0xff)); rgbFrame.data(0).put(3 * i + 1, (byte) (((pixels[i]) >> 8) & 0xff)); rgbFrame.data(0).put(3 * i + 2, (byte) ((pixels[i]) & 0xff)); } swscale.sws_scale(sws_ctx, rgbFrame.data(), rgbFrame.linesize(), 0, outFrame.height(), outFrame.data(), outFrame.linesize()); outFrame.pts(this.frameCounter++); encode(c, outFrame, pkt); } void close() { if (c != null && !c.isNull()) { avcodec_free_context(c); } if (rgbFrame != null && !rgbFrame.isNull()) { av_frame_free(rgbFrame); } if (outFrame != null && !outFrame.isNull()) { av_frame_free(outFrame); } if (sws_ctx != null && !sws_ctx.isNull()) { sws_freeContext(sws_ctx); } } }
true
2eb004ec7987ab086ee4690f623a67372922926a
Java
TeamGY/ViewGroupAdpterByDJ
/containers/actiontitle/ActionMenu.java
UTF-8
759
2.203125
2
[]
no_license
package com.hyj.containers.actiontitle; import java.util.List; public interface ActionMenu { public ActionItem addLeftBar(CharSequence title); public ActionItem addLeftBar(int titleResId); public ActionItem addLeftBar(CharSequence title,int orderId,int itemId); public ActionItem addLeftBar(int titleResId,int orderId,int itemId); public ActionItem getLeftBarItem(); public ActionItem addRightBar(CharSequence title); public ActionItem addRightBar(int titleResId); public ActionItem addRightBar(CharSequence title,int orderId,int itemId); public ActionItem addRightBar(int titleResId,int orderId,int itemId); public List<ActionItem> getRightBarItems(); public ActionItem add(CharSequence title,int itemId,int orderId); }
true
02f99b8ffc0dfb9a898eb5f3f8a21664e9f07713
Java
mrmar096/HelloInnoCV
/app/src/main/java/com/mrmarapps/helloinnocv/mvp/fragment/BaseMVPFragment.java
UTF-8
2,113
2.15625
2
[]
no_license
package com.mrmarapps.helloinnocv.mvp.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mrmarapps.helloinnocv.di.fragment.InjectedFragment; import com.mrmarapps.helloinnocv.mvp.PresenterActions; import javax.inject.Inject; /** * Created by mario on 11/09/17. */ public abstract class BaseMVPFragment<PRESENTER extends BaseMVPFragmentPresenter, LISTENER extends PresenterActions> extends InjectedFragment { public LISTENER actions; @Inject protected PRESENTER presenter; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (savedInstanceState != null) { onRestoreInstanceState(savedInstanceState); } return inflater.inflate(getFragmentLayout(), container, false); } protected void onRestoreInstanceState(Bundle savedInstanceState) { } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); presenter.onViewCreated(view); if (actions != null) { presenter.setListener(actions); } } @Override public void onAttach(Context context) { if (presenter == null) { inject(context); } presenter.setListener(actions); super.onAttach(context); } @Override public void onDestroyView() { presenter.onDestroyView(); super.onDestroyView(); } public abstract void inject(Context context); public PRESENTER getPresenter() { return presenter; } public void setListener(LISTENER actions) { this.actions = actions; if (presenter != null) { presenter.setListener(actions); } } public LISTENER getListener() { return actions; } }
true
a9118bf83bd774558257ad0734c57edbdd6ce735
Java
TimmosQuadros/CA2
/src/main/java/entity/Address.java
UTF-8
4,476
2.0625
2
[]
no_license
/* * 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 entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author TimmosQuadros */ @Entity @Table(name = "address") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Address.findAll", query = "SELECT a FROM Address a"), @NamedQuery(name = "Address.findByIdAddress", query = "SELECT a FROM Address a WHERE a.idAddress = :idAddress"), @NamedQuery(name = "Address.findByAdditionalInfo", query = "SELECT a FROM Address a WHERE a.additionalInfo = :additionalInfo"), @NamedQuery(name = "Address.findByStreet", query = "SELECT a FROM Address a WHERE a.street = :street")}) public class Address implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @NotNull @Column(name = "idAddress") private Integer idAddress; @Size(max = 255) @Column(name = "additionalInfo") private String additionalInfo; @Size(max = 255) @Column(name = "street") private String street; @JoinColumn(name = "Cityinfo_idCityinfo", referencedColumnName = "idCityinfo") @ManyToOne private Cityinfo cityinfoidCityinfo; @OneToMany(cascade = CascadeType.ALL, mappedBy = "addressidAddress") private Collection<Infoentity> infoentityCollection; public Address() { } public Address(String additionalInfo, String street, Cityinfo cityinfoidCityinfo, Collection<Infoentity> infoentityCollection) { this.additionalInfo = additionalInfo; this.street = street; this.cityinfoidCityinfo = cityinfoidCityinfo; this.infoentityCollection = infoentityCollection; } public Address(Integer idAddress) { this.idAddress = idAddress; } public Integer getIdAddress() { return idAddress; } public void setIdAddress(Integer idAddress) { this.idAddress = idAddress; } public String getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public Cityinfo getCityinfoidCityinfo() { return cityinfoidCityinfo; } public void setCityinfoidCityinfo(Cityinfo cityinfoidCityinfo) { this.cityinfoidCityinfo = cityinfoidCityinfo; } @XmlTransient public Collection<Infoentity> getInfoentityCollection() { return infoentityCollection; } public void setInfoentityCollection(Collection<Infoentity> infoentityCollection) { this.infoentityCollection = infoentityCollection; } @Override public int hashCode() { int hash = 0; hash += (idAddress != null ? idAddress.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Address)) { return false; } Address other = (Address) object; if ((this.idAddress == null && other.idAddress != null) || (this.idAddress != null && !this.idAddress.equals(other.idAddress))) { return false; } return true; } @Override public String toString() { return "entity.Address[ idAddress=" + idAddress + " ]"; } }
true
ad4e5efa29eb91123205a2d3435ef7176aa0cee3
Java
njradford/Hybridity
/core/src/com/solanum/hybridity/Bullet.java
UTF-8
4,060
2.96875
3
[]
no_license
package com.solanum.hybridity; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.Actor; import java.util.Iterator; /** * @author Aldous * <p/> * Basic projectile that can be used by multiple classes and have it's allegience switched. */ public class Bullet extends Actor { private final Sprite bulletSprite; private final double speed; private final double angle; private float timeSinceSpawn; public Bullet(float x, float y, float angle) { Pixmap bulletPixmap = new Pixmap(10, 10, Pixmap.Format.RGB888); bulletPixmap.setColor(Color.WHITE); bulletPixmap.fill(); Texture bulletTexture = new Texture("Bullet.png"); bulletSprite = new Sprite(bulletTexture); bulletSprite.setRotation(angle); bulletSprite.setPosition(x - bulletSprite.getWidth() / 2, y - bulletSprite.getHeight() / 2); setPosition(bulletSprite.getX(), bulletSprite.getY()); setWidth(bulletSprite.getWidth()); setHeight(bulletSprite.getHeight()); this.speed = (double) 20; this.angle = angle; setOrigin(this.getX() + bulletSprite.getWidth() / 2, this.getY() + bulletSprite.getHeight() / 2); timeSinceSpawn = 0; setWidth(bulletSprite.getWidth()); setHeight(bulletSprite.getHeight()); } public void act(float delta) { /** * Update the position of the Bullet in the field */ double sin = Math.sin(Math.toRadians(angle)); double height = sin * speed; double width = Math.sqrt((speed * speed) - (height * height)); /** * Correct the angle if it is out of an applicable range. */ if (angle > 90 && angle < 270) { width = -width; } setPosition((float) (getX() + width), (float) (getY() + height)); bulletSprite.setPosition(getX(), getY()); timeSinceSpawn += delta; /** * Terminate this actor if it is older than 10 seconds. */ if (timeSinceSpawn > 10) { this.destroy(); } int centerX = (int) (getX() + (getWidth() / 2)); int centerY = (int) (getY() + (getHeight() / 2)); Iterator<Actor> actors = null; try{ actors = getStage().getActors().iterator(); } catch(Exception e ){ } if (GameScreen.phase == 1) { if (!((Mainland) getStage().getRoot().findActor("ml")).containsPoint(centerX, centerY)) { this.destroy(); } } /** * Checks this Actor against all Seeders in play, calls the hit method of any colliding Seeders, * and then terminates this Actor. */ if (actors != null) { while (actors.hasNext()) { Actor c = actors.next(); if (c instanceof Seeder) { Rectangle seederC = ((Seeder) c).collision; if (Intersector.overlaps(bulletSprite.getBoundingRectangle(), seederC) && !((Seeder) c).following) { ((Seeder) c).hit(); this.destroy(); } } else if (c instanceof Enemy){ Rectangle enemyC = ((Enemy) c).collision; if (Intersector.overlaps(bulletSprite.getBoundingRectangle(), enemyC) && ((Enemy) c).following) { ((Enemy) c).hit(); this.destroy(); } }; } } } public void draw(Batch batch, float parentAlpha) { bulletSprite.draw(batch); } /** * Removes this Bullet from play */ void destroy() { remove(); } }
true
18e1469994ff66e34d0410719e6a00aead3c5bcb
Java
RennanEmanoel/Java
/Pratica/Java_Teste/src/curso_java/Função.java
ISO-8859-1
302
3.015625
3
[]
no_license
package curso_java; public class Funo { static int soma(int a, int b, int c) { int s = a + b - c; return(s); } public static void main(String[] args) { System.out.println("Comeou a prutaria"); int sn = soma(13, 1, 1); System.out.println("A soma "+sn); } }
true
6a42a1190090946ec7d60885833c67fa9fa9b2bc
Java
moutainhigh/promotion
/MarketingCampaign-Service/src/main/java/cn/ipanel/apps/marketing/campaign/service/controller/resp/back/GoodsBackVO.java
UTF-8
795
2.015625
2
[]
no_license
package cn.ipanel.apps.marketing.campaign.service.controller.resp.back; import cn.ipanel.apps.marketing.campaign.service.entity.GoodsInfo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * Created with Intellij IDEA. * * @author luzh * Create: 2018/8/20 下午3:32 * Modified By: * Description: */ @Data public class GoodsBackVO { @ApiModelProperty(value = "商品Id", required = true) private Integer id; @ApiModelProperty(value = "名称", required = true) private String name; @ApiModelProperty(value = "编号", required = true) private String code; public GoodsBackVO(GoodsInfo goodsInfo) { this.id = goodsInfo.getId(); this.name = goodsInfo.getGoodsName(); this.code = goodsInfo.getGoodsCode(); } }
true
6790031c0e29d4b745be1d4f757e4bf0a83ea200
Java
mquintas/codility-exercises
/src/com/maq/codewars/SimpleCardGame.java
UTF-8
1,727
3.671875
4
[]
no_license
package com.maq.codewars; import java.util.HashMap; import java.util.Map; public class SimpleCardGame { public static void main(String[] args) { System.out.println(winner(new String[]{"A", "7", "8"}, new String[]{"K", "5", "9"})); System.out.println(winner(new String[]{"T"}, new String[]{"T"})); System.out.println(winner(new String[]{"A", "7", "8"}, new String[]{"A", "8", "9"})); } public static String winner(String[] deckSteve, String[] deckJosh) { Map<String, Integer> deck = new HashMap<String, Integer>(); deck.put("2", 1); deck.put("3", 2); deck.put("4", 3); deck.put("5", 4); deck.put("6", 5); deck.put("7", 6); deck.put("8", 7); deck.put("9", 8); deck.put("T", 9); deck.put("J", 10); deck.put("Q", 11); deck.put("K", 12); deck.put("A", 13); int[] points = {0,0}; for (int i = 0 ; i < deckSteve.length; i++) { int winner = checkCards(deckSteve[i], deckJosh[i], deck); if (winner != -1) { points[winner]++; } } if (points[0] == points[1]) { return "Tie"; } else if (points[0] > points[1]) { return "Steve wins "+points[0]+" to "+points[1]; } else { return "Josh wins "+points[1]+" to "+points[0]; } } private static int checkCards(String card1, String card2, Map<String, Integer> deck) { if( (deck.get(card1)) == (deck.get(card2)) ) { return -1; } else if( (deck.get(card1)) > (deck.get(card2)) ) { return 0; } else { return 1; } } }
true
dad53104fc6d7ab6dc9b86bc0b8317abf17f936c
Java
Harshaprakashsunkari/library-management-collection
/librarymanagementjdbc/src/main/java/com/capgemini/librarymanagementjdbc/controller/LibraryManagementJDBCController.java
UTF-8
6,280
2.78125
3
[]
no_license
package com.capgemini.librarymanagementjdbc.controller; import java.util.Scanner; import com.capgemini.librarymanagementjdbc.dto.Book; import com.capgemini.librarymanagementjdbc.dto.User; import com.capgemini.librarymanagementjdbc.factory.AdminFactory; import com.capgemini.librarymanagementjdbc.factory.StudentFactory; import com.capgemini.librarymanagementjdbc.factory.UserFactory; import com.capgemini.librarymanagementjdbc.service.AdminService; import com.capgemini.librarymanagementjdbc.service.StudentService; import com.capgemini.librarymanagementjdbc.service.UserService; public class LibraryManagementJDBCController { public static void main(String[] args) { doReg(); } public static void doReg() { Scanner scanner = new Scanner(System.in); do { System.out.println("Press 1 to Register"); System.out.println("Press 2 to Login"); UserService service = UserFactory.getUserService(); AdminService service1 = AdminFactory.getAdminService(); int i = scanner.nextInt(); switch(i) { case 1: System.out.println("Enter Name"); String regName = scanner.next(); System.out.println("Enter Email"); String regEmail = scanner.next(); System.out.println("Enter Password"); String regPassword = scanner.next(); System.out.println("Enter Mobile"); long regMobile = scanner.nextLong(); System.out.println("Enter Role"); String regRole = scanner.next(); System.out.println("Enter ID"); int regID = scanner.nextInt(); User bean = new User(); bean.setId(regID); bean.setName(regName); bean.setMobile(regMobile); bean.setEmail(regEmail); bean.setPassword(regPassword); bean.setRole(regRole); try { int check = service.register(bean); if(check == 0) { System.out.println("Email already exists"); } else { System.out.println("Registered Successfully"); } }catch(Exception e) { System.out.println("Invalid"); } break; case 2: String student = null; String admin = null; String role = null; System.out.println("Enter Email"); String email = scanner.next(); System.out.println("Enter Password"); String password = scanner.next(); try { String auth = service.auth(email, password); if(auth.equalsIgnoreCase("Admin")) { admin(); }else if(auth.equalsIgnoreCase("Student")){ System.out.println("Student"); } else { System.out.println("Invalid email and password"); } }catch(Exception e) { System.out.println("Invalid credentials"); } break; } }while(true); } public static void admin() { UserService service = UserFactory.getUserService(); AdminService service1 = AdminFactory.getAdminService(); Scanner scanner = new Scanner(System.in); System.out.println("Press 1 to Add Book"); System.out.println("Press 2 to Remove Book"); System.out.println("Press 3 to Issue book"); System.out.println("Press 4 to Main"); int choice1 = scanner.nextInt(); switch (choice1) { case 1: System.out.println("Enter ID"); int bookId = scanner.nextInt(); System.out.println("Enter Book Name"); String bookName = scanner.next(); System.out.println("Enter Author"); String bookAuthor = scanner.next(); System.out.println("Enter Publisher Name"); String bookPublisher = scanner.next(); Book bean2 = new Book(); bean2.setBookId(bookId); bean2.setBookName(bookName); bean2.setBookAuthor(bookAuthor); bean2.setBookPublisher(bookPublisher); int check = service1.addBook(bean2); if(check==0) { System.out.println("Book already exists"); } else { System.out.println("Book added"); } break; case 2: System.out.println("Enter the Book Id:"); int book_Id = scanner.nextInt(); if (book_Id == 0) { System.out.println("Enter the Valid Book Id"); } else { Book bean3 = new Book(); bean3.setBookId(book_Id); int remove = service1.removeBook(book_Id); if (remove == 0) { System.out.println("The Book is not removed"); } else { System.out.println("The Book is removed"); } } break; case 3: // Issue book } } public static void student() { Scanner scanner = new Scanner(System.in); StudentService service2 = StudentFactory.getStudentService(); do { try { System.out.println("Press 1 to Request a book"); System.out.println("Press 2 to Search a Book Id"); System.out.println("Press 3 to Borrow a book"); System.out.println("Press 4 to Return a book"); System.out.println("Press 5 to Main"); int choice2 = scanner.nextInt(); switch (choice2) { case 1: System.out.println("Enter Book Id"); int reqBookId = scanner.nextInt(); System.out.println("Enter Author Name"); String reqBookAuthor = scanner.next(); boolean book = service2.placeReq(reqBookId, reqBookAuthor); if(book) { System.out.println("Requested Successfully"); }else { System.out.println("Book Not Found"); } break; case 2: System.out.println("Enter Book id"); int id = scanner.nextInt(); Book bean5 = new Book(); bean5.setBookId(id); Book list2 = service2.searchBook(id); if(list2!=null) { System.out.println(list2.getBookId()); System.out.println(list2.getBookName()); System.out.println(list2.getBookAuthor()); System.out.println(list2.getBookPublisher()); System.out.println(list2); } else { System.out.println("Book Not Found"); } break; case 3: // Borrow book case 4: System.out.println("enter id"); int returned = scanner.nextInt(); boolean returnBook = service2.returnBook(returned); if(returnBook) { System.out.println("Book returned"); }else { System.out.println("Book not Returned"); } break; default: break; } } catch (Exception e) { System.out.println("Invalid Credentials"); } break; }while(true); } }
true
c510f19a43dbc840f6220fbe0ba110d0eaabb8d5
Java
lilidejing/RkmFactoryTest
/src/com/csw/rkmfactorytest/WifiListActivity.java
GB18030
7,092
2.046875
2
[]
no_license
package com.csw.rkmfactorytest; import java.util.ArrayList; import java.util.List; import com.csw.communication.WifiAdmin; import com.csw.communication.WifiInfo; import com.csw.communication.WifiListAdapter; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class WifiListActivity extends Activity { private ListView mListView; private WifiManager wifiManager = null; // private String ssidName; // private WifiListAdapter wifiListAdapter; public static List<WifiInfo> wfinfoList = new ArrayList<WifiInfo>(); private String test; private WifiAdmin mWifiAdmin; // ɨб private List<ScanResult> scanList; private static String stopFlag = "0"; /** ɨϽ */ private WifiReceiver receiverWifi; private WifiListAdapter wifiListAdapter; private ProgressDialog dialog; private TextView currentWifiTextView; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.wifilistactivity); mContext=this; currentWifiTextView=(TextView)this.findViewById(R.id.currentConnectWifi); mListView=(ListView)this.findViewById(R.id.currentWifiListView); wifiManager = (WifiManager) WifiListActivity.this .getSystemService(Context.WIFI_SERVICE); mWifiAdmin = new WifiAdmin(WifiListActivity.this, test); receiverWifi =new WifiReceiver(); stopFlag = "0"; OpenWifi(); if (wfinfoList != null) { wfinfoList.clear(); } mWifiAdmin.startScan(); dialog = ProgressDialog.show(WifiListActivity.this, "", "ɨWIFIȵ,Ժ"); setDialogFontSize(dialog,30); dialog.setCancelable(true); // mHandler.sendEmptyMessage(0); } /* * 鵱ǰWIFIǷӣ˼ǷӣDzWIFI */ public static boolean isWifiConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null && info.isConnected() && ConnectivityManager.TYPE_WIFI == info.getType()) { return true; } return false; } Handler mHandler=new Handler(){ public void handleMessage(android.os.Message msg) { switch(msg.what){ case 0: boolean weatherConnect=isWifiConnected(mContext); if(weatherConnect==false){ currentWifiTextView.setText("ǰδ"); }else{ android.net.wifi.WifiInfo info = wifiManager.getConnectionInfo(); int strength = info.getRssi(); int speed = info.getLinkSpeed(); String units = android.net.wifi.WifiInfo.LINK_SPEED_UNITS; String ssid = info.getSSID(); String ip=intToIp(info.getIpAddress()); String mac=info.getMacAddress(); currentWifiTextView.setText("磺"+ssid+" źǿȣ"+strength+" ٶȣ"+speed+ String.valueOf(units)+" IPַ"+ip+" macַ"+mac+" ȵ"+wfinfoList.size()) ; } break; default: break; } }; }; /* * ȡIP */ private String intToIp(int i) { return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF); } /** * WIFI */ public void OpenWifi() { if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } } class WifiReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { scanList = mWifiAdmin.getWifiList(); if (scanList != null) { for (int i = 0; i < scanList.size(); i++) { WifiInfo info = new WifiInfo(); ScanResult s = scanList.get(i); info.setLeved(s.level); info.setSsid(s.SSID); info.setLeved(s.level); info.setWifisecurity(s.capabilities); int chanel=getChanel(s.frequency); info.setWifiChanel(chanel+""); System.out.println(s.SSID); wfinfoList.add(info); } } if (wfinfoList.size() == 0) { Toast.makeText(WifiListActivity.this, "ûɨ赽WiFi", 2000).show(); dialog.dismiss(); } else { // step1Changed(STATE_COMPLETED); if (stopFlag.equals("0")) { dialog.dismiss(); wifiListAdapter = new WifiListAdapter( WifiListActivity.this, wfinfoList); mListView.setAdapter(wifiListAdapter); mHandler.sendEmptyMessageDelayed(0, 1000); } else { System.out.println("߳ͣ"); } } } } } /** * ȡŵķ */ private int getChanel(int currentFrequency){ int currentChannel=0; switch (currentFrequency) { case 2412: currentChannel = 1; break; case 2417: currentChannel = 2; break; case 2422: currentChannel = 3; break; case 2427: currentChannel = 4; break; case 2432: currentChannel = 5; break; case 2437: currentChannel = 6; break; case 2442: currentChannel = 7; break; case 2447: currentChannel = 8; break; case 2452: currentChannel = 9; break; case 2457: currentChannel = 10; break; case 2462: currentChannel = 11; break; case 2467: currentChannel = 12; break; case 2472: currentChannel = 13; break; default: currentChannel = 0; break; } return currentChannel; } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); registerReceiver(receiverWifi, new IntentFilter( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));// ע㲥 } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopFlag = "1"; unregisterReceiver(receiverWifi);// ע㲥 } private void setDialogFontSize(Dialog dialog,int size) { Window window = dialog.getWindow(); View view = window.getDecorView(); setViewFontSize(view,size); } private void setViewFontSize(View view,int size) { if(view instanceof ViewGroup) { ViewGroup parent = (ViewGroup)view; int count = parent.getChildCount(); for (int i = 0; i < count; i++) { setViewFontSize(parent.getChildAt(i),size); } } else if(view instanceof TextView){ TextView textview = (TextView)view; textview.setTextSize(size); } } }
true
6b72b2b454dc2d61e713ae1d56fc0018c387f12a
Java
dat0106/datkts0106
/reference no run/com.martinstudio.hiddenrecorder/src/com/google/android/gms/wallet/fragment/Dimension.java
UTF-8
2,536
2.03125
2
[]
no_license
package com.google.android.gms.wallet.fragment; import android.util.DisplayMetrics; import android.util.TypedValue; public class Dimension { public static final int MATCH_PARENT = -1; public static final int UNIT_DIP = 1; public static final int UNIT_IN = 4; public static final int UNIT_MM = 5; public static final int UNIT_PT = 3; public static final int UNIT_PX = 0; public static final int UNIT_SP = 2; public static final int WRAP_CONTENT = -2; public static int a(long paramLong, DisplayMetrics paramDisplayMetrics) { int j = (int)(paramLong >>> 32); int i = (int)paramLong; switch (j) { default: throw new IllegalStateException("Unexpected unit or type: " + j); case 0: j = 0; break; case 1: j = 1; break; case 2: j = 2; break; case 3: j = 3; break; case 4: j = 4; break; case 5: j = 5; i = Math.round(TypedValue.applyDimension(j, Float.intBitsToFloat(i), paramDisplayMetrics)); break; case 128: i = TypedValue.complexToDimensionPixelSize(i, paramDisplayMetrics); break; } i = i; return i; } public static long a(int paramInt, float paramFloat) { switch (paramInt) { default: throw new IllegalArgumentException("Unrecognized unit: " + paramInt); } return l(paramInt, Float.floatToIntBits(paramFloat)); } public static long a(TypedValue paramTypedValue) { long l; switch (paramTypedValue.type) { default: throw new IllegalArgumentException("Unexpected dimension type: " + paramTypedValue.type); case 5: l = l(128, paramTypedValue.data); break; case 16: l = dM(paramTypedValue.data); } return l; } public static long dM(int paramInt) { long l; if (paramInt >= 0) { l = a(0, paramInt); } else { if ((paramInt != -1) && (paramInt != -2)) { throw new IllegalArgumentException("Unexpected dimension value: " + paramInt); } l = l(129, paramInt); } return l; } private static long l(int paramInt1, int paramInt2) { return paramInt1 << 32 | 0xFFFFFFFF & paramInt2; } } /* Location: E:\android\Androidvn\dex2jar\classes_dex2jar.jar * Qualified Name: com.google.android.gms.wallet.fragment.Dimension * JD-Core Version: 0.7.0.1 */
true
6d5e7b0f339f7a66a9efb815e35734d5cd4fa350
Java
ziaoliu/zTurn
/zTurn/src_1st_round/leetcode/SumRootToLeafNumbersOJ.java
UTF-8
1,890
3.78125
4
[]
no_license
package leetcode; import java.util.ArrayList; /* * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. * * An example is the root-to-leaf path 1->2->3 which represents the number 123. * * Find the total sum of all root-to-leaf numbers. * * For example, * * 1 * / \ * 2 3 * The root-to-leaf path 1->2 represents the number 12. * The root-to-leaf path 1->3 represents the number 13. * * Return the sum = 12 + 13 = 25. * * http://blog.csdn.net/linhuanmars/article/details/22913699 */ public class SumRootToLeafNumbersOJ { public class Solution { public int sumNumbers(TreeNode root) { return dfs(root, 0); } private int dfs(TreeNode root, int sum) { if (root == null) return 0; if (root.left == null && root.right == null) return sum * 10 + root.val; return dfs(root.left, sum * 10 + root.val) + dfs(root.right, sum * 10 + root.val); } } public class SolutionFirstTry { public int sumNumbers(TreeNode root) { if (root == null) return 0; int sum = 0; ArrayList<ArrayList<Integer>> list = new ArrayList<>(); ArrayList<Integer> one = new ArrayList<>(); dfs(list, one, root); for (ArrayList<Integer> temp : list) { StringBuilder sb = new StringBuilder(); for (int i : temp) sb.append(i); sum = sum + Integer.parseInt(sb.toString()); } return sum; } public void dfs(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> one, TreeNode root) { if (root == null) return; one.add(root.val); TreeNode left = root.left; TreeNode right = root.right; dfs(list, one, left); dfs(list, one, right); if (left == null && right == null) list.add(new ArrayList<Integer>(one)); one.remove(one.size() - 1); } } }
true
c0b423468c5d5c63693c5ac8e102b8fdf066be1a
Java
Xblade9/DemoCC
/com.selenium.maven/src/test/java/projectScripts/BalanceEnquiry.java
UTF-8
4,774
2.171875
2
[]
no_license
package projectScripts; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import io.github.bonigarcia.wdm.WebDriverManager; import utility.ScreenshortUtility; public class BalanceEnquiry { public WebDriver driver; public WebDriverWait wait; public String URL="http://www.demo.guru99.com/V4/index.php"; public WebElement w; @BeforeMethod(description = "Open the Browser") public void Open() { WebDriverManager.chromedriver().setup(); driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get(URL); w=driver.findElement(By.cssSelector("input[name='uid']")); w.sendKeys("mngr242181"); w=driver.findElement(By.cssSelector("input[name='password']")); w.sendKeys("Demo@123"); w=driver.findElement(By.cssSelector("input[type='submit']")); w.click(); Assert.assertTrue(driver.getTitle().contains("Guru"),"~Failed to Get the Page Title~"); System.out.println("Title : "+driver.getTitle()); w=driver.findElement(By.xpath("//td[text()='Manger Id : mngr242181']")); Assert.assertTrue(w.getText().contains("Manger")); System.out.println("Manager ID : "+w.getText()); } @Test(description = "BalanceEnquiry",enabled = false) public void balanceEnquiry() { try { w=driver.findElement(By.cssSelector(".menusubnav >li:nth-child(12)")); w.click(); wait=new WebDriverWait(driver, 10); w=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[text()='Balance Enquiry Form']"))); Assert.assertTrue(w.getText().contains("Balance")); System.out.println("Text Showing : "+w.getText()); w=driver.findElement(By.cssSelector("input[name='accountno']")); w.sendKeys("74895"); w=driver.findElement(By.cssSelector("input[type='submit']")); w.click(); Alert a=driver.switchTo().alert(); if(a.getText().contains("Account")) { wait=new WebDriverWait(driver, 5); a=wait.until(ExpectedConditions.alertIsPresent()); Assert.assertTrue(a.getText().contains("Account")); System.out.println("Alert Text : "+a.getText()); Thread.sleep(4000); a.accept(); w=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[text()='Balance Enquiry Form']"))); Assert.assertTrue(w.getText().contains("Balance")); System.out.println("Page Text After Alert : "+w.getText()); ScreenshortUtility.takeScreenshortUtility(driver, "RedirectBEnquiryAfterDeleteAlert"); } } catch (Exception e) { e.printStackTrace(); } } @Test(description = "Verify Balance") public void verifyBalanceAfterWithdrawl() { try { w=driver.findElement(By.cssSelector(".menusubnav >li:nth-child(12)")); w.click(); wait=new WebDriverWait(driver, 10); w=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[text()='Balance Enquiry Form']"))); Assert.assertTrue(w.getText().contains("Balance")); System.out.println("Text Showing : "+w.getText()); w=driver.findElement(By.cssSelector("input[name='accountno']")); w.sendKeys("75080"); w=driver.findElement(By.cssSelector("input[type='submit']")); w.click(); w=driver.findElement(By.xpath("//p[text()='Balance Details for Account 75080']")); Assert.assertTrue(w.getText().contains("Balance")); System.out.println("Balance Details : "+w.getText()); ScreenshortUtility.takeScreenshortUtility(driver, "BalanceDetails"); } catch(Exception e) { } } @AfterMethod(description = "Clost the Appn and Take Screenshort of Failed Tests") public void tearCloseDown(ITestResult result) { try { if(ITestResult.FAILURE==result.getStatus()) { ScreenshortUtility.takeScreenshortUtility(driver, "FailedBalanceEnquiry"); } Thread.sleep(3000); driver.quit(); } catch(Exception e) { e.printStackTrace(); } } }
true
9ae6ec7b3c4d93418ef6419d02e198a01f510ab5
Java
rolandbernard/daro
/src/test/java/daro/lang/values/UserTypeTest.java
UTF-8
738
2.21875
2
[ "BSD-2-Clause" ]
permissive
package daro.lang.values; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class UserTypeTest { @Test void sameEqual() { DaroType type = new DaroTypeInteger(); assertEquals(type, type); } @Test void equal() { assertEquals(new DaroTypeInteger(), new DaroTypeInteger()); } @Test void notEqual() { assertNotEquals(new DaroTypeInteger(), new DaroTypeType()); } @Test void getType() { DaroType type = new DaroTypeInteger(); assertEquals(new DaroTypeType(), type.getType()); } @Test void isTrue() { DaroType type = new DaroTypeInteger(); assertTrue(type.isTrue()); } }
true
3b6ced1086cf608cfe973dd26a4df133b692658c
Java
Vicky-w/JavaBaseDemo
/src/com/github/VickyWang/implTest/demo01/Attackable.java
UTF-8
144
2.125
2
[]
no_license
package com.github.VickyWang.implTest.demo01; /** * Created by Vicky.Wang on 2017/3/18. */ public interface Attackable { void attack(); }
true
77a27e2f683b007d81ef6da99af20060fbd22bab
Java
djxtusiji/enjin-java-sdk
/sdk/src/main/java/com/enjin/sdk/models/token/data/TokenFilter.java
UTF-8
1,600
2.203125
2
[ "Apache-2.0" ]
permissive
package com.enjin.sdk.models.token.data; import com.enjin.sdk.services.token.TokensService; import com.google.gson.annotations.SerializedName; import lombok.Builder; import java.util.Collection; /** * Filter input for token queries. * * @see TokensService */ @Builder public class TokenFilter { /** * The token id to filter for. */ private String id; /** * The token ids to filter for. */ @SerializedName("id_in") private Collection<String> idIn; /** * The token name to filter for. */ private String name; /** * The token names to filter for. */ @SerializedName("name_in") private Collection<String> nameIn; /** * The prefix to filter for. */ @SerializedName("name_starts_with") private String nameStartsWith; /** * The suffix to filter for. */ @SerializedName("name_ends_with") private String nameEndsWith; /** * The application id to filter for. */ private Integer appId; /** * The application ids to filter for. */ @SerializedName("appId_in") private Collection<Integer> appIdIn; /** * The wallet address to filter for. */ private String wallet; /** * The wallet addresses to filter for. */ @SerializedName("wallet_in") private Collection<String> walletIn; /** * The collection of filters to intersect with. */ private Collection<TokenFilter> and; /** * The collection of filters to union with. */ private Collection<TokenFilter> or; }
true
c6396edde8ec61bdbbe9bbd93678ffa9c44b06dc
Java
liang0125/Java
/exercise_2019422/src/main/java/TestReverse.java
UTF-8
1,081
3.828125
4
[]
no_license
import java.util.*; public class TestReverse { /* 题目描述 对字符串中的所有单词进行倒排。 说明: 1、每个单词是以26个大写或小写英文字母构成; 2、非构成单词的字符均视为单词间隔符; 3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符; 4、每个单词最长20个字母; */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String s1 = sc.nextLine(); String[] ss = s1.split("[^a-zA-Z]+"); int i=0; int j=ss.length-1; while (i<j){ String tmp=ss[i]; ss[i]=ss[j]; ss[j]=tmp; i++; j--; } for (int m=0;m<ss.length;m++){ System.out.print(ss[m]); if (m!=ss.length-1){ System.out.print(" "); } } } } }
true
541460f0fd3e0f3454c5f83072eec7fbcd1c2c3a
Java
ravikantvicky/doc-analyzer
/rest-services/doc-analyzer/src/main/java/com/infosys/stg/doc/repository/TemplateRepository.java
UTF-8
5,004
2.328125
2
[]
no_license
package com.infosys.stg.doc.repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.stereotype.Repository; import com.infosys.stg.doc.Utils.AppUtils; import com.infosys.stg.doc.exception.DocAnalyzeException; import com.infosys.stg.doc.model.SaveTemplateRequest; import com.infosys.stg.doc.model.TemplateData; @Repository public class TemplateRepository { @Autowired private Environment env; @Autowired private JdbcTemplate jdbcTemplate; public long saveTemplate(String templateName, String barcode, String description) throws DocAnalyzeException { try { String sql = env.getProperty("sql.saveTemplate"); GeneratedKeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, templateName); ps.setString(2, barcode); ps.setString(3, description); return ps; } }, holder); return holder.getKey().longValue(); } catch (Exception e) { e.printStackTrace(); throw new DocAnalyzeException("Error in saving template details."); } } public long saveTemplatePages(long templateId, int pageNo, String imageData, double width, double height) throws DocAnalyzeException { try { String sql = env.getProperty("sql.saveTemplatePages"); GeneratedKeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setLong(1, templateId); ps.setInt(2, pageNo); ps.setDouble(3, width); ps.setDouble(4, height); ps.setString(5, imageData); return ps; } }, holder); return holder.getKey().longValue(); } catch (Exception e) { e.printStackTrace(); throw new DocAnalyzeException("Error in saving template images details."); } } public void saveTemplateData(SaveTemplateRequest request) throws DocAnalyzeException { try { Set<String> keys = new HashSet<>(); jdbcTemplate.batchUpdate(env.getProperty("sql.saveTemplateData"), new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { TemplateData req = request.getData().get(i); String key = AppUtils.convertToKey(req.getLabel(), keys); ps.setLong(1, request.getTemplateId()); ps.setString(2, req.getLabel()); ps.setString(3, key); ps.setLong(4, request.getTemplateId()); ps.setInt(5, req.getPageNo()); ps.setDouble(6, req.getStartX()); ps.setDouble(7, req.getStartY()); ps.setDouble(8, req.getEndX()); ps.setDouble(9, req.getEndY()); } @Override public int getBatchSize() { return request.getData().size(); } }); } catch (Exception e) { e.printStackTrace(); throw new DocAnalyzeException("Error in saving template data.."); } } public void updateBarCode(String barcode, long templateId) throws DocAnalyzeException { try { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(env.getProperty("sql.updateBarCode")); ps.setString(1, barcode); ps.setLong(2, templateId); return ps; } }); } catch (Exception e) { e.printStackTrace(); throw new DocAnalyzeException("Error in updating barcode. "); } } public String getTemplateName(long templateId) { try { return jdbcTemplate.query(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(env.getProperty("sql.fetchTemplateName")); ps.setLong(1, templateId); return ps; } }, new ResultSetExtractor<String>() { @Override public String extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) return rs.getString(1); return null; } }); } catch (Exception e) { e.printStackTrace(); return null; } } }
true
d905fe3725aa7fadc67d6a26c3a4ea36437e1e40
Java
1649865412/solifeAdmin
/solifeAdmin/src/com/cartmatic/estore/common/model/order/base/SalesOrderGeoipTbl.java
UTF-8
5,456
2.21875
2
[]
no_license
package com.cartmatic.estore.common.model.order.base; import java.io.Serializable; import com.cartmatic.estore.Constants; import com.cartmatic.estore.core.model.BaseObject; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.EqualsBuilder; /** * SalesOrderGeoip Base Java Bean, base class for the model, mapped directly to database table * * Avoid changing this file if not necessary, will be overwritten. * * TODO: add class/table comments */ public class SalesOrderGeoipTbl extends BaseObject implements Serializable { protected Integer salesOrderGeoipId; protected String orderNo; protected String customerIp; protected String lon; protected String lat; protected Short actionType; protected String city; protected String state; protected String country; protected java.util.Date createTime; /** * Default Empty Constructor for class SalesOrderGeoip */ public SalesOrderGeoipTbl () { super(); } /** * Default Key Fields Constructor for class SalesOrderGeoip */ public SalesOrderGeoipTbl ( Integer in_salesOrderGeoipId ) { this.setSalesOrderGeoipId(in_salesOrderGeoipId); } /** * * @return Integer * @hibernate.id column="salesOrderGeoipId" type="java.lang.Integer" generator-class="native" */ public Integer getSalesOrderGeoipId() { return this.salesOrderGeoipId; } /** * Set the salesOrderGeoipId */ public void setSalesOrderGeoipId(Integer aValue) { this.salesOrderGeoipId = aValue; } /** * * @return String * @hibernate.property column="orderNo" type="java.lang.String" length="20" not-null="true" unique="false" */ public String getOrderNo() { return this.orderNo; } /** * Set the orderNo * @spring.validator type="required" */ public void setOrderNo(String aValue) { this.orderNo = aValue; } /** * * @return String * @hibernate.property column="customerIp" type="java.lang.String" length="64" not-null="false" unique="false" */ public String getCustomerIp() { return this.customerIp; } /** * Set the customerIp */ public void setCustomerIp(String aValue) { this.customerIp = aValue; } /** * * @return String * @hibernate.property column="lon" type="java.lang.String" length="32" not-null="false" unique="false" */ public String getLon() { return this.lon; } /** * Set the lon */ public void setLon(String aValue) { this.lon = aValue; } /** * * @return String * @hibernate.property column="lat" type="java.lang.String" length="32" not-null="false" unique="false" */ public String getLat() { return this.lat; } /** * Set the lat */ public void setLat(String aValue) { this.lat = aValue; } /** * * @return Short * @hibernate.property column="actionType" type="java.lang.Short" length="5" not-null="true" unique="false" */ public Short getActionType() { return this.actionType; } /** * Set the actionType * @spring.validator type="required" */ public void setActionType(Short aValue) { this.actionType = aValue; } /** * * @return java.util.Date * @hibernate.property column="createTime" type="java.util.Date" length="0" not-null="true" unique="false" */ public java.util.Date getCreateTime() { return this.createTime; } /** * Set the createTime * @spring.validator type="required" */ public void setCreateTime(java.util.Date aValue) { this.createTime = aValue; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof SalesOrderGeoipTbl)) { return false; } SalesOrderGeoipTbl rhs = (SalesOrderGeoipTbl) object; return new EqualsBuilder() .append(this.salesOrderGeoipId, rhs.salesOrderGeoipId) .append(this.orderNo, rhs.orderNo) .append(this.customerIp, rhs.customerIp) .append(this.lon, rhs.lon) .append(this.lat, rhs.lat) .append(this.actionType, rhs.actionType) .append(this.createTime, rhs.createTime) .isEquals(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(-82280557, -700257973) .append(this.salesOrderGeoipId) .append(this.orderNo) .append(this.customerIp) .append(this.lon) .append(this.lat) .append(this.actionType) .append(this.createTime) .toHashCode(); } /** * @see java.lang.Object#toString() */ public String toString() { return new ToStringBuilder(this) .append("salesOrderGeoipId", this.salesOrderGeoipId) .append("orderNo", this.orderNo) .append("customerIp", this.customerIp) .append("lon", this.lon) .append("lat", this.lat) .append("actionType", this.actionType) .append("createTime", this.createTime) .toString(); } /** * Return the name of the first key column */ public String getFirstKeyColumnName() { return "salesOrderGeoipId"; } /** * Return the Id (pk) of the entity, must be Integer */ public Integer getId() { return salesOrderGeoipId; } }
true
8539f3cf24c50addbcb2137cc83043eba0335290
Java
thangakumard/01_Datastructure
/algorithm/src/test/java/coreJava/regularExpression/regexSamples.java
UTF-8
2,469
3.1875
3
[]
no_license
package coreJava.regularExpression; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.regex.Pattern; /** * Refer : https://regex101.com/ */ public class regexSamples { @Test public void removeWhiteSpace(){ String regex = "\\s"; String input = "apple apple apple"; Assertions.assertThat(input.replaceAll(regex,"")).isEqualTo("appleappleapple"); } @Test public void Multiple(){ Assertions.assertThat(Pattern.matches("\\d", "1")).isTrue(); Assertions.assertThat(Pattern.matches("\\d+", "123456")).isTrue(); Assertions.assertThat(Pattern.matches("[0-9]", "1")).isTrue(); Assertions.assertThat(Pattern.matches("[0-9]+", "123456")).isTrue(); Assertions.assertThat(Pattern.matches("\\D", "a")).isTrue(); Assertions.assertThat(Pattern.matches("\\D+", "abc")).isTrue(); Assertions.assertThat(Pattern.matches("[a-zA-Z]", "a")).isTrue(); Assertions.assertThat(Pattern.matches("[a-zA-Z]+", "abc")).isTrue(); //String with the length of 6 characters Assertions.assertThat(Pattern.matches("[a-zA-Z]{6}", "abcdef")).isTrue(); Assertions.assertThat(Pattern.matches("[a-zA-Z]+", "abc")).isTrue(); //a or b or c must appear once Assertions.assertThat(Pattern.matches("[abc]?", "a")).isTrue(); Assertions.assertThat(Pattern.matches("[abc]?", "aaa")).isFalse(); Assertions.assertThat(Pattern.matches("[456]{1}[0-9]{9}", "4258291831")).isTrue(); } @Test public void Test1(){ String regex = "apple[,]apple[,]apple"; String input = "apple,apple,apple"; Assertions.assertThat(input.matches(regex)).isTrue(); } @Test public void Test2(){ String regex = "apple[,]\\w+[,]apple"; String input = "apple,apple,apple"; Assertions.assertThat(input.matches(regex)).isTrue(); } @Test public void Test3(){ String regex = ".*\\w+[,]\\w+[,]\\w+[,]apple[,].*banana[,]"; String input = "orange,apple,banana,orange,apple,orange,orange,banana,"; Assertions.assertThat(input.matches(regex)).isTrue(); } @Test public void Test4(){ String regex = ".*\\w+[,]\\w+[,]\\w+[,]apple.*banana[,]\\w+[,]banana.*"; String input = "orange,apple,banana,orange,apple,orange,orange,banana,apple,banana"; Assertions.assertThat(input.matches(regex)).isTrue(); } }
true
f9e87202b24418f0e780194f488c76a5af70e88a
Java
jzjloveu/Leetcode-java
/LinkedList/RemoveDuplicatesFromSortedList/DeleteDuplicates.java
UTF-8
1,109
3.859375
4
[]
no_license
/* Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. . */ package ListUtil; import ListUtil.*; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class DeleteDuplicates { public ListNode deleteDuplicates(ListNode head) { if(head==null || head.next==null) return head; ListNode curr = head; while(curr.next != null){ if(curr.next.val == curr.val) curr.next = curr.next.next; else curr = curr.next; } return head; } public static void main(String args[]){ int[] arr = {1,1,2,3,3}; DeleteDuplicates sol = new DeleteDuplicates(); ListNode head = ListUtil.buildList(arr); ListUtil.printList(head); head = sol.deleteDuplicates(head); ListUtil.printList(head); } }
true
bd484c5414a3e4cd3e1b1562c1e1a976a8a08e37
Java
wgnrMelo/lista-estrutura-condicional
/Exercicio07JOptionPane.java
UTF-8
463
2.28125
2
[]
no_license
import javax.swing.JOptionPane; public class Exercicio07JOptionPane{ public static void main(String[] args){ JOptionPane.showMessageDialog(null, "Arvore de Natal"+ "\n ** "+ "\n **** "+ "\n ****** " + "\n ******** " + "\n ********** " + "\n ************ " + "\n ***** " + "\n *** " ); } }
true
c3d2c9e66b175eb0a39a74e9844ebd585a28df5d
Java
xueshun/springboot09
/src/test/java/com/xue/Springboot09ApplicationTests.java
UTF-8
1,668
2.125
2
[]
no_license
package com.xue; import java.util.Date; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.xue.bean.RoncooUser; import com.xue.bean.RoncooUserLog; import com.xue.dao.RoncooUserLogDao; import com.xue.dao.UserDao; import com.xue.util.base.Page; @RunWith(SpringRunner.class) @SpringBootTest public class Springboot09ApplicationTests { @Autowired private UserDao userDao; @Autowired private RoncooUserLogDao userLogDao; @Test public void insert() { RoncooUser roncooUser = new RoncooUser(); roncooUser.setName("测试"); roncooUser.setCreateTime(new Date()); int result = userDao.insert(roncooUser); System.out.println(result); } @Test public void delete() { int result = userDao.deleteById(1); System.out.println(result); } @Test public void update() { RoncooUser roncooUser = new RoncooUser(); roncooUser.setId(2); roncooUser.setName("测试 2"); roncooUser.setCreateTime(new Date()); int result = userDao.updateById(roncooUser); System.out.println(result); } @Test public void select() { RoncooUser result = userDao.selectById(2); System.out.println(result); } @Test public void pageSelect() { Page<RoncooUser> queryForPage = userDao.queryForPage(1, 20, "测试"); System.out.println(queryForPage); } @Test public void inserLog() { RoncooUserLog log = new RoncooUserLog(); log.setCreateTime(new Date()); log.setUserIp("127.0.0.1"); log.setUserName("wang"); userLogDao.save(log); } }
true
3c3286105c4c153e9afe41e7bde5143851a5a11c
Java
aman1002/ANZCodingChallenge
/src/main/java/com/anz/codechallenge/controller/AccountController.java
UTF-8
2,210
2.546875
3
[]
no_license
package com.anz.codechallenge.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.anz.codechallenge.exceptions.AccountNotFoundException; import com.anz.codechallenge.exceptions.AccountsNotFetchedException; import com.anz.codechallenge.models.Account; import com.anz.codechallenge.service.AccountServiceImpl; import com.anz.codechallenge.validator.AccountValidator; @RestController @RequestMapping("v1/accounts") public class AccountController { @Autowired private AccountServiceImpl accountService; private static final Logger log = LoggerFactory.getLogger(AccountController.class); // API to get account by passing the id as account number @GetMapping(path = "/id") public ResponseEntity<Account> getAccount(@RequestBody String accountNumber) throws Exception { AccountValidator.validateAccountNumber(accountNumber); Account account = accountService.getAccount(accountNumber); if (account == null) { log.info("Account Not Found with account number: "+accountNumber); throw new AccountNotFoundException("Account Not Found with account number: "+accountNumber); } log.info("Account fetched is: "+account.toString()); return new ResponseEntity<Account>(account, HttpStatus.OK); } // API to get all the accounts saved in the database for the user @GetMapping(path = "/") public ResponseEntity<List<Account>> getAllAccounts() { List<Account> accountList = accountService.getAllAccounts(); if (accountList == null || accountList.isEmpty()) { log.info("Unable to fetch details from the database."); throw new AccountsNotFetchedException("Can't Fetch Details. Server Error"); } log.info("Accounts list fetched properly. "+accountList); return new ResponseEntity<List<Account>>(accountList, HttpStatus.OK); } }
true
844ab8fbbcb362994df17a85f516ba0e9f5fc342
Java
mongojack/mongojack
/src/test/java/org/mongojack/TestUUIDHandling.java
UTF-8
2,775
2.203125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2011 VZ Netzwerke Ltd * Copyright 2014 devbliss GmbH * * 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.mongojack; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.types.ObjectId; import org.junit.Test; import java.util.UUID; import static org.hamcrest.core.IsEqual.*; import static org.junit.Assert.*; @SuppressWarnings("ConstantConditions") public class TestUUIDHandling extends MongoDBTestBase { @Test public void testUnderlyingMongoFunctionality() { final MongoCollection<Document> collection = getMongoCollection(Document.class); final Document document = new Document("uuid", UUID.randomUUID()); collection.insertOne(document); final Document found = collection.find(Filters.eq("uuid", document.get("uuid"))).first(); assertThat(found.get("uuid"), equalTo(document.get("uuid"))); } @Test public void testSavesAndRetrievesUuid() { ObjectIdId object = new ObjectIdId(UUID.randomUUID()); JacksonMongoCollection<ObjectIdId> coll = getCollection(ObjectIdId.class); coll.insert(object); ObjectId id = coll.findOne()._id; ObjectIdId result = coll.findOneById(id); assertThat(result._id, equalTo(id)); assertThat(result.uuid, equalTo(object.uuid)); assertThat(getUnderlyingCollection(coll).find().first().get("uuid"), equalTo(object.uuid)); } @Test public void testQueryByUuid() { ObjectIdId object = new ObjectIdId(UUID.randomUUID()); JacksonMongoCollection<ObjectIdId> coll = getCollection(ObjectIdId.class); coll.insert(object); ObjectId id = coll.findOne()._id; ObjectIdId result = coll.findOne(Filters.eq("uuid", object.uuid)); assertThat(result._id, equalTo(id)); assertThat(result.uuid, equalTo(object.uuid)); assertThat(getUnderlyingCollection(coll).find().first().get("uuid"), equalTo(object.uuid)); } public static class ObjectIdId { public ObjectId _id; public UUID uuid; public ObjectIdId() { } public ObjectIdId(final UUID uuid) { this.uuid = uuid; } } }
true
b5e5ce8498244003cfb294b889c7e0d22360ef24
Java
CE244-spring2016/94105503_94105558
/src/GUI/NetworkPanel.java
UTF-8
2,958
3.0625
3
[]
no_license
package GUI; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * Created by ruhollah on 7/13/2016. */ public final class NetworkPanel extends JPanel { private static NetworkPanel networkPanel; private Controller controller; private JLabel waitLabel = new JLabel("<html><font size=\"5\">Waiting for someone to join...</font></html>"); private int width = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() * 2) / 3; private int height = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() * 2) / 3; public static NetworkPanel getInstance() { return networkPanel; } public static NetworkPanel getInstance(Controller controller) { if (networkPanel == null) { networkPanel = new NetworkPanel(controller); } return networkPanel; } private NetworkPanel(Controller controller) { this.controller = controller; this.setLayout(null); this.setFocusable(true); this.requestFocus(); this.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { System.out.println(e.getX() + ", " + e.getY()); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); this.setSize(width, height); this.setPreferredSize(new Dimension(width, height)); create(); } private void create() { JButton hostButton = new JButton("<html><font size=\"5\">Host</font></html>"); hostButton.setBounds((width * 750) / 1920, (height * 230) / 1080, (width * 160) / 1920, (height * 50) / 1080); hostButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.setPanel(new HostPanel(controller)); } }); this.add(hostButton); JButton joinButton = new JButton("<html><font size=\"5\">Join</font></html>"); joinButton.setBounds((width * 750) / 1920, (height * 330) / 1080, (width * 160) / 1920, (height * 50) / 1080); joinButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.setPanel(new JoinPanel(controller)); } }); this.add(joinButton); } }
true
bd999b27cfb5655457823d6e31d1a5b10cc1f9a3
Java
zofiawell/tester-auto-repo
/selenium-zadania/SearchTest2.java
UTF-8
1,132
2.28125
2
[]
no_license
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import static org.junit.Assert.*; public class SearchTest2 { //klasa nie może się nazywać SearchTest2 :-) private WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver","/home/zofia/tester-automat-kurs/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @After public void tearDown() { driver.quit(); } @Test public void searchTest() { driver.get("http://www.bing.com"); WebElement input = driver.findElement(By.name("q")); input.sendKeys("Mistrzostwa Świata w piłce nożnej 2018"); input.submit(); String title = driver.getTitle(); System.out.println(title); assertEquals("Mistrzostwa Świata w piłce nożnej 2018 - Bing", title); } //wszystkie Stringi do stałych }
true
d6ff6daafa4dc3bd9ace001023a2ca2e2d8c2b26
Java
maohuihua123/Energy-Efficient-Algorithms_CloudSim
/cloudsim/modules/cloudsim/src/main/java/org/cloudbus/cloudsim/CloudletSchedulerDynamicWorkloadUncertain.java
UTF-8
617
2.25
2
[]
no_license
package org.cloudbus.cloudsim; public class CloudletSchedulerDynamicWorkloadUncertain extends CloudletSchedulerDynamicWorkload{ public CloudletSchedulerDynamicWorkloadUncertain(double mips, int numberOfPes) { super(mips, numberOfPes); } public double getEstimateTimeUncertain(Cloudlet cl){ ResCloudlet rcl = new ResCloudlet(cl); rcl.setCloudletStatus(Cloudlet.INEXEC); for (int i = 0; i < cl.getNumberOfPes(); i++) { rcl.setMachineAndPeId(0, i); } double time = getEstimatedFinishTime(rcl, getPreviousTime()); return time; } }
true
f7a33f7f1f8a14db5d0683bf5227d2d2a5c05e5b
Java
eidrien/economicsCD
/src/main/java/cd/Simulation.java
UTF-8
2,682
2.578125
3
[]
no_license
package cd; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.logging.Logger; import cd.commits.Commit; import cd.programmer.ImperfectProgrammer; import cd.programmer.Programmer; import utils.RandomGenerator; public class Simulation { private final static Logger LOGGER = Logger.getLogger(Simulation.class.getName()); List<Programmer> programmers; Codebase codebase; Pipeline pipeline; private static RandomGenerator randomGenerator; public Simulation(){ programmers = new ArrayList<Programmer>(); codebase = new Codebase(); pipeline = new Pipeline(); } private void runStep() { for(Programmer programmer : programmers){ Commit commit = programmer.code(); LOGGER.info(commit.toString()); codebase.addCommit(commit); pipeline.push(codebase.build()); } pipeline.timeStepElapsed(); Set<Functionality> detectedErrors = pipeline.getDetectedErrors(); Set<Functionality> untestedFunctionalities = pipeline.getUntestedFunctionalities(); for(Programmer programmer : programmers){ programmer.errorsDetected(detectedErrors); programmer.untestedFunctionalities(untestedFunctionalities); } LOGGER.info(pipeline.toString()); } private void addProgrammer(Programmer programmer) { programmers.add(programmer); } public static void main(String[] args){ LOGGER.info("Starting the simulation"); seedRandomGenerator(); Simulation simulation = new Simulation(); addImperfectProgrammer(simulation); for(int i=0; i<200; i++){ LOGGER.info("Step:" + i); simulation.runStep(); LOGGER.info(simulation.getStatistics()); } } private static void seedRandomGenerator() { randomGenerator = new RandomGenerator(); randomGenerator.setRandomSeed(100); } private static void addImperfectProgrammer(Simulation simulation) { ImperfectProgrammer programmer = new ImperfectProgrammer(); programmer.setRandomGenerator(randomGenerator); programmer.setErrorRate(0.1); programmer.setFatalErrorRate(0.3); programmer.setFixRate(0.75); programmer.setTestRate(0.2); programmer.setMaxTestExecutionTime(10); simulation.addProgrammer(programmer); } private String getStatistics() { Build prod = pipeline.getBuildIn(Stages.PROD); Build test = pipeline.getBuildIn(Stages.TEST); Build wait = pipeline.getBuildIn(Stages.WAITING_FOR_TEST); StringBuffer sb = new StringBuffer(); if(prod != null){ sb.append("PROD - ").append(prod.toString()).append("\n"); } if(test != null){ sb.append("TEST - ").append(test.toString()).append("\n"); } if(wait != null){ sb.append("WAIT - ").append(wait.toString()).append("\n"); } return sb.toString(); } }
true
c29d0d443e28b94bb18bed11be46f831fc1f99cf
Java
Jana100/jf-5-homework
/src/md/tekwill/Exercise1.java
UTF-8
461
2.828125
3
[]
no_license
package md.tekwill; public class Exercise1 { /* Print a Celsius - Fahrenheit table from 0 to 300 with interval 10C 0C - 32F 10C - 50F 20C - 68F 30C - 86F ... 300 - 572n */ public static void main(String[] args) { int fahr; int celsius; for (celsius = 0; celsius < 300; celsius++) ; { fahr = (celsius * 9 / 5) + 32; celsius = celsius + 10; } } }
true
9cf49ea318d83eaa1064dea91378440c9aaed371
Java
nreina003/RentG
/src/java/packServlets/SvrConsultarReservas.java
UTF-8
15,962
2.078125
2
[]
no_license
package packServlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import packBD.Conexion; import packModelo.Reserva; @WebServlet(name = "SrvConsultarReservas", urlPatterns = {"/SrvConsultarReservas"}) public class SvrConsultarReservas extends HttpServlet { //estas 2 private static SvrConsultarReservas cr; private static int id = 0; private Connection con; private Statement set; private ResultSet rs; String cad; public String matri; //matri nuevo public void init(ServletConfig cfg) throws ServletException { Conexion c = Conexion.getInstance(); c.conectar(); } //este public static SvrConsultarReservas getInstance() { if (cr == null) { cr = new SvrConsultarReservas(); } return cr; } public ResultSet rCliente() { ResultSet reservas = null; Conexion c = Conexion.getInstance(); c.conectar(); // String reservas = null; try { reservas = c.getSt().executeQuery("SELECT * FROM rentg02.reservas order by email;"); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } return reservas; } public ArrayList<Reserva> buscarReservasPorEmail() { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { String query = "SELECT * FROM reservas order by email"; rs = c.getSt().executeQuery("SELECT * FROM reservas order by email"); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public ArrayList<Reserva> buscarReservasPorEmailCliente(String pEmail) { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { String query = "SELECT * FROM reservas where email ='" + pEmail + "'"; rs = c.getSt().executeQuery(query); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public ArrayList<Reserva> buscarReservasPorCoche(String pMatric) { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { System.out.println(pMatric); String query = "SELECT * FROM reservas where matricula ='" + pMatric + "'"; rs = c.getSt().executeQuery("SELECT * FROM reservas where matricula ='" + pMatric + "'"); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public ArrayList<Reserva> buscarReservasPorCocheCliente(String pMatric, String pEmail) { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { String query = "SELECT * FROM reservas where matricula ='" + pMatric + "' AND email ='" + pEmail + "'"; rs = c.getSt().executeQuery("SELECT * FROM reservas WHERE matricula ='" + pMatric + "' AND email ='" + pEmail + "'"); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public ArrayList<Reserva> buscarReservasPorFecha(String pFecha) { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { System.out.println(pFecha); String query = "SELECT * FROM reservas where fechaInicio ='" + pFecha + "'"; rs = c.getSt().executeQuery("SELECT * FROM reservas where fechaInicio ='" + pFecha + "'"); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public ArrayList<Reserva> buscarReservasPorFechaCliente(String pFecha, String pEmail) { ResultSet rs = null; Conexion c = Conexion.getInstance(); c.conectar(); ArrayList<Reserva> reservas = new ArrayList<>(); try { String query = "SELECT * FROM reservas where fechaInicio ='" + pFecha + "' AND email ='" + pEmail + "'"; rs = c.getSt().executeQuery("SELECT * FROM reservas WHERE fechaInicio ='" + pFecha + "' AND email ='" + pEmail + "'"); Integer idReservas; String email; String matricula; String fechaInicio; String fechaFin; String lugar; String cocheRecogido; String cocheEntregado; String pagoExtra; String retraso; while (rs.next()) { System.out.println("añadir"); idReservas = rs.getInt("idReservas"); email = rs.getString("email"); matricula = rs.getString("matricula"); fechaInicio = rs.getString("fechaInicio"); fechaFin = rs.getString("fechaFin"); lugar = rs.getString("lugar"); cocheRecogido = rs.getString("cocheRecogido"); cocheEntregado = rs.getString("CocheEntregado"); pagoExtra = rs.getString("pagoExtra"); retraso = rs.getString("retraso"); reservas.add(new Reserva(idReservas, email, matricula, fechaInicio, fechaFin, lugar, cocheRecogido, cocheEntregado, pagoExtra, retraso)); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } System.out.println(reservas); return reservas; } public boolean eliminarReserva(Integer pIdr) { Conexion c = Conexion.getInstance(); c.conectar(); boolean eliminada = false; try { Statement sentencia = Conexion.getInstance().getSt(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String query = "DELETE FROM reservas WHERE idReservas= '" + pIdr + "'"; sentencia.executeUpdate(query); eliminada = true; } catch (SQLException ex) { Logger.getLogger(SvrConsultarReservas.class.getName()).log(Level.SEVERE, null, ex); eliminada = false; } return eliminada; } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nomConsulta = request.getParameter("nomConsulta"); String nomConsultaCliente = request.getParameter("nomConsultaCliente"); String matri = request.getParameter("matri"); System.out.println(matri); if (Objects.equals(nomConsulta, "fecha")) { request.getRequestDispatcher("fecha.jsp").forward(request, response); } else if (Objects.equals(nomConsulta, "coche")) { request.setAttribute("matri", matri); request.getRequestDispatcher("coche.jsp").forward(request, response); } else if (Objects.equals(nomConsulta, "cliente")) { response.sendRedirect("cliente.jsp"); } else if (Objects.equals(nomConsultaCliente, "fechaCliente")) { request.getRequestDispatcher("fechaCliente.jsp").forward(request, response); } else if (Objects.equals(nomConsultaCliente, "cocheCliente")) { request.getRequestDispatcher("cocheCliente.jsp").forward(request, response); } else if (Objects.equals(nomConsultaCliente, "clienteCliente")) { response.sendRedirect("clienteCliente.jsp"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
9a214af998c2e13997f7e5f103c038dfd3933b97
Java
CoderZxd/Design-pattern
/src/main/java/com/zxd/learning/designpattern/bridge/DrawAPI.java
UTF-8
298
2.3125
2
[]
no_license
package com.zxd.learning.designpattern.bridge; /** * @Project Design-pattern * @Package com.zxd.learning.designpattern.bridge * @Author:zouxiaodong * @Description: * @Date:Created in 15:02 2018/2/12. */ public interface DrawAPI { void drawCircle(int radius,int x,int y); }
true
891d86a8ad5d16d402ea1acdbca8a29fa67b8649
Java
geovaly/majortom
/majortom-redis/src/main/java/de/topicmapslab/majortom/redis/store/index/paged/PagedRedisTypeInstanceIndex.java
UTF-8
517
1.859375
2
[]
no_license
package de.topicmapslab.majortom.redis.store.index.paged; import de.topicmapslab.majortom.index.paged.PagedTypeInstanceIndexImpl; import de.topicmapslab.majortom.redis.store.RedisTopicMapStore; import de.topicmapslab.majortom.redis.store.index.RedisTypeInstanceIndex; public class PagedRedisTypeInstanceIndex extends PagedTypeInstanceIndexImpl<RedisTopicMapStore> { public PagedRedisTypeInstanceIndex(RedisTopicMapStore store, RedisTypeInstanceIndex parentIndex) { super(store, parentIndex); } }
true
1e59c1b83862b53ce2deec737fb76d4c2a2a6a05
Java
axkum/Swisshimmel
/sh-website/src/main/java/ch/swisshimmel/website/occasion/persist/entity/Occasion.java
UTF-8
3,163
2.234375
2
[]
no_license
package ch.swisshimmel.website.occasion.persist.entity; import java.sql.Date; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name="OCCASION") public class Occasion { @Id @Column(name="occasion_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private int occasion_id; @NotEmpty(message="Please enter a Occasion Name") @Column(name="occasionName") private String occasionName; @Column(name="city") private String city; @Column(name="country") @NotEmpty(message="Please enter a country Name") private String country; @Column(name="comment") private String comment; @Column(name="wikiLink") private String wikiLink ; @Column(name="repeatsEveryYear") private boolean repeatsEveryYear; @Column(name="timeEnteredBy") private Date timeEnteredBy; /* @OneToMany(targetEntity=OccasionTime.class, mappedBy="occasion_id", fetch=FetchType.EAGER, cascade = {CascadeType.ALL}) */ @OneToMany(targetEntity=OccasionTime.class, mappedBy="occasion_id", fetch=FetchType.EAGER) @Valid private List<OccasionTime> occasionTimes = new ArrayList<OccasionTime>(); public int getOccasion_id() { return occasion_id; } public void setOccasion_id(int occasion_id) { this.occasion_id = occasion_id; } public String getOccasionName() { return occasionName; } public void setOccasionName(String occasionName) { this.occasionName = occasionName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getWikiLink() { return wikiLink; } public void setWikiLink(String wikiLink) { this.wikiLink = wikiLink; } public boolean isRepeatsEveryYear() { return repeatsEveryYear; } public void setRepeatsEveryYear(boolean repeatsEveryYear) { this.repeatsEveryYear = repeatsEveryYear; } public Date getTimeEnteredBy() { return timeEnteredBy; } public void setTimeEnteredBy(Date timeEnteredBy) { this.timeEnteredBy = timeEnteredBy; } public List<OccasionTime> getOccasionTimes() { return occasionTimes; } public void setOccasionTimes(List<OccasionTime> occasionTimesList) { this.occasionTimes = occasionTimesList; } }
true
64855a8db60879ff32a6c68a531f3b9a669c0491
Java
vermouth-wl/mybatis-annotationIDUS
/src/com/mybatis/mapper/AdminMapper.java
UTF-8
945
2.140625
2
[]
no_license
package com.mybatis.mapper; import com.mybatis.pojo.Admin; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; /** * @InterfaceName AdminMapper * @Description TODO 管理员接口 * @Author 将烬星火是否太炽热, 明日黄花会开败阡陌 * @Date 2020-11-17 21:33 * @Version 1.0 **/ public interface AdminMapper { // 根据管理员id查询出对应的管理员信息 @Select("select * from admin t where t.id = #{id}") @Results({ @Result(id = true, property = "id", column = "id"), @Result(property = "name", column = "name"), // 多对多关联属性 @Result(column = "id", property = "funcions", many = @Many(select = "com.mybatis.mapper.FunctionMapper.findFunctionByAid")) }) public Admin findAdminById(Integer id); }
true
5a53a61857ca8e319597a171569a12fc066c5a0a
Java
CHDylan/test1-mybatis-01
/src/com/mybatis/pojo/Person.java
UTF-8
396
2.375
2
[]
no_license
package com.mybatis.pojo; public class Person { /** * */ private Studnet studnet ; @Override public String toString() { return "Person{" + "studnet=" + studnet + '}'; } public Studnet getStudnet() { return studnet; } public void setStudnet(Studnet studnet) { this.studnet = studnet; } }
true
a3f8344e9a1688e7d4959544d89b8033da0b0f11
Java
askarsyzdykov/android.temp
/app/src/main/java/kz/base/app/mvp/common/RxUtils.java
UTF-8
1,289
2.40625
2
[ "MIT", "Apache-2.0" ]
permissive
package kz.base.app.mvp.common; import java.io.IOException; import kz.base.app.mvp.app.MyError; import retrofit2.Call; import retrofit2.Response; import rx.Observable; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Date: 18.01.2016 * Time: 14:37 * * @author Yuri Shmakov */ public class RxUtils { public static <T> Observable<T> wrapRetrofitCall(final Call<T> call) { return Observable.create(subscriber -> { final Response<T> execute; try { execute = call.execute(); } catch (IOException e) { subscriber.onError(e); return; } if (execute.isSuccessful()) { subscriber.onNext(execute.body()); } else { subscriber.onError(new MyError(execute.errorBody())); } }); } public static <T> Observable<T> wrapAsync(Observable<T> observable) { return wrapAsync(observable, Schedulers.io()); } public static <T> Observable<T> wrapAsync(Observable<T> observable, Scheduler scheduler) { return observable .subscribeOn(scheduler) .observeOn(AndroidSchedulers.mainThread()); } }
true
7c15dda05c1d20d85bbf0d7b02ae755af1386860
Java
nlp-lap/Version_Compatible_HL7_Parser
/hl7/pseudo/message/RSP_Q11.java
UTF-8
298
1.617188
2
[]
no_license
package hl7.pseudo.message; import hl7.bean.Structure; public class RSP_Q11 extends hl7.model.V2_6.message.RSP_Q11{ public RSP_Q11(){ super(); } public static RSP_Q11 CLASS; static{ CLASS = new RSP_Q11(); } public Structure[][] getComponents(){ return super.getComponents(); } }
true
6c7cc256a5c5f878fb620ef0b06a4dfcee6e4c4d
Java
inkp80/Naver_SmartEditor
/DoIt/naver_smart_editor_lec6/prac11/app/src/main/java/com/example/naver/prac11/MainActivity.java
UTF-8
1,314
2.109375
2
[]
no_license
package com.example.naver.prac11; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { Button mColorSelect; Button mStrokeSelect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PaintBoardView myView = new PaintBoardView(this); LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.board_place); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); myView.setLayoutParams(params); mLinearLayout.addView(myView); mColorSelect = (Button) findViewById(R.id.bt_sel_color); mColorSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ColorSelectDialog.class); startActivity(intent); } }); } }
true
354581c54aef4a180da7089cc9a886fed2af7970
Java
WEIHUAKUI/Java-for-YUNMU
/Personally/src/NoteBOOK.java
GB18030
27,079
2.421875
2
[]
no_license
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.swing.event.*; import java.util.*; import java.awt.datatransfer.*; class text implements Serializable{ String keyword;// String textmain;//ı } public class NoteBOOK extends JFrame implements ActionListener,ListSelectionListener{ MenuBar menusBar;//˵ MenuItem open,keep,save,newfile,exit_out,about,text_font,colorchoose,backchoose,timeadd,keyopen,keysave,zcancel,copy,paste,cut,delete,selectall,search,autoline; Menu file,edit,format,help;//˵ MenuShortcut opencut,dsavecut,savecut,newworkcut,quitcut,aboutcut,fontchoosecut,colorchoosecut,backchoosecut,timeaddcut,keyopencut,keysavecut,zcancelcut,copycut,pastecut,cutcut,deletecut,selectallcut,searchcut,autolinecut; Toolkit tool=this.getToolkit(); Clipboard clip;// Image image=tool.getImage("data/icon.jpg");//ͼ JTextArea textarea;//ı JDialog dialog,fontdialog,keydialog,searchdialog;//Ƿ JList fontlist;//嵥 Choice fontpara;//б JTextField fontsizetext;//С JTextField searchtext;// JTextField changetext;//滻 TextField keyentertext;// JScrollPane listscroll,textscroll; JPanel fontbuttonpanel,fontmainpanel,fontsizepanel,searchpanel,searchbuttonpanel,searchtextpanel,changepanel,changetextpanel,changebuttonpanel; GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); String fontname[]=ge.getAvailableFontFamilyNames();// boolean havesave=true;//ǷѴ boolean enterquit=false;//жԻ֮ǰǷ˳ JButton yes,no,cancel,ok,can,keyok,searchok,searchcancel,changeok,changeall;//Իť JLabel tip,fonttype,fontsize,searchtip,changetip;//ʾ FileDialog filedialog;//Ի text text;//洢 String opensource="";//жǷѱ String texttype="";// String direct="";//· String canceltext="";// int size=18;//С int para=0;//б Font font=new Font(texttype,Font.PLAIN,size); Color fontcolor=Color.black;//ɫ Color backcolor=Color.white;//ɫ Date nowtime;//ʱ char savemode1='s'; char savemode2='t';//ܱ淽ʽ public NoteBOOK(String title){ this.setIconImage(image);//ͼ setTitle(title);// this.setResizable(true);//Сɵ this.setBackground(Color.cyan); this.setBounds(new Rectangle(150,100,800,550));//ڴС this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.out.println("ر"); System.exit(0); } public void windowOpened(WindowEvent e){ System.out.println(""); } });//رռ clip=getToolkit().getSystemClipboard();//ü this.initcopy();//ʼΪ textarea=new JTextArea(); textarea.setLineWrap(false); textarea.setFont(font); textarea.setForeground(Color.black); textarea.setBackground(Color.white); textscroll=new JScrollPane(textarea); this.add(textscroll); //ı //------------------------------------------------ searchdialog=new JDialog(this,"/Q",false); searchdialog.setResizable(false); searchdialog.setLayout(new BorderLayout()); searchdialog.setSize(250,230); searchok=new JButton("һ"); searchcancel=new JButton("ȡ"); searchtext=new JTextField("",10); searchtip=new JLabel("ؼ֣"); searchpanel=new JPanel(); searchpanel.setBorder(BorderFactory.createTitledBorder(""));//ӱ߿ searchpanel.setLayout(new BoxLayout(searchpanel, BoxLayout.Y_AXIS));//µ searchbuttonpanel=new JPanel(); searchbuttonpanel.setLayout(new FlowLayout()); searchtextpanel=new JPanel(); searchtextpanel.setLayout(new FlowLayout()); searchtextpanel.add(searchtip); searchtextpanel.add(searchtext); searchbuttonpanel.add(searchok); searchbuttonpanel.add(searchcancel); searchpanel.add(searchtextpanel); searchpanel.add(searchbuttonpanel); searchdialog.add(searchpanel,BorderLayout.NORTH); searchok.addActionListener(this); searchcancel.addActionListener(this); //Ի() changetext=new JTextField("",10); changetip=new JLabel("滻Ϊ "); changeok=new JButton("滻"); changeall=new JButton("ȫ滻"); changepanel=new JPanel(); changepanel.setBorder(BorderFactory.createTitledBorder("滻"));//ӱ߿ changepanel.setLayout(new BoxLayout(changepanel, BoxLayout.Y_AXIS));//µ changebuttonpanel=new JPanel(); changebuttonpanel.setLayout(new FlowLayout()); changetextpanel=new JPanel(); changetextpanel.setLayout(new FlowLayout()); changetextpanel.add(changetip); changetextpanel.add(changetext); changebuttonpanel.add(changeok); changebuttonpanel.add(changeall); changepanel.add(changetextpanel); changepanel.add(changebuttonpanel); searchdialog.add(changepanel,BorderLayout.CENTER); changeok.addActionListener(this); changeall.addActionListener(this); //Ի(滻) keyentertext=new TextField("",8); keyentertext.setEchoChar('*'); keyok=new JButton(""); keydialog=new JDialog(this,"",true); keydialog.setResizable(false); keydialog.setLayout(new FlowLayout()); keydialog.setSize(250,80); keydialog.add(keyentertext); keydialog.add(keyok); keyok.addActionListener(this); //Ի yes=new JButton(""); no=new JButton(""); cancel=new JButton("ȡ"); tip=new JLabel("ļѾĶҪļ"); dialog=new JDialog(this,"дְ",true); dialog.setResizable(false); dialog.setLayout(new FlowLayout()); dialog.setSize(250,100); dialog.add(tip); dialog.add(yes); dialog.add(no); dialog.add(cancel); yes.addActionListener(this); no.addActionListener(this); cancel.addActionListener(this); //ʾԻ ok=new JButton("ȷ"); can=new JButton("ȡ"); fontpara=new Choice(); fontpara.add("һ"); fontpara.add(""); fontpara.add("б"); fontpara.add("б"); fonttype=new JLabel("ѡ"); fontsize=new JLabel("Сѡ"); fontsizetext=new JTextField("18",2); fontlist=new JList(fontname); listscroll=new JScrollPane(fontlist); fontbuttonpanel=new JPanel(); fontbuttonpanel.setLayout(new FlowLayout(FlowLayout.RIGHT,10,10)); fontbuttonpanel.add(ok); fontbuttonpanel.add(can); fontmainpanel=new JPanel(); fontmainpanel.setLayout(new BorderLayout()); fontmainpanel.add(fonttype,BorderLayout.NORTH); fontmainpanel.add(listscroll,BorderLayout.CENTER); fontsizepanel=new JPanel(); fontsizepanel.setLayout(new FlowLayout(FlowLayout.RIGHT,10,10)); fontsizepanel.add(fontsize); fontsizepanel.add(fontsizetext); fontsizepanel.add(fontpara); fontdialog=new JDialog(this,"Ի",true); fontdialog.setResizable(false); fontdialog.setLayout(new BorderLayout()); fontdialog.setSize(440,200); fontdialog.add(fontmainpanel,BorderLayout.WEST); fontdialog.add(fontbuttonpanel,BorderLayout.SOUTH); fontdialog.add(fontsizepanel,BorderLayout.EAST); fontlist.addListSelectionListener(this); ok.addActionListener(this); can.addActionListener(this); //Ի //------------------------------------------------------- menusBar=new MenuBar(); file=new Menu("ļ"); edit=new Menu("༭"); format=new Menu("ʽ"); help=new Menu(""); newfile=new MenuItem("½"); open=new MenuItem(""); keep=new MenuItem(""); save=new MenuItem("Ϊ"); exit_out=new MenuItem("˳"); zcancel=new MenuItem(""); copy=new MenuItem(""); paste=new MenuItem("ճ"); cut=new MenuItem(""); delete=new MenuItem("ɾ"); selectall=new MenuItem("ȫѡ"); search=new MenuItem("/Q"); timeadd=new MenuItem("ʱ/"); autoline=new MenuItem("Զ"); text_font=new MenuItem("ʽ..."); colorchoose=new MenuItem("ɫ..."); backchoose=new MenuItem("ɫ..."); about=new MenuItem(""); keyopen=new MenuItem("ļ"); keysave=new MenuItem("ܱΪ"); newworkcut=new MenuShortcut(KeyEvent.VK_N); newfile.setShortcut(newworkcut); opencut=new MenuShortcut(KeyEvent.VK_O); open.setShortcut(opencut); dsavecut=new MenuShortcut(KeyEvent.VK_S); keep.setShortcut(dsavecut); savecut=new MenuShortcut(KeyEvent.VK_L); save.setShortcut(savecut); quitcut=new MenuShortcut(KeyEvent.VK_Q); exit_out.setShortcut(quitcut); fontchoosecut=new MenuShortcut(KeyEvent.VK_F); text_font.setShortcut(fontchoosecut); colorchoosecut=new MenuShortcut(KeyEvent.VK_Y); colorchoose.setShortcut(colorchoosecut); backchoosecut=new MenuShortcut(KeyEvent.VK_B); backchoose.setShortcut(backchoosecut); aboutcut=new MenuShortcut(KeyEvent.VK_H); about.setShortcut(aboutcut); timeaddcut=new MenuShortcut(KeyEvent.VK_F5); timeadd.setShortcut(timeaddcut); keyopencut=new MenuShortcut(KeyEvent.VK_P); keyopen.setShortcut(keyopencut); keysavecut=new MenuShortcut(KeyEvent.VK_K); keysave.setShortcut(keysavecut); copycut=new MenuShortcut(KeyEvent.VK_C); copy.setShortcut(copycut); pastecut=new MenuShortcut(KeyEvent.VK_V); paste.setShortcut(pastecut); cutcut=new MenuShortcut(KeyEvent.VK_X); cut.setShortcut(cutcut); deletecut=new MenuShortcut(KeyEvent.VK_DELETE); delete.setShortcut(deletecut); selectallcut=new MenuShortcut(KeyEvent.VK_A); selectall.setShortcut(selectallcut); zcancelcut=new MenuShortcut(KeyEvent.VK_Z); zcancel.setShortcut(zcancelcut); searchcut=new MenuShortcut(KeyEvent.VK_F3); search.setShortcut(searchcut); autolinecut=new MenuShortcut(KeyEvent.VK_F2); autoline.setShortcut(autolinecut); file.add(newfile); file.add(open); file.add(keep); file.add(save); file.addSeparator(); file.add(keyopen); file.add(keysave); file.addSeparator(); file.add(exit_out); edit.add(zcancel); edit.addSeparator(); edit.add(copy); edit.add(paste); edit.add(cut); edit.add(delete); edit.addSeparator(); edit.add(search); edit.addSeparator(); edit.add(selectall); edit.add(timeadd); format.add(autoline); format.addSeparator(); format.add(text_font); format.add(colorchoose); format.add(backchoose); help.add(about); menusBar.add(file); menusBar.add(edit); menusBar.add(format); menusBar.add(help); setMenuBar(menusBar); newfile.addActionListener(this); open.addActionListener(this); keep.addActionListener(this); save.addActionListener(this); exit_out.addActionListener(this); zcancel.addActionListener(this); copy.addActionListener(this); paste.addActionListener(this); cut.addActionListener(this); search.addActionListener(this); delete.addActionListener(this); selectall.addActionListener(this); keyopen.addActionListener(this); keysave.addActionListener(this); text_font.addActionListener(this); colorchoose.addActionListener(this); backchoose.addActionListener(this); timeadd.addActionListener(this); autoline.addActionListener(this); about.addActionListener(this); //˵ } //------------------------------------------------------ public void actionPerformed(ActionEvent e){ if(e.getSource()==newfile){ this.judge(); this.newwork(); } if(e.getSource()==open){ this.judge(); this.open(); } if(e.getSource()==keep){ this.dsave(); } if(e.getSource()==save){ this.save(); } if(e.getSource()==exit_out){ this.judge(); this.quit(); } if(e.getSource()==keyopen){ this.judge(); this.keyopen(); } if(e.getSource()==keysave){ this.keysave(); } if(e.getSource()==zcancel){ this.zcancel(); } if(e.getSource()==copy){ this.copy(); } if(e.getSource()==paste){ this.paste(); } if(e.getSource()==cut){ this.cut(); } if(e.getSource()==search){ searchdialog.setVisible(true); } if(e.getSource()==searchok){ this.search(); } if(e.getSource()==searchcancel){ searchdialog.setVisible(false); } if(e.getSource()==changeok){ this.change(); } if(e.getSource()==changeall){ this.changeall(); } if(e.getSource()==delete){ this.delete(); } if(e.getSource()==selectall){ this.selectall(); } if(e.getSource()==timeadd){ this.time(); } if(e.getSource()==autoline){ this.autoline(); } if(e.getSource()==text_font){ fontdialog.setVisible(true); } if(e.getSource()==colorchoose){ this.colorchoose(); } if(e.getSource()==backchoose){ this.backchoose(); } if(e.getSource()==about){ this.about(); } if(e.getSource()==cancel){ dialog.setVisible(false); enterquit=false; } if(e.getSource()==no){ if(!enterquit){ dialog.setVisible(false); textarea.setText(""); }else if(enterquit){ System.exit(0); } else{ } } if(e.getSource()==yes){ dialog.setVisible(false); this.save(); if(enterquit){ System.exit(0); } } if(e.getSource()==ok){ this.font(); textarea.setFont(font); fontdialog.setVisible(false); } if(e.getSource()==can){ fontdialog.setVisible(false); } if(e.getSource()==keyok){ keydialog.setVisible(false); } } public void valueChanged(ListSelectionEvent e){ texttype=fontname[fontlist.getSelectedIndex()]; } public void newwork(){ if(!havesave){ dialog.setVisible(true); }else{ textarea.setText(""); direct=""; canceltext=textarea.getText();//ڳ } opensource=textarea.getText(); } public void open(){ if(!havesave){ dialog.setVisible(true); }try{ filedialog=new FileDialog(this,"",FileDialog.LOAD); filedialog.setVisible(true); if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){ BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(filedialog.getDirectory()+filedialog.getFile()))); String temp=""; String now=(String)in.readLine(); while(now!=null){ temp+=now+"\r"+"\n"; now=(String)in.readLine(); } textarea.setText(temp); in.close(); opensource=temp; direct=filedialog.getDirectory()+filedialog.getFile(); canceltext=textarea.getText();//ڳ } }catch(Exception e){ System.out.println("Read error:"+e); JOptionPane.showMessageDialog(this,"","",JOptionPane.WARNING_MESSAGE); } } public void dsave(){ if(direct==""){ this.save(); } else if(direct!="null" && direct!="nullnull"){ try{ OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(direct)); out.write(textarea.getText()); out.close(); opensource=textarea.getText(); }catch(Exception e){ System.out.println("Write error:"+e); JOptionPane.showMessageDialog(this,"д","",JOptionPane.WARNING_MESSAGE); } } } public void save(){ try{ filedialog=new FileDialog(this,"",FileDialog.SAVE); filedialog.setVisible(true); if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){ OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(filedialog.getDirectory()+filedialog.getFile())); out.write(textarea.getText()); out.close(); opensource=textarea.getText(); direct=filedialog.getDirectory()+filedialog.getFile(); } }catch(Exception e){ System.out.println("Write error:"+e); JOptionPane.showMessageDialog(this,"д","",JOptionPane.WARNING_MESSAGE); } } public void quit(){ if(!havesave){ enterquit=true; dialog.setVisible(true); } else{ System.exit(0); } } public void judge(){//жǷ񱣴 if(textarea.getText().equals(opensource)){ havesave=true; } else{ havesave=false; } } public void font(){//ʽ try{ size=Integer.parseInt(fontsizetext.getText()); if(size<=0 || size>99){ size=18; throw new Exception("СΧΪ1~99,彫ԭΪĬֵ"); } }catch(Exception e){ JOptionPane.showMessageDialog(this,"С","",JOptionPane.WARNING_MESSAGE); } if(fontpara.getSelectedItem()=="һ"){ font=new Font(texttype,Font.PLAIN,size); } else if(fontpara.getSelectedItem()==""){ font=new Font(texttype,Font.BOLD,size); } else if(fontpara.getSelectedItem()=="б"){ font=new Font(texttype,Font.ITALIC,size); } else if(fontpara.getSelectedItem()=="б"){ font=new Font(texttype,Font.BOLD+Font.ITALIC,size); } else{} } public void colorchoose(){//ɫ fontcolor=JColorChooser.showDialog(this,"ɫѡ",textarea.getForeground()); textarea.setForeground(fontcolor); } public void backchoose(){//ɫ backcolor=JColorChooser.showDialog(this,"ɫѡ",textarea.getBackground()); textarea.setBackground(backcolor); } public void about(){// JOptionPane.showMessageDialog(this,"\tдְ\n\tдְ FOR JAVA,ҷļô123456ҲԼⱣһġ##κ","",JOptionPane.PLAIN_MESSAGE); } public void time(){//ǰʱ nowtime=new Date(); canceltext=textarea.getText();//ڳ textarea.replaceRange(nowtime+"",textarea.getSelectionStart(),textarea.getSelectionEnd()); } public void keysave(){//ܱ try{ FileDialog filedialog=new FileDialog(this,"ܱ",FileDialog.SAVE); filedialog.setVisible(true); text=new text(); text.textmain=textarea.getText(); text.keyword=""; keydialog.setVisible(true); this.keyset(); this.secret(savemode1,savemode2); if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){ ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(filedialog.getDirectory()+filedialog.getFile())); out.writeObject(text); out.close(); direct=filedialog.getDirectory()+filedialog.getFile(); } }catch(Exception e){ System.out.println("Write error:"+e); JOptionPane.showMessageDialog(this,"ܳ","",JOptionPane.WARNING_MESSAGE); } } public void keyopen(){//ܴ try{ FileDialog filedialog=new FileDialog(this,"",FileDialog.LOAD); filedialog.setVisible(true); if(filedialog.getDirectory()!=null && filedialog.getFile()!=null){ ObjectInputStream in=new ObjectInputStream(new FileInputStream(filedialog.getDirectory()+filedialog.getFile())); text=(text)in.readObject(); in.close(); this.breaksecret(savemode1,savemode2); keydialog.setVisible(true); this.keyjudge(keyentertext.getText(),text.keyword); textarea.setText(text.textmain); canceltext=textarea.getText();//ڳ direct=filedialog.getDirectory()+filedialog.getFile(); } }catch(Exception e){ System.out.println("Read error:"+e); JOptionPane.showMessageDialog(this,"","",JOptionPane.WARNING_MESSAGE); } } public void secret(char a,char b){// char main[]=text.textmain.toCharArray(); char key[]=text.keyword.toCharArray(); for(int i=0;i<main.length;i++){ main[i]=(char)(main[i]^a); } for(int i=0;i<key.length;i++){ key[i]=(char)(key[i]^b); } text.textmain=new String(main); text.keyword=new String(key); } public void breaksecret(char a,char b){// char main[]=text.textmain.toCharArray(); char key[]=text.keyword.toCharArray(); for(int i=0;i<main.length;i++){ main[i]=(char)(main[i]^a); } for(int i=0;i<key.length;i++){ key[i]=(char)(key[i]^b); } text.textmain=new String(main); text.keyword=new String(key); } public void copy(){ String selection=textarea.getSelectedText(); if (selection==null){} else{ StringSelection clipString=new StringSelection(selection); clip.setContents(clipString,clipString); } } public void initcopy(){//ʼ String selection=""; StringSelection clipString=new StringSelection(selection); clip.setContents(clipString,clipString); } public void paste(){ Transferable clipdata=clip.getContents(NoteBOOK.this); try{ canceltext=textarea.getText();//ڳ String temp=(String)clipdata.getTransferData(DataFlavor.stringFlavor); textarea.replaceRange(temp,textarea.getSelectionStart(),textarea.getSelectionEnd()); }catch(Exception e){} } public void cut(){ String selection=textarea.getSelectedText(); if (selection==null){} else{ canceltext=textarea.getText();//ڳ StringSelection clipString=new StringSelection(selection); clip.setContents(clipString,clipString); textarea.replaceRange("",textarea.getSelectionStart(),textarea.getSelectionEnd()); } } public void delete(){ canceltext=textarea.getText();//ڳ textarea.replaceRange("",textarea.getSelectionStart(),textarea.getSelectionEnd()); } public void selectall(){ textarea.selectAll(); } public void keyset(){// text.keyword=keyentertext.getText(); keyentertext.setText(""); } public void keyjudge(String a,String b){ if(a.equals(b)){ } else{ this.secret(savemode1,savemode2); JOptionPane.showMessageDialog(this,"","",JOptionPane.WARNING_MESSAGE); } } public void zcancel(){ String temp=textarea.getText(); textarea.setText(canceltext); canceltext=temp; } public void search(){ String needsearch=searchtext.getText(); String main=textarea.getText(); String temp; if(needsearch.equals("")){ JOptionPane.showMessageDialog(this,"ؼΪգ","",JOptionPane.WARNING_MESSAGE); } else if(needsearch.length()>main.length()){ JOptionPane.showMessageDialog(this,"ûҵؼ","ʾ",JOptionPane.INFORMATION_MESSAGE); } else{ int position=textarea.getSelectionEnd()-needsearch.length()+1; if(position>=main.length()-needsearch.length() ||position<0){ position=0; } for(;position<=main.length()-needsearch.length();position++){ temp=main.substring(position,position+needsearch.length()); if(temp.equals(needsearch)){ textarea.setSelectionStart(position); textarea.setSelectionEnd(position+needsearch.length()); break; } else if(position>=main.length()-needsearch.length()){ textarea.setSelectionStart(0); textarea.setSelectionEnd(0); JOptionPane.showMessageDialog(this,"ûҵؼ","ʾ",JOptionPane.INFORMATION_MESSAGE); break; } } } } public void change(){ String changeword=changetext.getText(); if(textarea.getSelectionStart()!=textarea.getSelectionEnd()){ textarea.replaceRange(changeword,textarea.getSelectionStart(),textarea.getSelectionEnd()); } else if(textarea.getSelectionStart()==textarea.getSelectionEnd()){ JOptionPane.showMessageDialog(this,"滻","",JOptionPane.WARNING_MESSAGE); } } public void changeall(){ String needsearch=searchtext.getText(); String changeword=changetext.getText(); String main=textarea.getText(); String temp; for(int i=0;i<=main.length()-needsearch.length();i++){ temp=main.substring(i,i+needsearch.length()); if(temp.equals(needsearch)){ textarea.setSelectionStart(i); textarea.setSelectionEnd(i+needsearch.length()); textarea.replaceRange(changeword,textarea.getSelectionStart(),textarea.getSelectionEnd()); main=textarea.getText(); } } } public void autoline(){ if(!textarea.getLineWrap()){ textarea.setLineWrap(true); autoline.setLabel("ȡԶ"); } else if(textarea.getLineWrap()){ textarea.setLineWrap(false); autoline.setLabel("Զ"); } } public static void main(String[] args) { NoteBOOK SlNotepad=new NoteBOOK("дְ"); SlNotepad.show(); } }
true
46743a06f8c808dc4b844ddeae9ba7af7b96b90d
Java
rohitjain00/Cracking-the-Coding-Interview
/C1q2.java
UTF-8
805
3.375
3
[]
no_license
import java.util.Scanner; public class C1q2 { private static int maxCharLength = 256; public static boolean permutationString(String str1, String str2) { int[] charCountArr = new int[maxCharLength]; if (str1.length() != str2.length()) { return false; } for (char i : str1.toCharArray()) { charCountArr[(int) i]++; } for (char i : str2.toCharArray()) { charCountArr[(int) i]--; } for (int i = 0; i < charCountArr.length; i++) { if (charCountArr[i] != 0) { return false; } } return true; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); if (permutationString(sc.nextLine(),sc.nextLine())) { System.out.println("T"); } else { System.out.println("F"); } } }
true
0b7eb65c1a38e8e3dd92f86fccf4512269cf1883
Java
zyk123/tb
/tomp/src/main/java/com/flash/toolbar/omp/remind/controller/RemindController.java
UTF-8
6,834
1.851563
2
[]
no_license
package com.flash.toolbar.omp.remind.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.flash.toolbar.omp.common.action.BaseAction; import com.flash.toolbar.omp.common.util.DateUtil; import com.flash.toolbar.omp.common.util.HtmlUtil; import com.flash.toolbar.omp.common.util.IdGenerator; import com.flash.toolbar.omp.model.SysRemindConfig; import com.flash.toolbar.omp.remind.bo.SysRemindConfigModel; import com.flash.toolbar.omp.remind.service.impl.RemindService; import com.flash.toolbar.omp.user.bo.QxUserModel; @Controller @RequestMapping(value="/remind") public class RemindController extends BaseAction{ private static final Logger log = Logger.getLogger(RemindController.class); @Resource private RemindService remindService; @RequestMapping(value="/show") public String show(){ return "remind/remind"; } @RequestMapping(value="/list") public void list(HttpServletRequest request, HttpServletResponse response,SysRemindConfigModel sysRemindConfigModel) { try { QxUserModel qxUserModel = getSessionModel(); if(qxUserModel!=null){ sysRemindConfigModel.getBean().setCountryno(qxUserModel.getBean().getCountryno()); sysRemindConfigModel.getBean().setToperatorid(qxUserModel.getBean().getToperatorid()); } List<SysRemindConfig> list = remindService.getRemindListInfo(sysRemindConfigModel); Map<String, Object> map = new HashMap<String, Object>(); map.put("list", list); map.put("page", sysRemindConfigModel.getPager()); HtmlUtil.writerJson(response, map); } catch (Exception e) { log.error("The exception of querying the remindlist :"+e); } } @RequestMapping(value="/batchOnOff") public void batchOnOff(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "batchIds[]") String[] batchIds,@RequestParam(value = "type") String type){ try { if (batchIds == null || batchIds.length == 0) { log.info("ID invalid!"); sendFailureMessage(response, "ID invalid!"); } else { remindService.batchOnOff(batchIds,type,getSessionModel()); log.info("Update success!"); sendSuccessMessage(response, "Update success!",batchIds.length); } } catch (Exception e) { sendFailureMessage(response, "Update failure!"); log.error("The exception of turning on or off :"+e); } } @RequestMapping(value="/batchSetTimeInterval") public void batchSetTimeInterval(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "batchIds[]") String[] batchIds,@RequestParam(value = "remindVal") String remindVal){ try { if (batchIds == null || batchIds.length == 0) { log.info("ID invalid!"); sendFailureMessage(response, "ID invalid!"); } else { remindService.batchSetTimeInterval(batchIds,remindVal,getSessionModel()); log.info("Update success!"); sendSuccessMessage(response, "Update success!",batchIds.length); } } catch (Exception e) { sendFailureMessage(response, "Update failure!"); log.error("The exception of modifying time interval :"+e); } } @RequestMapping(value="/modify") public void modify(HttpServletRequest request, HttpServletResponse response,SysRemindConfig sysRemindConfig){ try { QxUserModel qxUserModel = getSessionModel(); if(qxUserModel!=null){ sysRemindConfig.setCountryno(qxUserModel.getBean().getCountryno()); sysRemindConfig.setToperatorid(qxUserModel.getBean().getToperatorid()); sysRemindConfig.setModifydate(DateUtil.getTimeZoneDate(new Date(), qxUserModel.getTimeZone(), "yyyy-MM-dd HH:mm:ss")); sysRemindConfig.setModifyman(qxUserModel.getBean().getUserid()); } remindService.modify(sysRemindConfig); sendSuccessMessage(response, "Update success!"); } catch (Exception e) { sendFailureMessage(response, "Update failure!"); log.error("The exception of modifying :"+e); } } @RequestMapping(value="/add") public void add(HttpServletRequest request, HttpServletResponse response,SysRemindConfig sysRemindConfig){ try { QxUserModel qxUserModel = getSessionModel(); if(qxUserModel!=null){ sysRemindConfig.setCountryno(qxUserModel.getBean().getCountryno()); sysRemindConfig.setToperatorid(qxUserModel.getBean().getToperatorid()); sysRemindConfig.setModifydate(DateUtil.getTimeZoneDate(new Date(), qxUserModel.getTimeZone(), "yyyy-MM-dd HH:mm:ss")); sysRemindConfig.setModifyman(qxUserModel.getBean().getUserid()); } sysRemindConfig.setId(IdGenerator.getUUID()); SysRemindConfigModel sysRemindConfigModel = getTempsysRemindConfigModel(sysRemindConfig,qxUserModel); if(sysRemindConfigModel!=null && remindService.countByCondition(sysRemindConfigModel)==0){ remindService.add(sysRemindConfig); }else{ sendFailureMessage(response, "Sorry,Contains same data,Please re-enter!"); } sendSuccessMessage(response, "Update success!"); } catch (Exception e) { sendFailureMessage(response, "Update failure!"); log.error("The exception of modifying :"+e); } } @RequestMapping(value="/delete") public void delete(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "batchIds[]") String[] batchIds){ try { if (batchIds == null || batchIds.length == 0) { log.info("ID invalid!"); sendFailureMessage(response, "ID invalid!"); } else { remindService.deleteRemindList(batchIds,getSessionModel()); log.info("Delete success!"); sendSuccessMessage(response, "Delete success!",batchIds.length); } } catch (Exception e) { sendFailureMessage(response, "DeLete failure!"); log.error("The exception of deleting the remindList :"+e); } } private SysRemindConfigModel getTempsysRemindConfigModel(SysRemindConfig originalSysRemindConfig,QxUserModel qxUserModel){ if(qxUserModel==null || originalSysRemindConfig==null){ return null; } SysRemindConfigModel sysRemindConfigModel = new SysRemindConfigModel(); SysRemindConfig tempSysRemindConfig = new SysRemindConfig(); tempSysRemindConfig.setCountryno(qxUserModel.getBean().getCountryno()); tempSysRemindConfig.setToperatorid(qxUserModel.getBean().getToperatorid()); tempSysRemindConfig.setBrand(originalSysRemindConfig.getBrand()); tempSysRemindConfig.setType(originalSysRemindConfig.getType()); tempSysRemindConfig.setPreposindicator(originalSysRemindConfig.getPreposindicator()); sysRemindConfigModel.setBean(tempSysRemindConfig); return sysRemindConfigModel; } }
true
9fd27e6574cb2261f5074d23d938f652f84ed3aa
Java
IhoFenixMFS/SpaceInvaders
/app/src/main/java/com/example/hectormediero/spaceinvadersdas/Adapters/ScoreAdapter.java
UTF-8
3,701
2.5625
3
[]
no_license
package com.example.hectormediero.spaceinvadersdas.Adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Picture; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.hectormediero.spaceinvadersdas.Models.Score; import com.example.hectormediero.spaceinvadersdas.R; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class ScoreAdapter extends ArrayAdapter<Score> { private Context context; private ArrayList<Score> datos; private String mCurrentPhotoPath; public ScoreAdapter(Context context, ArrayList datos,String mCurrentPhotoPath) { super(context, R.layout.item_list_view,datos); this.context=context; this.datos=datos; this.mCurrentPhotoPath=mCurrentPhotoPath; } @Override public View getView(int position, View convertView, ViewGroup parent) { // En primer lugar "inflamos" una nueva vista, que será la que se // mostrará en la celda del ListView. Para ello primero creamos el // inflater, y después inflamos la vista. LayoutInflater inflater = LayoutInflater.from(context); View item = inflater.inflate(R.layout.item_list_view, null); // A partir de la vista, recogeremos los controles que contiene para // poder manipularlos. // Recogemos el ImageView y le asignamos una foto. ImageView imagen = (ImageView) item.findViewById(R.id.imageView); // imagen.setImageResource(R.drawable.celeste); setPic(imagen,datos.get(position).getNombre()); TextView numero = (TextView) item.findViewById(R.id.etNumero); numero.setText(datos.get(position).getPuntuacion().toString()); TextView etiqueta = (TextView) item.findViewById(R.id.etTag); etiqueta.setText(datos.get(position).getNombre()); return item; } private void setPic(ImageView imageView,String username) { // Get the dimensions of the View int targetW = 100; int targetH = 100; // Get the dimensions of the bitmap BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; String pathImage=findImage(username); if(pathImage.equals("No")){ imageView.setImageResource(R.drawable.celeste); }else{ BitmapFactory.decodeFile(pathImage, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; // Determine how much to scale down the image int scaleFactor = Math.min(photoW/targetW, photoH/targetH); // Decode the image file into a Bitmap sized to fill the View bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = scaleFactor; bmOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeFile(pathImage, bmOptions); imageView.setImageBitmap(bitmap); } } private String findImage(String username){ String path = mCurrentPhotoPath +File.separator; File f = new File(path); //obtiene nombres de archivos dentro del directorio. File file[] = f.listFiles(); for (int i=0; i < file.length; i++) { if(file[i].getName().contains(username)){ return file[i].getAbsolutePath(); } } return "No"; } }
true
89ad30a668642a9d5a7ff4d36d719ed00103c851
Java
raphaeloneves/shipping-api
/src/main/java/pt/raphaelneves/shipping/domain/entity/SupplierProduct.java
UTF-8
2,176
2.359375
2
[]
no_license
package pt.raphaelneves.shipping.domain.entity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import java.util.Map; import static java.util.Comparator.comparing; import static javax.persistence.GenerationType.IDENTITY; @AllArgsConstructor @EqualsAndHashCode @Getter @NoArgsConstructor @ToString @Entity @Table(name = "supplier_product", uniqueConstraints = @UniqueConstraint(name = "supplier_product_uk", columnNames = {"supplier_id", "product_id"})) public class SupplierProduct implements Comparable<SupplierProduct> { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id") private Long id; @ManyToOne @JoinColumn(name = "supplier_id") private Supplier supplier; @ManyToOne @JoinColumn(name = "product_id") private Product product; @Lob @Column(name = "delivery_times", nullable = false) private String deliveryTimes; @Column(name = "in_stock", nullable = false) private Integer inStock; public Map<String, Integer> getDeliveryTimes() { try { final var mapper = new ObjectMapper(); return mapper.readValue(this.deliveryTimes, new TypeReference<>() { }); } catch (final JsonProcessingException exception) { throw new IllegalArgumentException(exception); } } @Override public int compareTo(final SupplierProduct other) { return comparing(SupplierProduct::getId, Long::compareTo) .thenComparing(SupplierProduct::getProduct, comparing(Product::getName)) .compare(this, other); } }
true
b2f46b68f364e3f90af7611c709fd36edae176ba
Java
GarvitPareek5816/Internship_Project
/pdfmerge/app/src/main/java/com/example/lenovopc/pdfmerge/MainActivity.java
UTF-8
4,522
2.21875
2
[]
no_license
package com.example.lenovopc.pdfmerge; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; public class MainActivity extends FragmentActivity { private EditText txt1,txt2; private Button bt1,bt2; private Handler handler; private final int PICKFILE_RESULT_CODE=10; private String btTag=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt1=(EditText)findViewById(R.id.txtfirstpdf); txt2=(EditText)findViewById(R.id.txtsecondpdf); bt1=(Button)findViewById(R.id.bt1); bt2=(Button)findViewById(R.id.bt2); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btTag=((Button)v).getTag().toString(); showFileChooser(); } }); bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btTag=((Button)v).getTag().toString(); showFileChooser(); } }); public void mergePdfFiles(View view){ try { String[] srcs = {txt1.getText().toString(), txt2.getText().toString()}; mergePdf(srcs); }catch (Exception e){e.printStackTrace();} } public void mergePdf(String[] srcs){ try{ // Create document object Document document = new Document(); // Create pdf copy object to copy current document to the output mergedresult file PdfCopy copy = new PdfCopy(document, new FileOutputStream(Environment.getExternalStorageDirectory()+"/mergedresult.pdf")); // Open the document document.open(); PdfReader pr; int n; for (int i = 0; i < srcs.length; i++) { // Create pdf reader object to read each input pdf file pr = new PdfReader(srcs[i].toString()); // Get the number of pages of the pdf file n = pr.getNumberOfPages(); for (int page = 1; page <=n;page++) { // Import all pages from the file to PdfCopy copy.addPage( copy.getImportedPage(pr,page)); } } document.close(); // close the document }catch(Exception e){e.printStackTrace();} } @Override // Save tag of the clicked button // It is used to identify the button has been pressed public void onSaveInstanceState( Bundle outState) { super.onSaveInstanceState(outState); outState.putString("savText", btTag); } @Override // Restore the tag protected void onRestoreInstanceState( Bundle savedInstanceState) { super.onRestoreInstanceState( savedInstanceState); btTag=savedInstanceState.getString( "savText"); } private void showFileChooser(){ Log.e("AA","bttag="+btTag); String folderPath = Environment. getExternalStorageDirectory()+"/"; Intent intent = new Intent(); intent.setAction( Intent.ACTION_GET_CONTENT); Uri myUri = Uri.parse(folderPath); intent.setDataAndType( myUri ,"file/*"); Intent intentChooser = Intent.createChooser(intent, "Select a file"); startActivityForResult(intentChooser, PICKFILE_RESULT_CODE); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data != null) { if (requestCode == PICKFILE_RESULT_CODE) { if (resultCode == RESULT_OK) { String FilePath = data.getData().getPath(); if(bt1.getTag().toString().equals(btTag)) txt1.setText(FilePath); else txt2.setText(FilePath); } } } } }
true
62a053586454ee9a8cdf64deb54a729b2d831bf8
Java
ByMiles/Android-Java-SerialUsb-CC2531-Zigbee
/ZnpService/src/main/java/de/htw/tma/bic/ZnpService/service/ZnpService.java
UTF-8
1,854
2.5625
3
[]
no_license
package de.htw.tma.bic.ZnpService.service; import de.htw.tma.bic.ZnpService.callBack.RxCallBack; import de.htw.tma.bic.UsbDriver.UsbDriver; public class ZnpService { private static ZnpService instance; private static UsbDriver driver; private ZnpTxService znpTxService; private RxCallBack subscriber; private static boolean connected = false; private static boolean updatedChannel = false; public ZnpService(UsbDriver usbDriver) { driver = usbDriver; } public static ZnpService service(UsbDriver driver) { if (instance == null) instance = new ZnpService(driver); return instance; } public static ZnpService service() { return instance; } public void start(RxCallBack subscriber) { if (driver != null) connected = true; if (subscriber == null) return; try { updatedChannel = false; this.subscriber = subscriber; this.znpTxService = new ZnpTxService(driver); new ZnpRxService(driver, subscriber); connected = true; } catch (Exception e){ driver = null; connected = false; } } public void start(){ if (driver != null) connected = true; start(subscriber); } public ZnpTxService tx(){ return znpTxService; } public static String getUsbInfo(){ return (driver != null) ? driver.getUsbInfo() : "NO DEVICE\nFOUND!"; } public static boolean isConnected(){ return connected; } public static boolean isChangeChannel() { if (updatedChannel) { updatedChannel = false; return false; } return connected; } public void setUpdatedChannel(boolean updatedChannel) { this.updatedChannel = updatedChannel; } }
true
0cbee2eede11d28b1567831e652f5c1f475ad6ae
Java
coricoste/LaboratorSP10
/src/Package1/Paragraph.java
UTF-8
1,619
3.15625
3
[]
no_license
package Package1; import java.util.ArrayList; public class Paragraph implements Element, Observable{ private String _paragraphName; private AlignStrategy _strategy; private String _oldValue; private ArrayList<Observer> obsList = new ArrayList<Observer>(); public String get_paragraphName() { return _paragraphName; } public void set_paragraphName(String _paragraphName) { this._paragraphName = _paragraphName; } public Paragraph(String paragraphName){ _paragraphName = paragraphName; obsList.add(DocumentManager.getInstance().getFirstObserver()); } @Override public void print() { System.out.println("Paragraph name: "+get_paragraphName()); if(_strategy == null){ System.out.println(_paragraphName); }else{ _strategy.Print(_paragraphName); } } public void SetStrategy(AlignStrategy Strategy){ _strategy = Strategy; } @Override public void Accept(BookStatistics bookStatistics) { bookStatistics.Visit(this); } public void setNewValue(String newValue) { this._oldValue = _paragraphName; this._paragraphName = newValue; this.notifyObservers(); } public void addObserver(Observer ob) { this.obsList.add(ob); } public void removeObserver(Observer ob) { int indexObs = this.obsList.indexOf(ob); this.obsList.remove(indexObs); } public void notifyObservers() { for(Observer obs : this.obsList) { obs.update(this._oldValue,this._paragraphName); } } }
true
43e117d32eab6a6bdc51f37d8abd0fdf7711b779
Java
xiang205012/Test
/cjLibrary/src/main/java/cj/library/base/AppBaseAdapter.java
UTF-8
829
2.421875
2
[]
no_license
package cj.library.base; import java.util.List; import android.content.Context; import android.os.Bundle; import android.widget.BaseAdapter; /** * @Description:自定义的BaseAdapter,所有adapter的父类。 * Created by cj on 2015/11/22. */ public abstract class AppBaseAdapter<D> extends BaseAdapter { public Context context; public List<D> list;// public AppBaseAdapter(Context context, List<D> list) { this.context = context; this.list = list; } /** * update * @param list */ public void updateListView(List<D> list){ this.list = list; notifyDataSetChanged(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } }
true
4abdea57164479936e3ed32f8f123d9ab2e16de5
Java
haoshou/Java
/src/map/TestHashMap.java
UTF-8
993
3.515625
4
[]
no_license
package map; /** * HashMap是Map接口之中使用最多的一个子类 * 线程非安全,采取异步处理方式,性能相对更高,是JDK1.2推出的 * 允许将key或value设置为null */ import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class TestHashMap { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("name:", "小明"); map.put(null, "小红"); map.put("name:", "小西");//key重复,value会被新内容覆盖 map.put("test:", "小白"); /*System.out.println(map.get(null)); System.out.println(map.get("name:"));*/ Set<String> keySet = map.keySet(); //取得Map里面的所有Key Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key:" + key + "," + "value:" + map.get(key)); } } }
true
f41d8d32a1436f8df36fe1e86cb9d0ca4dd87b9d
Java
sleaof/bootcamp-frescos-project
/src/main/java/com/mercadolibre/dambetan01/model/Batch.java
UTF-8
1,099
2.0625
2
[]
no_license
package com.mercadolibre.dambetan01.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.time.LocalDate; import java.util.List; @Entity @Table(name = "batch") @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class Batch { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long batchId; private Double minTemperature; private Double currentTemperature; private LocalDate manufacturingDate; private LocalDate manufacturingTime; private Long initialQuantity; private Long currentQuantity; private LocalDate dueDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id_fk") private Product product; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "section_id_fk") private Section section; @OneToMany(mappedBy = "batchs") private List<InboundOrderHasBatch> inboundOrderHasBatch; @OneToMany(mappedBy = "batch") private List<BatchHasPurchaseOrder> purchaseOrders; }
true
23cd73b8235065b0b8d9e7fb8c198dc2ee8ad62c
Java
wplatform/HelloWorld
/world-service/src/main/java/com/rainbowland/service/characters/domain/MailItems.java
UTF-8
1,759
2.234375
2
[]
no_license
package com.rainbowland.service.characters.domain; import io.r2dbc.spi.Row; import org.springframework.data.relational.core.mapping.Table; import org.springframework.data.relational.core.mapping.Column; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.r2dbc.core.Parameter; import org.springframework.data.convert.WritingConverter; import org.springframework.data.r2dbc.mapping.OutboundRow; import lombok.Data; import java.util.Optional; @Data @Table("mail_items") public class MailItems { @Column("mail_id") private Integer mailId; @Column("item_guid") private Long itemGuid; @Column("receiver") private Long receiver; @ReadingConverter public static class RowMapper implements Converter<Row, MailItems> { public MailItems convert(Row row) { MailItems domain = new MailItems(); domain.setMailId(row.get("mail_id", Integer.class)); domain.setItemGuid(row.get("item_guid", Long.class)); domain.setReceiver(row.get("receiver", Long.class)); return domain; } } @WritingConverter public static class ParamMapper implements Converter<MailItems, OutboundRow> { public OutboundRow convert(MailItems source) { OutboundRow row = new OutboundRow(); Optional.ofNullable(source.getMailId()).ifPresent(e -> row.put("mail_id", Parameter.from(e))); Optional.ofNullable(source.getItemGuid()).ifPresent(e -> row.put("item_guid", Parameter.from(e))); Optional.ofNullable(source.getReceiver()).ifPresent(e -> row.put("receiver", Parameter.from(e))); return row; } } }
true
557a20666e2d2ce33dec8c6b5bb5040308027335
Java
seuCHENGHQ/Spring_Boot_SSMshop
/src/main/java/com/chq/ssmshop/entity/ProductCategory.java
UTF-8
1,142
2.0625
2
[]
no_license
package com.chq.ssmshop.entity; import java.util.Date; public class ProductCategory { private Integer productCategoryId; private String productCategoryName; private Integer priority; private Date createTime; private Date lastEditTime; private Shop shop; public Integer getProductCategoryId() { return productCategoryId; } public String getProductCategoryName() { return productCategoryName; } public Integer getPriority() { return priority; } public Date getCreateTime() { return createTime; } public Date getLastEditTime() { return lastEditTime; } public Shop getShop() { return shop; } public void setProductCategoryId(Integer productCategoryId) { this.productCategoryId = productCategoryId; } public void setProductCategoryName(String string) { this.productCategoryName = string; } public void setPriority(Integer priority) { this.priority = priority; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public void setLastEditTime(Date lastEditTime) { this.lastEditTime = lastEditTime; } public void setShop(Shop shop) { this.shop = shop; } }
true
0279a3fa0cd1092e221eacc3ad94f3625c5fab69
Java
liuanxin/mall-cloud-2
/mall-common/src/test/java/com/github/common/util/DateTest.java
UTF-8
1,039
2.78125
3
[]
no_license
package com.github.common.util; import com.github.common.date.DateFormatType; import com.github.common.date.DateUtil; import org.junit.jupiter.api.Test; import java.util.Date; public class DateTest { @Test public void date() { Date now = DateUtil.now(); System.out.println(now); System.out.println(DateUtil.formatDateTime(now)); System.out.println(DateUtil.formatDateTimeMs(now)); String date = DateUtil.formatDate(now); System.out.println(date); System.out.println(DateUtil.parse(date)); date = DateUtil.format(now, DateFormatType.YYYYMMDDHHMMSS); System.out.println(DateUtil.parse(date)); long end = DateUtil.parse("2019-01-03 01:02:02").getTime(); long start = DateUtil.parse("2019-01-01 01:02:03").getTime(); System.out.println(DateUtil.toHumanRoughly(end - start)); System.out.println(DateUtil.toHuman(end - start)); System.out.println(DateUtil.getDayStart(DateUtil.parse("2019-01-03 01:02:02"))); } }
true
503bfd412ef042ca6c5a58669a8b0fd6c6943f9b
Java
enermax626/simian-project
/src/test/java/com/simian/project/simianproject/domain/AnimalOrderTest.java
UTF-8
804
2.671875
3
[]
no_license
package com.simian.project.simianproject.domain; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AnimalOrderTest { @Test @DisplayName("Validate AnimalOrder Values") void values() { Assertions.assertEquals(AnimalOrder.values().length,2); Assertions.assertEquals(AnimalOrder.values()[0],AnimalOrder.SIMIAN); Assertions.assertEquals(AnimalOrder.values()[1],AnimalOrder.HUMAN); } @Test @DisplayName("Validate AnimalOrder String values") void valueOf() { Assertions.assertEquals(AnimalOrder.valueOf("SIMIAN"),AnimalOrder.SIMIAN); Assertions.assertEquals(AnimalOrder.valueOf("HUMAN"),AnimalOrder.HUMAN); } }
true
1b60ef3522ea1a1501b4b500b3ad733a5b2fd2f4
Java
casperenghuus/6878
/Gene4x/ARACNE/src/org/geworkbench/bison/datastructure/bioobjects/sequence/CSSequence.java
UTF-8
4,887
2.296875
2
[]
no_license
package org.geworkbench.bison.datastructure.bioobjects.sequence; import org.geworkbench.bison.datastructure.properties.CSDescribable; import org.geworkbench.bison.datastructure.properties.CSExtendable; import java.io.ObjectStreamField; import java.io.Serializable; import java.util.regex.Matcher; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class CSSequence implements DSSequence, Serializable { private final static ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("isDNA", boolean.class), new ObjectStreamField("label", String.class), new ObjectStreamField("sequence", String.class), new ObjectStreamField("descriptions", CSDescribable.class), new ObjectStreamField("extend", CSExtendable.class), new ObjectStreamField("id", String.class), new ObjectStreamField("serial", int.class), new ObjectStreamField("isEnabled", boolean.class) }; static final String[] repeats = {"(at){5,}", "a{7,}", "c{7,}", "g{7,}", "t{7,}"}; static final java.util.regex.Pattern[] repeatPattern = new java.util.regex.Pattern[repeats.length]; static java.util.regex.Pattern dnaPattern = java.util.regex.Pattern.compile("[^#acgtnxACGTNX]"); private String id = ""; private int serial = -1; private boolean isEnabled = true; private String sequence = new String(); private String label = new String(); private boolean isDNA = true; /** * Used in the implementation of the <code>Extendable</code> interface. */ protected CSExtendable extend = new CSExtendable(); /** * Used in the implementation of the <code>Describable</code> interface. */ protected CSDescribable descriptions = new CSDescribable(); public CSSequence() { } public CSSequence(String l, String s) { setSequence(s); label = l; } public String getLabel() { return label; } public String getSequence() { return sequence; } public CSSequence getSubSequence(int from, int to){ if (from >= 0 && to >= 0 && from < sequence.length() && to < sequence.length()) return new CSSequence(getLabel(), getSequence().substring(from, to)); return null; } public void setLabel(String l) { label = l; } public void setSequence(String s) { sequence = s; Matcher m = dnaPattern.matcher(sequence); if (m.find()) { isDNA = false; } } public String toString() { return label; } public int length() { return sequence.length(); } public boolean isDNA() { return isDNA; } public void maskRepeats() { for (int i = 0; i < repeats.length; i++) { if (repeatPattern[i] == null) { repeatPattern[i] = java.util.regex.Pattern.compile(repeats[i]); } Matcher m = repeatPattern[i].matcher(sequence); sequence = m.replaceAll("#########"); } } public void setID(String _id) { id = _id; } public String getID() { return id; } public void setSerial(int _serial) { serial = _serial; } public int getSerial() { return serial; } public boolean enabled() { return isEnabled; } public void enable(boolean status) { isEnabled = status; } public void clearName(String name) { extend.clearName(name); } public void forceUniqueValue(String name) { extend.forceUniqueValue(name); } public void allowMultipleValues(String name) { extend.allowMultipleValues(name); } public boolean isUniqueValue(String name) { return extend.isUniqueValue(name); } public void addDescription(String desc) { descriptions.addDescription(desc); } public String[] getDescriptions() { return descriptions.getDescriptions(); } public void removeDescription(String desc) { descriptions.removeDescription(desc); } public void addNameValuePair(String name, Object value) { extend.addNameValuePair(name, value); } public Object[] getValuesForName(String name) { return extend.getValuesForName(name); } public void shuffle() { char[] tokens = new char[sequence.length()]; for (int i = 0; i < sequence.length(); i++) { tokens[i] = sequence.charAt((int) (Math.random() * sequence.length())); } sequence = new String(tokens); } }
true
7d669277f4890270cb3f34252bb101503d7c540f
Java
peter517/BookCode
/UnderstandingTheJVM/src/other/thread/SynTest.java
UTF-8
1,118
3.40625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package other.thread; /** * * @author PenGuin */ class FooOne_Syn extends Thread { private int val; private String x = "A"; public FooOne_Syn(int v) { val = v; } public void printVal(int v, String y) { synchronized (this) { while (v < 500) { System.out.println(y + ": " + v++); } } } public void run() { printVal(val, x); } } class FooTwo_Syn extends Thread { private String x = "B"; private FooOne_Syn sameFoo; public FooTwo_Syn(FooOne_Syn f) { sameFoo = f; } public void run() { sameFoo.printVal(2, x); } } //只会对同一个对象的同一个方法加锁,f2与f1是不同的对象 public class SynTest { public static void main(String[] args) { FooOne_Syn f1 = new FooOne_Syn(1); f1.start(); FooTwo_Syn b = new FooTwo_Syn(f1); b.start(); // FooOne_Syn f2 = new FooOne_Syn(3); // f2.start(); } }
true
9c7b9fcc9a3cc03fb2fddef5ee81f7d041c6643d
Java
BessinkaA/masters-project
/hvac-service/src/main/java/com/cit/masters/hvacservice/HvacService.java
UTF-8
413
2.125
2
[]
no_license
package com.cit.masters.hvacservice; import org.springframework.stereotype.*; import static java.util.UUID.*; @Service public class HvacService { public Boolean receive(EnrichedTemperatureData data) { try { fromString(data.getTemperatureData().getSensorId()); return true; } catch (IllegalArgumentException exception) { return false; } } }
true
0cd7a70d2de2754b7a911eacfb02aa1680cd2721
Java
r8d8/lastlock
/QCA4020_SDK/QCA4020_SDK/target/mobileapp/android/qca_onboarding/app/src/main/java/com/qualcomm/qti/qca40xx/Util/Logger.java
UTF-8
2,488
2.390625
2
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-unknown-license-reference", "HPND", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
/* * Copyright (c) 2018 Qualcomm Technologies, Inc. * All Rights Reserved. * Confidential and Proprietary - Qualcomm Technologies, Inc. */ package com.qualcomm.qti.qca40xx.Util; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by ka.akshay on 10/14/2017. */ public class Logger { private static final String Log_TAG = "QCAOnboarding"; private static boolean isLogEnable = true; private static Logger logger = null; private static FileWriter writer; public static Logger getInstance() { if (logger == null) { logger = new Logger(); try { File root = new File(Environment.getExternalStorageDirectory(), "Notes"); if (!root.exists()) { root.mkdirs(); } SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); String filename = dateFormat.format(date) + ".txt"; File gpxfile = new File(root, filename); writer = new FileWriter(gpxfile); } catch (IOException e) { e.printStackTrace(); } } return logger; } public static void v(String TAG, String msg) { if (isLogEnable) { Log.v(TAG, msg); writeLogOnSD(TAG + " - \t" + msg + "\n"); } } public static void d(String TAG, String msg) { if (isLogEnable) { Log.d(TAG, msg); writeLogOnSD(TAG + " - \t" + msg + "\n"); } } public static void e(String TAG, String msg) { if (isLogEnable) { Log.e(TAG, msg); writeLogOnSD(TAG + " - \t" + msg + "\n"); } } public static void i(String TAG, String msg) { if (isLogEnable) { Log.i(TAG, msg); writeLogOnSD(TAG + " - \t" + msg + "\n"); } } private static void writeLogOnSD(String sBody) { try { if (writer != null) { writer.append(sBody); writer.flush(); } else { Log.i(Log_TAG, "File Writer not created"); } // writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
7e01ea6efb609b99f80d9bb28113f15175cf8cb8
Java
netboynb/matrix-leetcode
/src/main/java/com/matrix/easy/Solution6.java
UTF-8
2,095
3.921875
4
[]
no_license
package com.matrix.easy; import java.util.LinkedList; import java.util.List; /** * @创建人 netboy * @创建时间 2020/7/21 * @描述 字形变换 * 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 * * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: * * L C I R * E T O E S I I G * E D H N * 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 * * 请你实现这个将字符串进行指定行数变换的函数: * * string convert(string s, int numRows); * 示例 1: * * 输入: s = "LEETCODEISHIRING", numRows = 3 * 输出: "LCIRETOESIIGEDHN" * 示例 2: * * 输入: s = "LEETCODEISHIRING", numRows = 4 * 输出: "LDREOEIIECIHNTSG" * 解释: * * L D R * E O E I I * E C I H N * T S G * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/zigzag-conversion * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Solution6 { public static String convert(String s, int numRows) { if(null== s || s.length() <=2 || numRows <=1){ return s; } List<StringBuilder> list = new LinkedList<>(); for(int i =0;i < Math.min(numRows,s.length());i++){ list.add(new StringBuilder()); } int curRow = 0; boolean goDown = false; for(char cr : s.toCharArray()){ list.get(curRow).append(cr); if(curRow == 0 || curRow == numRows -1){ goDown = !goDown; } curRow += goDown ? 1 :-1; } StringBuilder result = new StringBuilder(); for(StringBuilder builder : list){ result.append(builder); } return result.toString(); } public static void main(String[] args) { String s = "ab"; String reuslt = Solution6.convert(s,3); System.out.print(reuslt); } }
true
711af4a68ac256e438e7e46f0d8484795198a8cd
Java
pokraas/Learning
/Algorithms_Princeton_1/src/Week4/Board.java
UTF-8
4,097
3.53125
4
[]
no_license
package Week4; import java.util.ArrayList; import java.util.Iterator; /** * A class to represent a n*n board with sliding tiles, like in the 15-puzzle. * @author Alex Pokras */ public class Board { private final int[][]tiles; private int n; private int manhattan, hamming; //cached values /** Create a new board from a n*n array of tiles*/ public Board(int[][]tiles) { this.tiles=tiles; n=tiles.length; manhattan=-1; hamming=-1; } /** number of tiles out of place (Hamming distance)*/ public int hamming() { if (hamming!=-1) return hamming; //return previously computed value int h=0; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (tiles[i][j]==0) continue; //disregard Hamming distance for the empty tile if (tiles[i][j]!=n*i+j+1) h++; } } hamming=h; return h; } /** In which row should this tile be placed?*/ private int row(int tile) { if (tile==0) return n-1; return (tile-1)/n; } /** In which column should this tile be placed?*/ private int col(int tile) { if (tile==0) return n-1; return (tile-1)%n; } /** For a tile at position (row,col) calculates Manhattan distance to its goal position*/ private int manhattanForTile (int row, int col, int tile) { if (tile==0) return 0; //disregard Manhattan distance for the empty tile return Math.abs(row-row(tile))+Math.abs(col-col(tile)); } /** Sum of Manhattan distances between tiles and their goals*/ public int manhattan() { if (manhattan!=-1) return manhattan; //return previously computed value int m=0; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { m+=manhattanForTile(i,j,tiles[i][j]); } } manhattan=m; return m; } /** Is this board the goal board? * (Are all tiles in growing order?)*/ public boolean isGoal() { return hamming()==0; } /** create a new Board with swapped tiles at (row1,col1) and (row2,col2)*/ private Board swap(int row1, int col1,int row2,int col2) { int[][] s = new int[n][n]; //copy tiles to s for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { s[i][j]=tiles[i][j]; } } //swap elements in s int temp = s[row1][col1]; s[row1][col1]=s[row2][col2]; s[row2][col2]=temp; return new Board(s); } /** Returns a board obtained by exchanging a pair of tiles. Useful to detect unsolvable boards.*/ public Board twin() { if (tiles[0][0]==0 || tiles[0][1]==0)return swap(1,0,1,1); //swap in the 1st row return swap(0,0,0,1); //swap in the 0th row } /** All neighboring boards (obtained via moving a neighboring non-empty tile to blank tile)*/ public Iterable<Board> neighbors(){//TODO sometimes non-neighboring boards are returned (?) ArrayList<Board> a = new ArrayList<Board>(); int i0=0,j0=0; //row and column of the empty tile //searching for the empty tile for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (tiles[i][j]==0) { i0=i; j0=j; break; } } } //adding neighbors to the ArrayList if (i0>0) a.add(swap(i0,j0,i0-1,j0)); if (i0<n-1) a.add(swap(i0,j0,i0+1,j0)); if (j0>0) a.add(swap(i0,j0,i0,j0-1)); if (j0<n-1) a.add(swap(i0,j0,i0,j0+1)); return a; } @Override public boolean equals (Object other) { if (! (other instanceof Board)) return false; if (this.n!=((Board)other).n) return false; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (this.tiles[i][j] != ((Board)other).tiles[i][j]) return false; } } return true; } /** Board dimension n*/ public int dimension() { return n; } @Override public String toString() { StringBuilder sb = new StringBuilder(Integer.toString(n)); sb.append('\n'); for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { sb.append(tiles[i][j]); sb.append(' '); } sb.append('\n'); } return sb.toString(); } public static void main(String[] args) { int[][] myTiles = { {8,1,3}, {4,0,2}, {7,6,5} }; Board board = new Board(myTiles); int[][] myTiles2 = { {0,3,7}, {4,5,6}, {2,8,1} }; Board board2 = new Board(myTiles2); System.out.println(board2.twin().toString()); } }
true
f5f9fa127729f3a2c0db4bf1376423c47edc6f3b
Java
EBI-IntAct/intact-cores
/intact-core/src/main/java/uk/ac/ebi/intact/core/config/ConfigurationHandler.java
UTF-8
11,478
1.640625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2011 The European Bioinformatics Institute, and others. * * 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 uk.ac.ebi.intact.core.config; import com.google.common.collect.Maps; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import uk.ac.ebi.intact.core.annotations.PersistentConfiguration; import uk.ac.ebi.intact.core.annotations.PersistentProperty; import uk.ac.ebi.intact.core.config.property.*; import uk.ac.ebi.intact.core.context.IntactContext; import uk.ac.ebi.intact.core.persistence.dao.meta.ApplicationDao; import uk.ac.ebi.intact.model.meta.Application; import uk.ac.ebi.intact.model.meta.ApplicationProperty; import javax.annotation.PostConstruct; import java.lang.reflect.Field; import java.util.Map; /** * @author Bruno Aranda (baranda@ebi.ac.uk) * @version $Id$ */ @Controller public class ConfigurationHandler { private static final Log log = LogFactory.getLog(ConfigurationHandler.class); private Map<Class, PropertyConverter> supportedPrimitiveConverter = Maps.newHashMap(); @Autowired private ApplicationContext springContext; @PostConstruct public void init() { supportedPrimitiveConverter.put( java.lang.Boolean.TYPE, springContext.getBean( BooleanPropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Short.TYPE, springContext.getBean( ShortPropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Integer.TYPE, springContext.getBean( IntegerPropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Long.TYPE, springContext.getBean( LongPropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Float.TYPE, springContext.getBean( FloatPropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Double.TYPE, springContext.getBean( DoublePropertyConverter.class ) ); supportedPrimitiveConverter.put( java.lang.Character.TYPE, springContext.getBean( CharPropertyConverter.class ) ); } @Transactional public Application loadConfiguration(Application application) { Application appFromDb = getApplicationDao().getByKey(application.getKey()); if (appFromDb != null) { application = appFromDb; } if (log.isInfoEnabled()) { log.info("Loading configuration for application: "+application.getKey()); } final ConfigurableListableBeanFactory beanFactory = IntactContext.getCurrentInstance().getSpringContext().getBeanFactory(); final Map<String,Object> beansWithConfig = beanFactory.getBeansWithAnnotation( PersistentConfiguration.class ); for (Map.Entry<String,Object> entry : beansWithConfig.entrySet()) { final String beanName = entry.getKey(); final Object beanWithConfig = entry.getValue(); for (Field field : beanWithConfig.getClass().getDeclaredFields()) { PersistentProperty persistentProperty = field.getAnnotation(PersistentProperty.class); if (persistentProperty != null) { String key = calculateKey(beanName, field, persistentProperty); ApplicationProperty applicationProperty = application.getProperty(key); if (applicationProperty != null) { // set the property String value = applicationProperty.getValue(); if (log.isDebugEnabled()) { log.debug("Loading field (db): "+key+"="+value); } setConfigValue(beanWithConfig, field, value); } else { String value = getConfigValue(beanWithConfig, field, persistentProperty.defaultValue()); if (log.isDebugEnabled()) { log.debug("Loading field (beanWithConfig object): "+key+"="+value); } // create the property applicationProperty = new ApplicationProperty(application, key, value); application.addProperty(applicationProperty); } } } } return application; } @Transactional public void persistConfiguration() { // update the Application object with the latest changes, since the last time the config was loaded Application application = IntactContext.getCurrentInstance().getApplication(); if (log.isInfoEnabled()) log.info("Persisting configuration for application: "+application.getKey()); Application dbApp = getApplicationDao().getByKey(application.getKey()); if (dbApp != null) { synchronizeApplication( application, dbApp ); application = dbApp; } Map<String,Object> beansWithConfig = IntactContext.getCurrentInstance().getSpringContext().getBeanFactory().getBeansWithAnnotation(PersistentConfiguration.class); for (Map.Entry<String,Object> entry : beansWithConfig.entrySet()) { final String beanName = entry.getKey(); final Object beanWithConfig = entry.getValue(); for (Field field : beanWithConfig.getClass().getDeclaredFields()) { PersistentProperty persistentProperty = field.getAnnotation(PersistentProperty.class); if (persistentProperty != null) { String key = calculateKey(beanName, field, persistentProperty); ApplicationProperty applicationProperty = application.getProperty(key); String value = getConfigValue(beanWithConfig, field, persistentProperty.defaultValue()); if (applicationProperty == null) { if (log.isDebugEnabled()) { log.debug("Creating field: " + key + "=" + value); } applicationProperty = new ApplicationProperty(application, key, value); application.addProperty(applicationProperty); } else { if (log.isDebugEnabled()) { log.debug("Updating field: " + key + "=" + value); } applicationProperty.setValue(value); } } } } // persist the application object getApplicationDao().saveOrUpdate(application); } /** * Synchronize all attributes of source onto target. * @param source the source application * @param target the target application */ private void synchronizeApplication( Application source, Application target ) { target.setDescription( source.getDescription() ); // create in target missing properties and update existing ones for ( ApplicationProperty sourceProperty : source.getProperties() ) { final ApplicationProperty targetProperty = target.getProperty( sourceProperty.getKey() ); if( targetProperty != null ) { targetProperty.setValue( sourceProperty.getValue() ); } else { target.addProperty( sourceProperty ); } } // remove from target those properties that are not in the source // final Iterator<ApplicationProperty> targetPropertiesIterator = target.getProperties().iterator(); // while ( targetPropertiesIterator.hasNext() ) { // ApplicationProperty targetProperty = targetPropertiesIterator.next(); // if( source.getProperty( targetProperty.getKey() ) == null ) { // targetPropertiesIterator.remove(); // } // } } private void setConfigValue(Object beanWithConfig, Field field, String value) { try { PropertyConverter converter = getPropertyConverter( field.getType() ); Object objectValue = converter.convertFromString( value ); PropertyUtils.setProperty(beanWithConfig, field.getName(), objectValue); } catch (Throwable e) { throw new RuntimeException("Problem writing field: "+field.getName(), e); } } private String getConfigValue(Object beanWithConfig, Field field, String defaultValue) { // get the value Object objValue = null; try { objValue = PropertyUtils.getProperty(beanWithConfig, field.getName()); } catch (Throwable e) { throw new RuntimeException("Problem reading field: "+field.getName(), e); } String value; if (objValue == null) { value = defaultValue; } else { PropertyConverter converter = getPropertyConverter( objValue.getClass() ); value = converter.convertToString(objValue); if (value == null) { value = defaultValue; } } return value; } private PropertyConverter getPropertyConverter( Class clazz ) { PropertyConverter converter = null; final ConfigurableApplicationContext springContext = IntactContext.getCurrentInstance().getSpringContext(); if( supportedPrimitiveConverter.containsKey( clazz ) ) { // we have a converter for this primitive type converter = supportedPrimitiveConverter.get( clazz ); } else { final Map<String, PropertyConverter> converters = springContext.getBeansOfType( PropertyConverter.class ); for (PropertyConverter converterCandidate : converters.values()) { if (converterCandidate.getObjectType().isAssignableFrom( clazz )) { converter = converterCandidate; break; } } } if( converter == null ) { throw new RuntimeException( "Could not find a PropertyConverter for attribute of type: " + clazz.getName() ); } return converter; } private String calculateKey(String beanName, Field field, PersistentProperty persistentProperty) { String key = persistentProperty.key(); if (key.isEmpty()) { key = beanName+"."+field.getName(); } return key; } private ApplicationDao getApplicationDao() { return IntactContext.getCurrentInstance().getDaoFactory().getApplicationDao(); } }
true
a93421a28a35202527c2bf9f630b7153dfc30105
Java
NishantAbhishek/GalleryApp
/app/src/main/java/com/ntech/galleryapp/Adapter/BottomCircular.java
UTF-8
1,841
2.53125
3
[]
no_license
package com.ntech.galleryapp.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.ntech.galleryapp.Model.ImageModel; import com.ntech.galleryapp.R; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import de.hdodenhof.circleimageview.CircleImageView; public class BottomCircular extends RecyclerView.Adapter<BottomCircular.ViewHolder>{ private ArrayList<ImageModel> imageModels; private Context mContext; public BottomCircular(ArrayList<ImageModel> imageModels, Context mContext) { this.imageModels = imageModels; this.mContext = mContext; } @NonNull @Override public BottomCircular.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.circular_image_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull BottomCircular.ViewHolder holder, int position) { holder.setData(imageModels.get(position)); } @Override public int getItemCount() { return imageModels.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private CircleImageView circleImageView; public ViewHolder(@NonNull View itemView) { super(itemView); circleImageView = itemView.findViewById(R.id.imgChooseImage); } public void setData(ImageModel imageModel){ Glide.with(mContext).load(imageModel.getPhotoGrapherImage().getLargeImage()).into(circleImageView); } } }
true
0ed152e76b563730d54a4217f7843c63e14906f5
Java
azyuzko/eclipsetransaq
/ru.eclipsetrader.transaq.core/src/ru/eclipsetrader/transaq/core/util/Holder3.java
UTF-8
836
3.015625
3
[]
no_license
package ru.eclipsetrader.transaq.core.util; public class Holder3<T1, T2, T3> { T1 t1; T2 t2; T3 t3; public Holder3(T1 t1, T2 t2, T3 t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; } public T1 getFirst(){ return t1; } public T2 getSecond() { return t2; } public T3 getThird() { return t3; } @Override public String toString() { return String.valueOf(t1) + " - " + String.valueOf(t2) + " - " + String.valueOf(t3); } @Override public int hashCode() { return t1.hashCode() + t2.hashCode() + t3.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Holder3<?, ?, ?>) { @SuppressWarnings("unchecked") Holder3<T1, T2, T3> h = (Holder3<T1, T2, T3>)obj; return t1.equals(h.t1) && t2.equals(h.t2) && t3.equals(h.t3); } else { return false; } } }
true
6ca71292251bd0a1bda18d37cae3aa9841b0bfe6
Java
victorLxry/tvbrowserandroid
/TV-Browser/src/org/tvbrowser/tvbrowser/UpdateAlarmValue.java
UTF-8
3,140
1.851563
2
[ "LicenseRef-scancode-other-permissive" ]
permissive
/* * TV-Browser for Android * Copyright (C) 2013 René Mach (rene@tvbrowser.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to use, copy, modify or merge the Software, * furthermore to publish and distribute the Software free of charge without modifications and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.tvbrowser.tvbrowser; import java.util.concurrent.atomic.AtomicBoolean; import org.tvbrowser.content.TvBrowserContentProvider; import org.tvbrowser.settings.SettingConstants; import org.tvbrowser.utils.IOUtils; import org.tvbrowser.utils.PrefUtils; import org.tvbrowser.utils.UiUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; public class UpdateAlarmValue extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { final AtomicBoolean firstStart = new AtomicBoolean(false); if(intent != null && intent.getAction() != null && (intent.getAction().equals("android.intent.action.BOOT_COMPLETED") || intent.getAction().equals("android.intent.action.QUICKBOOT_POWERON"))) { SettingConstants.setReminderPaused(context, false); firstStart.set(true); } new Thread() { public void run() { PrefUtils.initialize(context); IOUtils.handleDataUpdatePreferences(context); Cursor alarms = context.getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA, new String[] {TvBrowserContentProvider.KEY_ID, TvBrowserContentProvider.DATA_KEY_STARTTIME}, " ( " + TvBrowserContentProvider.DATA_KEY_MARKING_REMINDER + " OR " + TvBrowserContentProvider.DATA_KEY_MARKING_FAVORITE_REMINDER + " ) AND ( " + TvBrowserContentProvider.DATA_KEY_ENDTIME + " >= " + System.currentTimeMillis() + " ) ", null, TvBrowserContentProvider.KEY_ID); alarms.moveToPosition(-1); while(alarms.moveToNext()) { long id = alarms.getLong(alarms.getColumnIndex(TvBrowserContentProvider.KEY_ID)); long startTime = alarms.getLong(alarms.getColumnIndex(TvBrowserContentProvider.DATA_KEY_STARTTIME)); UiUtils.removeReminder(context, id); UiUtils.addReminder(context, id, startTime, UpdateAlarmValue.class, firstStart.get()); } alarms.close(); } }.start(); } }
true
e7b1cbd013ad16587c939be8edf59ed002f3210e
Java
andreireinus/IDK0051
/ylesanne2/src/y2/game/tests/BoardTest.java
UTF-8
892
2.984375
3
[]
no_license
package y2.game.tests; import org.junit.Test; import y2.game.Board; import y2.game.Tile; import static org.junit.Assert.*; public class BoardTest { @Test public void testGetStart() { Board b = new Board(); assertNull(b.getStart()); b.append(new Tile("test")); assertNotNull(b.getStart()); } @Test public void testAppend() { Board b = new Board(); b.append(new Tile("1")); assertEquals(1, getBoardLength(b.getStart())); b.append(new Tile("2")); assertEquals(2, getBoardLength(b.getStart())); b.append(new Tile("3")); assertEquals(3, getBoardLength(b.getStart())); b.append(new Tile("4")); assertEquals(4, getBoardLength(b.getStart())); } private int getBoardLength(Tile tile) { int length = 1; while (tile.getNext() != null) { tile = tile.getNext(); length++; } return length; } }
true
6d9b2275150994ff877649b799484b311db0c827
Java
2767274907/crm
/src/main/java/com/t248/lmf/crm/service/impl/RoleServiceImpl.java
UTF-8
2,700
1.976563
2
[]
no_license
package com.t248.lmf.crm.service.impl; import com.t248.lmf.crm.entity.Right; import com.t248.lmf.crm.entity.Role; import com.t248.lmf.crm.entity.User; import com.t248.lmf.crm.repository.RightRepostitory; import com.t248.lmf.crm.repository.RoleRepository; import com.t248.lmf.crm.repository.SysRoleRightRepostitor; import com.t248.lmf.crm.service.IRoleService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; @Service("iRoleService") public class RoleServiceImpl implements IRoleService { @Resource private RoleRepository roleRepository; @Resource private RightRepostitory rightRepostitory; @Resource SysRoleRightRepostitor sysRoleRightRepostitor; @Override public List<Role> findAllRoles() { return roleRepository.findAll(); } @Override public Role getRolebyUser(User user) { return roleRepository.findRoleByUsers(user); } @Override public Role getRoleByroleId(Long roleId) { return roleRepository.getOne(roleId); } @Override public void saveRole(Role role) { roleRepository.save(role); } @Override public Page<Role> findRoles(String roleName , Pageable pageable) { return roleRepository.findAll(new Specification<Role>(){ @Override public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { List<Predicate> predicates = new ArrayList<>(); if (roleName != null && roleName != "") { predicates.add(criteriaBuilder.like(root.get("roleName"),"%"+roleName+"%")); } return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } },pageable); } @Override public List<Right> findAllRights() { return rightRepostitory.findAll(); } @Override public List<Role> findRolesByNameLink(String roleName) { return roleRepository.findRolesByRoleNameLike("%"+roleName+"%"); } @Override public void deleRole(Long roleId) { roleRepository.deleteById(roleId); } @Override public void delSysRoleRight(Long roleId) { sysRoleRightRepostitor.deleteByRole(roleRepository.getOne(roleId)); } }
true
e9ca6cf77b5460f11a3c87da02aa695e3cb57b05
Java
dzheleznyakov/LearningJavaFx
/src/main/java/zh/learn/javafx/ch10container/tilepane/TilePaneTileAlignment.java
UTF-8
1,277
3.109375
3
[]
no_license
package zh.learn.javafx.ch10container.tilepane; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.scene.layout.TilePane; import javafx.stage.Stage; import zh.learn.javafx.Aux; public class TilePaneTileAlignment extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { TilePane tileAlignCenter = createTilePane(Pos.CENTER); TilePane tileAlignTopRight = createTilePane(Pos.TOP_LEFT); HBox root = new HBox(tileAlignCenter, tileAlignTopRight); root.setFillHeight(false); Aux.showStage(stage, root, "The tileAlignment Property for TilePane"); } private TilePane createTilePane(Pos tileAlignment) { Button[] buttons = new Button[] { new Button("Tiles"), new Button("are"), new Button("aligned"), new Button("at"), new Button(tileAlignment.toString()) }; TilePane tpane = new TilePane(5, 5, buttons); tpane.setTileAlignment(tileAlignment); tpane.setPrefColumns(3); Aux.style(tpane); return tpane; } }
true
bf632e39c7ded187d08bc2e8bef6551dfadc5e7e
Java
derrick3192/populationoptimizer
/src/main/java/rhinova/framework/drawable/ImageShape.java
UTF-8
330
2.265625
2
[]
no_license
package rhinova.framework.drawable; import java.awt.Dimension; import java.awt.Graphics; import rhinova.metapopulation.model.graphicx.DrawingFunctions; public class ImageShape extends Shape { public static void drawBackGround(Graphics g, Dimension d, String path) { DrawingFunctions.drawBackgroundImage(g, d, path); } }
true
ea72a8786e7c6f619b2d2b2a9b535ef573c93118
Java
Librazy/HibernateProvider
/src/test/java/org/librazy/provider/hibernate/TestEntity.java
UTF-8
1,373
2.28125
2
[]
no_license
package org.librazy.provider.hibernate; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Date; import java.util.UUID; @Entity @Table(name = "TestEntity") public class TestEntity { private String test; private UUID uuid; private int id; private Date dateTime; @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(name = "uuid", length = 36) public UUID getUuid() { return uuid; } public TestEntity setUuid(UUID uuid) { this.uuid = uuid; return this; } @Id @Column(name = "id", nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public TestEntity setId(int id) { this.id = id; return this; } @CreationTimestamp @Column(name = "timestamp") @Temporal(TemporalType.TIMESTAMP) public Date getDateTime() { return dateTime; } public TestEntity setDateTime(Date dateTime) { this.dateTime = dateTime; return this; } @Column(name = "test") public String getTest() { return test; } public TestEntity setTest(String test) { this.test = test; return this; } }
true
9442f8967444aaaa03eb26b249e992b7f71382e7
Java
peterbeleganski/rms-maven
/src/main/java/com/restaurant/management/model/Restaurant.java
UTF-8
1,154
1.851563
2
[]
no_license
package com.restaurant.management.model; import com.restaurant.management.config.util.CollectionNames; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import java.util.ArrayList; import java.util.List; @EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor @NoArgsConstructor @Document(collection = CollectionNames.RESTAURANTS) public class Restaurant extends BaseObject { private String name; @DBRef private List<Order> orders = new ArrayList<>(); private String coverImageUrl; private String coverImage; private String logoImageUrl; private String logoImage; @DBRef private User owner; @DBRef private List<User> waiters = new ArrayList<>(); @DBRef private List<Product> products = new ArrayList<>(); private String location; private List<String> menus = new ArrayList<>(); @DBRef private List<Category> categories = new ArrayList<>(); private boolean active; }
true
7c68191d0ea2fd427282def70336ed4f33ab09ee
Java
jaideeprana/design-patterns
/src/main/java/creationalPatterns/prototypePattern/sheep/CloneFactory.java
UTF-8
163
2.921875
3
[ "MIT" ]
permissive
package creationalPatterns.prototypePattern.sheep; public class CloneFactory { public Animal getClone(Animal anAnimal) { return anAnimal.makeClone(); } }
true
a97d9357812c3f1052d7eabd08e3328ab6fe33f9
Java
hieutd231000/java_oop
/sortArray/src/com/company/Main.java
UTF-8
1,146
3.78125
4
[]
no_license
package com.company; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int count = scanner.nextInt(); int[] myArray = getIntegers(count); printArray(sortIntegers(myArray)); } private static int[] getIntegers(int num){ Scanner scanner = new Scanner(System.in); int[] myArray = new int[num]; for(int i=0 ; i<num; i++){ myArray[i] = scanner.nextInt(); } return myArray; } private static void printArray(int[] myArray){ for(int i=0 ; i< myArray.length; i++){ System.out.println("Element " + i + " contents " + myArray[i]); } } private static int[] sortIntegers(int[] myArray){ for(int i=0 ; i<myArray.length; i++){ for(int j=i+1; j<myArray.length; j++){ if(myArray[i]<myArray[j]){ int move = myArray[i]; myArray[i] = myArray[j]; myArray[j] = move; } } } return myArray; } }
true
2b4d9067fcb98d5c7cad174cc0cb8d5055c2e5cd
Java
CharllesSilva/crud-dsdeliver
/src/entities/OrderStatus.java
UTF-8
71
1.703125
2
[]
no_license
package entities; public enum OrderStatus { PENDING, DELIVERES; }
true
a60ca44e3a36ab1fa6050bc0f2c7d62882c170ea
Java
lipanpan/lpp-aop-study
/src/main/java/com/example/aop/javassist/core/AbstractAdviceHandler.java
UTF-8
1,256
2.453125
2
[]
no_license
package com.example.aop.javassist.core; import javassist.util.proxy.MethodHandler; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * Created by lipan on 2017/9/24. * Describe: 抽象横切面 */ public abstract class AbstractAdviceHandler implements AdviceMethod, MethodHandler { @Override public Object invoke(Object var1, Method var2, Method var3, Object[] var4) throws Throwable { AdviceContext context = new AdviceContext(); context.setTarget(var1).setMethod(var2).setArgs(var4).setMethodProxy(var3); before(context); Object result; try { around(context); result = var3.invoke(var1, var4); around(context); } catch (Exception e) { handleException(context, e); throw e; } finally { after(context); } return result; } @Override public void before(AdviceContext context) { } @Override public void around(AdviceContext context) { } @Override public void after(AdviceContext context) { } @Override public void handleException(AdviceContext context, Exception e) { } }
true
35bc629da971585d1eaf1bc3be0546e04f4660bc
Java
baaldor/drinkersdiary
/src/drinkerdiary/business/BusinessFacade.java
UTF-8
678
2.421875
2
[]
no_license
/* * 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 drinkerdiary.business; import drinkerdiary.Core.Drinker; import drinkerdiary.Core.Substance; import java.util.Set; /** * * @author BaalDor */ public interface BusinessFacade { public Set<String> loadAllDrinkerNames(); //Storing public void storeDrinker(Drinker myDrinker); public void storeSubstance(Substance mySubstance); //EntityFactory public Drinker createNewDrinker(); public Substance createNewSubstance(); }
true
c5d766bf3b9e81cbf2947ecb05210718c5a2ea05
Java
ifoets/teaching
/algorithms/src/main/java/com/design/analysis/core/algo/randomizedalgorithms/RandomAlgoImpl.java
UTF-8
7,731
3.515625
4
[]
no_license
/** * */ package com.design.analysis.core.algo.randomizedalgorithms; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.TreeSet; /* * * @author GuruG * * 1. Random Variables 2. Binomial Random Variables 3. Generate integer from 1 to 7 with equal probability 4. Make a fair coin from a biased coin 5. Shuffle a given array 6. Reservoir Sampling 7. Select a random number from stream, with O(1) space 8. Random number generator in arbitrary probability distribution fashion 9. Write a function that generates one of 3 numbers according to given probabilities 10. K�th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) 11. Birthday Paradox 12. Linearity of Expectation 13. Expected Number of Trials until Success 14. Load Balancing on Servers (Randomized Algorithm) 15. Karger�s algorithm for Minimum Cut | Set 1 (Introduction and Implementation) 16. Select a Random Node from a Singly Linked List 17. Karger�s algorithm for Minimum Cut | Set 2 (Analysis and Applications) 18. Primality Test | Set 2 (Fermat Method) 19. Generate 0 and 1 with 25% and 75% probability 20. Implement rand3() using rand2() 21. Strong Password Suggester Program 22. Freivald�s Algorithm to check if a matrix is product of two 23. mplement random-0-6-Generator using the given random-0-1-Generator 24. Select a Random Node from a tree with equal probability 25. QuickSort using Random Pivoting 26. Operations on Sparse Matrices 27. Random Walk (Implementation in Python) 28. Expectation or expected value of an array 29. Estimating the value of Pi using Monte Carlo 30. Randomized Binary Search Algorithm 31. Shuffle a deck of cards 32. Program to generate CAPTCHA and verify user 33. Find an index of maximum occurring element with equal probability 34. Implement rand12() using rand6() in one line */ public class RandomAlgoImpl implements IRandomAlgo { /** 1. Randomized Algorithms | Set 3 (1/2 Approximate Median) **/ public int randApproxMedian(int a[], int n) { Random r = new Random(); if (n == 0) return 0; double k = 100 * Math.log(n); int k1 = (int) k; TreeSet<Integer> tree = new TreeSet<>(); for (int i = 0; i < k1; i++) { int index = r.nextInt(n); tree.add(a[index]); } Iterator<Integer> itr = tree.iterator(); int temp = tree.size() / 2 - 1; for (int i = 0; i < temp; i++) { itr.next(); } return itr.next(); } /** 2. Binomial Random Variables **/ /** 3. Generate integer from 1 to 7 with equal probability **/ /* generate 1-5 with equal probability */ Set<Integer> set = new HashSet<>(); @Override public int equlProbRandom1To5() { int rNo = 0; Random r = new Random(); if (set.isEmpty()) { set = new HashSet<>(); for (int i = 1; i <= 5; i++) set.add(i); } rNo = r.nextInt(25); while (!set.contains(rNo + 1)) { rNo = r.nextInt(25); } set.remove(rNo + 1); return rNo + 1; } Set<Integer> set1 = new HashSet<>(); @Override // TODO test is failing public int rad1To7ByRand1To5() { int i = equlProbRandom1To5() + equlProbRandom1To5() - 5; if (i < 22) return i % 7 + 1; return rad1To7ByRand1To5(); } /** 4. Make a fair coin from a biased coin */ int i = 0; @Override public int zero60AndOne40Return() { i++; if (i % 2 == 0) { return 1; } else { if (i == 5) i = 0; return 0; } } int j = 1; // @Override public int zero60AndOne40Return1() { j++; if (j % 2 == 0) { return 1; } else { if (j == 5) j = 0; return 0; } } @Override public int equlProbByzero60AndOne40Return() { int a = zero60AndOne40Return(); int b = zero60AndOne40Return1(); if (a == 0 && b == 1) return 0; if (a == 1 && b == 0) return 1; return equlProbByzero60AndOne40Return(); } /** 5. Shuffle a given array **/ @Override public void suffleArray(int a[]) { Random r = new Random(); for (int i = a.length - 1; i > 0; i--) { int j = r.nextInt(i); int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /** 6. Reservoir Sampling **/ @Override public int[] selectKItems(int stream[], int k) { int i; // index for elements in stream[] // reservoir[] is the output array. Initialize it with // first k elements from stream[] int reservoir[] = new int[k]; for (i = 0; i < k; i++) reservoir[i] = stream[i]; Random r = new Random(); // Iterate from the (k+1)th element to nth element for (; i < stream.length; i++) { // Pick a random index from 0 to i. int j = r.nextInt(i + 1); // If the randomly picked index is smaller than k, // then replace the element present at the index // with new element from stream if (j < k) reservoir[j] = stream[i]; } System.out.println("Following are k randomly selected items"); System.out.println(Arrays.toString(reservoir)); return reservoir; } /** 7.Select a random number from stream, with O(1) space **/ public static int count = 0; @Override public int selectRnFromStream(Integer strm[]) { if (count == 0) count = strm.length; if (count == 1) { count--; return strm[0]; } // swap the random selected index no with last and decrease the count; Random r = new Random(); int index = r.nextInt(count); int temp = strm[index]; strm[index] = strm[count - 1]; strm[count - 1] = temp; count--; return strm[count]; } /** 8. Random number generator in arbitrary probability distribution fashion **/ public int countr = 0; Integer arr[] = null; @Override public int randomByFreqDistirbution(int a[], int frq[]) { if (countr == 0) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < frq.length; i++) { for (int j = 0; j < frq[i]; j++) list.add(a[i]); } arr = new Integer[list.size()]; for (int j = 0; j < arr.length; j++) arr[j] = list.get(j); if (countr == 0) countr = arr.length; if (countr == 1) { countr--; return arr[0]; } } Random r = new Random(); int index = r.nextInt(countr); int temp = arr[index]; arr[index] = arr[countr - 1]; arr[countr - 1] = temp; countr--; return arr[countr]; } /** * 9. Write a function that generates one of 3 numbers according to given * probabilities **/ @Override public int generateNoInGienProbal(int x, int y, int z, int px, int py, int pz) { // Generate a number from 1 to 100 Random rm = new Random(); int r = rm.nextInt(100); // r is smaller than px with probability px/100 if (r < px) return x; // r is greater than px and smaller than or equal to px+py // with probability py/100 if (r < (px + py)) return y; // r is greater than px+py and smaller than or equal to 100 // with probability pz/100 else return z; } /** * 10. K�th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear * Time) no are unque and positive **/ public int kthLargestSmallestUnsortedArr(int a[], int k, boolean isSmlOrLar) { int max = a[0]; int min = a[0]; for (int i = 1; i < a.length; i++) { if (max < a[i]) max = a[i]; if (min > a[i]) min = a[i]; } int b[] = new int[max + 1]; for (int i = 0; i < a.length; i++) b[a[i]] = a[i]; int count = 0; if (isSmlOrLar) { for (int i = 0; i < b.length; i++) { if (b[i] != 0) count++; if (count == k) return b[i]; } } else { for (int i = b.length - 1; i >= 0; i--) { if (b[i] != 0) count++; if (count == k) return b[i]; } } return -1; } /** 11. Birthday Paradox **/ public double birthdayParadox(double p) { return Math.ceil(Math.sqrt(2 * 365 * Math.log(1 / (1 - p)))); } }
true
683cb174ed576913401adbbd8529ebb6577876a1
Java
lixiaopeng98/interview
/src/main/java/com/interview/demo/redis/releaseandsub/ReleaseAndSub.java
UTF-8
1,274
2.8125
3
[]
no_license
package com.interview.demo.redis.releaseandsub; /** * @describe: redis 发布 与 订阅 * @author: lxp * @date: 2021/1/6 14:32 */ public class ReleaseAndSub { /** * 命令 * * 订阅某个频道 * PUBSCRIBE "news.it" * * 向 news.it 频道 发送 hello 消息 * PUBLISH "news.it" "hello" * */ /** * 1. 服务器状态在 pubsub_channels 字典保存了所有频道的订阅关系: * SUBSCRIBE命令负责将客户端和被订阅的频道关联到这个字典里面, * UNSUBSCRIBE命令则负责接触客户端和被退订频道之间的关联 * 2. 服务器状态在pubsub_patterns 链表保存了所有模式的订阅关系: * PSUBSCRIBE 命令负责将客户端和被订阅的模式记录到这个链表中 * PUNSUBSCRIBE 命令则负责移除客户端和被退订模式在链表中的记录 * 3. PUBLISH 命令通过访问 pubsub_channels 字典来向频道的所有订阅者发送消息, * 通过访问pubsub_channels 链表来向所有匹配频道的模式的订阅者发送消息 * 4. PUBSUB 命令的三个子命令都是通过读取 pubsub_channels 字典和 pubsub_patterns * 链表中的信息来实现的 */ }
true
5d8d92a85e4c44ba6806a3fc4e77742f1f702588
Java
agelogeo/GotPuzzled
/src/guiPackage/BackgroundSound.java
ISO-8859-7
1,197
2.65625
3
[]
no_license
package guiPackage; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; /** * sound.wav "" 100 . * @author Admin * */ public class BackgroundSound { Clip clip; public BackgroundSound(){ try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("sound.wav")); clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.loop(100); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Clip getMusic(){ return clip; } public void startMusic(){ clip.start(); } public void stopMusic(){ clip.stop(); } }
true
d7499f7b1bee899e4bb8fd233d9ffd2cfb6cc087
Java
renecordier/android-openid-client
/libs/AndroidOpenidClient/android-openid-client/src/main/java/com/bip/androidopenidclient/response/OAuth2Response.java
UTF-8
1,026
1.8125
2
[]
no_license
package com.bip.androidopenidclient.response; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by rene on 06/03/17. */ public class OAuth2Response { @SerializedName("access_token") public String accessToken; @SerializedName("token_type") public String tokenType; @SerializedName("expires_in") public Integer expiresIn; @SerializedName("refresh_token") public String refreshToken; // Optional @SerializedName("search_token") public List<String> searchToken; @SerializedName("id_token") public String idToken; public String scope; @SerializedName("@httpResponseCode") public Integer httpResponseCode; @SerializedName("@requestId") public String requestId; public String code; public String state; // Error fields public String error; @SerializedName("error_uri") public String errorUri; @SerializedName("@errorCode") public ApiErrorCode errorCode; public String errorMsg; }
true
70422a5b1e716fd860aeecd221cb65b8ee8782b1
Java
chengqu/Simcity201
/src/LYN/CustomerAgent.java
UTF-8
10,783
2.359375
2
[]
no_license
package LYN; import LYN.gui.CustomerGui; import LYN.gui.RestaurantGui; import LYN.interfaces.Cashier; import LYN.interfaces.Customer; import LYN.interfaces.Host; import LYN.interfaces.Waiter; import agent.Agent; import agents.Person; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import tracePanelpackage.AlertLog; import tracePanelpackage.AlertTag; /** * Restaurant customer agent. */ public class CustomerAgent extends Agent implements Customer { private String name; private int hungerLevel = 5; // determines length of meal Timer timer = new Timer(); private CustomerGui customerGui; private int TABLENUM; private double Check; private String choice = null; private int a = 3; Random randnumber = new Random(); private double money; // agent correspondents private Host host; private Waiter waiter; //private Menu menu; private Cashier cashier; Random run = new Random(); private Person p; // private boolean isHungry = false; //hack for gui public enum AgentState {DoingNothing, WaitingInRestaurant, BeingSeated, Seated, lookingatfood,callwaitertocome,ordering,reordered,Eating, DoneEating, Leaving, waittocheck,checking,leaverestaurant}; private AgentState state = AgentState.DoingNothing;//The start state public enum AgentEvent {none, gotHungry, followHost, seated, wanttoorder,waittoorder,reorder,gotfood,doneEating, gotcheck, gotchange,doneLeaving,nofoodandleave, paying}; AgentEvent event = AgentEvent.none; /** * Constructor for CustomerAgent class * * @param name name of the customer * @param gui reference to the customergui so the customer can send it messages */ public CustomerAgent(Person p, String name){ super(); this.p = p; this.name = name; } public List<String> menus = new ArrayList<String>(); /** * hack to establish connection to Host agent. */ public void setHost(HostAgent host) { this.host = host; } public void setWaiter(WaiterAgent waiter){ this.waiter = waiter; } public void setCashier(CashierAgent cashier){ this.cashier = cashier; } // Messages public void gotHungry() {//from animation AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"I'm hungry" + p.money); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"I'm hungry"+ p.money); /* if(this.name.equals("salad")){ money = 6; } money = money + 2; */ event = AgentEvent.gotHungry; stateChanged(); } public void msgcannotwait(){ AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"I can not wait, I am leaving " + name); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"I can not wait, I am leaving " + name); customerGui.DoExitRestaurant(); } public void msgFollowMe(Waiter w, int a, Menu m) { event = AgentEvent.followHost; if(p.money>=5.99 && p.money<8.99){ menus.add(m.Salad()); } else { menus.add(m.Chicken()); menus.add(m.Salad()); menus.add(m.Pizza()); menus.add(m.Steak()); } this.waiter = w; TABLENUM = a; stateChanged(); } public void msgAnimationFinishedGoToSeat() { //from animation event = AgentEvent.seated; stateChanged(); } public void msgnotenoughmoney() { event = AgentEvent.nofoodandleave; stateChanged(); } public void msgwhatwouldyoulike() { event = AgentEvent.waittoorder; stateChanged(); } public void msgwhatwouldyouliketoreorder(String choice) { for (int i = 0; i<menus.size(); i++) { if(menus.get(i) == choice){ menus.remove(i); break; } } if(menus.size() == 0) { event = AgentEvent.nofoodandleave; a = 3; } else { event = AgentEvent.reorder; } stateChanged(); } public void msgHereisyourfood() { event = AgentEvent.gotfood; stateChanged(); } public void msghereisyourbill(double check) { event = AgentEvent.gotcheck; Check = check; stateChanged(); } public void msghereisyourchange(double change) { AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"Here is my change" + change); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"Here is my change" + change); if(change>=0){ p.money = (float)change; } event = AgentEvent.gotchange; stateChanged(); } public void msgAnimationFinishedLeaveRestaurant() { //from animation event = AgentEvent.doneLeaving; stateChanged(); } public void msgArriveatcashier() { event = AgentEvent.paying; stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ protected boolean pickAndExecuteAnAction() { // CustomerAgent is a finite state machine try{ if (state == AgentState.DoingNothing && event == AgentEvent.gotHungry ){ state = AgentState.WaitingInRestaurant; goToRestaurant(); return true; } if (state == AgentState.WaitingInRestaurant && event == AgentEvent.followHost ){ state = AgentState.BeingSeated; SitDown(); return true; } if (state == AgentState.BeingSeated && event == AgentEvent.seated){ state = AgentState.lookingatfood; lookatfood(); return true; } if (state == AgentState.lookingatfood && event == AgentEvent.wanttoorder){ state = AgentState.callwaitertocome; callwaiter(); return true; } if (state == AgentState.callwaitertocome && event == AgentEvent.waittoorder){ state = AgentState.ordering; tellwaiterthechoice(); return true; } if ((state == AgentState.ordering) && event == AgentEvent.reorder){ event = AgentEvent.none; tellwaiterthechoice(); return true; } if ((state == AgentState.ordering) && event == AgentEvent.gotfood){ state = AgentState.Eating; EatFood(); return true; } if (state == AgentState.Eating && event == AgentEvent.doneEating){ state = AgentState.Leaving; p.hungerLevel = 0; leaveTable(); return true; } if( state == AgentState.Leaving && event == AgentEvent.paying) { state = AgentState.waittocheck; iwannacheck(); return true; } if (state == AgentState.waittocheck && event == AgentEvent.gotcheck){ state = AgentState.checking; givemoneytoCashier(); return true; } if ((state == AgentState.checking && event == AgentEvent.gotchange)){ state = AgentState.leaverestaurant; p.hungerLevel = 0; getcheckandleave(); return true; } if( (event == AgentEvent.nofoodandleave && state == AgentState.ordering)) { state = AgentState.leaverestaurant; leave(); return true; } if( (event == AgentEvent.nofoodandleave && state == AgentState.lookingatfood)) { state = AgentState.leaverestaurant; leave(); return true; } if (state == AgentState.leaverestaurant && event == AgentEvent.doneLeaving){ state = AgentState.DoingNothing; //no action return true; } }catch (ConcurrentModificationException errorCCE) { return true; } return false; } // Actions private void goToRestaurant() { host.msgIWantFood(this);//send our instance, so he can respond to us } private void SitDown() { customerGui.DoGoToSeat(TABLENUM);//hack; only one table } private void lookatfood(){ boolean leave = false; Random rand1 = new Random(); if( p.money < 5.99) { if (rand1.nextInt(2) == 0) { leave = true; timer.schedule(new TimerTask() { Object cookie = 1; public void run() { msgnotenoughmoney(); } }, 1000); } } if(leave == false) { timer.schedule(new TimerTask() { Object cookie = 1; public void run() { event = AgentEvent.wanttoorder; //isHungry = false; stateChanged(); } }, 4000); } } private void callwaiter(){ waiter.msgReadyToOrder(this); } private void tellwaiterthechoice(){ AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"Sending message to waiter what do I want"); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"Sending message to waiter what do I want"); if(p.money>=5.99 && p.money < 8.99){ AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"I can only afford salad, and I will do that"); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"I can only afford salad, and I will do that"); choice = "Salad"; } else if(this.name.equals("pizza")){ choice = "Pizza"; } else { String[] t = menus.toArray(new String[0]); choice = t[run.nextInt(t.length)]; } a = 1; waiter.msgHereismychoice(this,choice); } private void EatFood() { a = 2; //This next complicated line creates and starts a timer thread. //We schedule a deadline of getHungerLevel()*1000 milliseconds. //When that time elapses, it will call back to the run routine //located in the anonymous class created right there inline: //TimerTask is an interface that we implement right there inline. //Since Java does not all us to pass functions, only objects. //So, we use Java syntactic mechanism to create an //anonymous inner class that has the public method run() in it. timer.schedule(new TimerTask() { Object cookie = 1; public void run() { event = AgentEvent.doneEating; //isHungry = false; stateChanged(); } }, 10000);//getHungerLevel() * 1000);//how long to wait before running task } private void leaveTable() { AlertLog.getInstance().logMessage(AlertTag.LYNCustomer, this.name,"Leaving and sending message to waiter."); AlertLog.getInstance().logMessage(AlertTag.LYN, this.name,"Leaving and sending message to waiter."); a = 3; waiter.msgDoneEatingAndLeaving(this); customerGui.gotocashier(); } private void iwannacheck() { cashier.msgcustomercheck(this); } private void givemoneytoCashier(){ if(p.money < Check){ cashier.msgcustomernotenoughmoney(this,p.money,Check); } else { cashier.msghereismoney(this,Check,p.money); p.money-=Check; } } private void getcheckandleave() { customerGui.DoExitRestaurant(); p.hungerLevel = 0; p.msgDone(); } private void leave() { customerGui.DoExitRestaurant(); waiter.msgDoneEatingAndLeaving(this); p.msgDone(); } // Accessors, etc. public String getName() { return name; } public int getHungerLevel() { return hungerLevel; } public void setHungerLevel(int hungerLevel) { this.hungerLevel = hungerLevel; //could be a state change. Maybe you don't //need to eat until hunger lever is > 5? } public String getchoice(){ return choice; } public int getstate() { return a; } public String toString() { return "customer " + getName(); } public void setGui(CustomerGui g) { customerGui = g; } public CustomerGui getGui() { return customerGui; } }
true
fa3f2a7257e64c5517b66765b1efe2c5969532ee
Java
mumuling/LoanWallet
/app/src/main/java/com/pingxun/daishangqianbao/ui/activity/other/ProductInfoActivity.java
UTF-8
8,121
1.78125
2
[]
no_license
package com.pingxun.daishangqianbao.ui.activity.other; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.orhanobut.logger.Logger; import com.pingxun.daishangqianbao.R; import com.pingxun.daishangqianbao.base.BaseActivity; import com.pingxun.daishangqianbao.data.ProductInfoBean; import com.pingxun.daishangqianbao.meijie.DemoActivity; import com.pingxun.daishangqianbao.other.G_api; import com.pingxun.daishangqianbao.other.InitDatas; import com.pingxun.daishangqianbao.other.Urls; import com.pingxun.daishangqianbao.ui.view.EmptyLayout; import com.pingxun.daishangqianbao.ui.view.IsApplyDialogPopupView; import com.pingxun.daishangqianbao.utils.ActivityUtil; import com.pingxun.daishangqianbao.utils.Convert; import com.pingxun.daishangqianbao.utils.GlideImgManager; import com.pingxun.daishangqianbao.utils.NetUtil; import com.pingxun.daishangqianbao.utils.ToastUtils; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.OnClick; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; /** * 产品详情页 */ public class ProductInfoActivity extends BaseActivity implements G_api.OnResultHandler { @BindView(R.id.iv_product) ImageView mIvProduct;//产品图片 @BindView(R.id.tv_title) TextView mTvTitle;//产品标题 @BindView(R.id.tv_quota) TextView mTvQuota;//额度范围 @BindView(R.id.tv_time) TextView mTvTime;//额度期限 @BindView(R.id.tv_speed) TextView mTvSpeed;//最快放款 @BindView(R.id.tv_rate_explain) TextView mTvRateExplain;//利率说明 @BindView(R.id.tv_process) TextView mTvProcess;//申请流程 @BindView(R.id.tv_condition) TextView mTvCondition;//申请条件 @BindView(R.id.tv_datum) TextView mTvDatum; //申请材料 @BindView(R.id.btn_enter) Button mBtnEnter;//立即借款 @BindView(R.id.parent_view) LinearLayout mParentView; @BindView(R.id.empty_layout) EmptyLayout mEmptyLayout; private String sId;//产品ID private static final int GET_FIND_BY_ID = 1;//获取产品详情 private static final int POST_APPLY = 2;//立即申请 private final static int REQUESTCODE = 333; // 返回的结果码 private String mWebUrls; private String mNameStr; @Override protected int getLayoutId() { return R.layout.activity_product_info; } @Override protected void initData() { initTopView("产品详情"); Bundle bundle = getIntent().getExtras(); if (bundle != null) { sId = bundle.getString(InitDatas.PROUDUCT_ID); mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING); update(); } } @Override public void onResult(String jsonStr, int flag) { mEmptyLayout.setErrorType(EmptyLayout.NO_ERROR); mParentView.setVisibility(View.VISIBLE); switch (flag) { case GET_FIND_BY_ID: Logger.json(jsonStr); ProductInfoBean mProductInfoBean = Convert.fromJson(jsonStr, ProductInfoBean.class); if (mProductInfoBean == null || !mProductInfoBean.isSuccess()) { ToastUtils.showToast(me, "获取产品详情失败"); return; } if (mProductInfoBean.isSuccess()) { mNameStr = mProductInfoBean.getData().getName(); GlideImgManager.glideLoader(me, mProductInfoBean.getData().getDetailImg(), R.mipmap.tu_jiazai, R.mipmap.tu_jiazai, mIvProduct, 1); //Glide.with(me).load(mProductInfoBean.getData().getDetailImg()).crossFade().transform(new GlideRoundTransform(me, 30)).into(mIvProduct); mTvTitle.setText(mNameStr);//产品名称 mTvQuota.setText("额度范围 " + initTvQuota(mProductInfoBean.getData().getStartAmount(), mProductInfoBean.getData().getEndAmount())); mTvTime.setText("额度期限 " + mProductInfoBean.getData().getStartPeriod() + "~" + mProductInfoBean.getData().getEndPeriod() + mProductInfoBean.getData().getPeriodTypeStr()); mTvSpeed.setText("最快放款 " + mProductInfoBean.getData().getLoanDay() + "天"); mTvRateExplain.setText(mProductInfoBean.getData().getRateMemo()); mTvProcess.setText(mProductInfoBean.getData().getApplyFlow()); mTvCondition.setText(mProductInfoBean.getData().getApplyCondition()); mTvDatum.setText(mProductInfoBean.getData().getApplyMaterial()); mWebUrls = mProductInfoBean.getData().getUrl(); break; } break; case POST_APPLY: // Logger.json(jsonStr); break; } } @Override public void onError(int flag) { if (NetUtil.getNetWorkState(me)==-1) { mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR); } } private String initTvQuota(Double start, Double end) { String newStr = String.valueOf((start / 10000)) + "-" + String.valueOf((end / 10000)) + "万元"; return newStr; } @OnClick({R.id.btn_enter, R.id.empty_layout}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.btn_enter://立即申请 postPoint(); Bundle bundle = new Bundle(); bundle.putString("url", mWebUrls); bundle.putString("productName", mNameStr); if (mWebUrls.contains("jie.gomemyf.com")) { ActivityUtil.goForward(me, DemoActivity.class,REQUESTCODE,bundle); } else { ActivityUtil.goForward(me, WebViewActivity.class,REQUESTCODE, bundle); } break; case R.id.empty_layout://重连 mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING); update(); break; } } /** * 数据埋点 */ private void postPoint() { //手机型号 String model = Build.MODEL; //设备厂商 String carrier = Build.MANUFACTURER; Map<String, String> params = new HashMap<String, String>(); params.put("productId", sId); params.put("deviceNumber", model + "(" + carrier + ")"); params.put("applyArea", InitDatas.latitude + ";" + InitDatas.longitude); params.put("channelNo", InitDatas.CHANNEL_NO); params.put("appName", InitDatas.APP_NAME); JSONObject jsonObj = new JSONObject(params); G_api.getInstance().setHandleInterface(this).upJson(Urls.URL_POST_APPLY_LOAN, jsonObj, POST_APPLY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUESTCODE) { IsApplyDialogPopupView isApplyDialogPopupViewView = new IsApplyDialogPopupView(me, sId); isApplyDialogPopupViewView.setPopupWindowFullScreen(true); isApplyDialogPopupViewView.showPopupWindow(); } } private void update() { Observable.timer(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { getInfo(); } }); } private void getInfo() { Map<String, String> params = new HashMap<>(); params.put("id", sId); G_api.getInstance().setHandleInterface(this).getRequest(Urls.URL_GET_FIND_BY_ID,params, GET_FIND_BY_ID); } }
true
a587b49b665bd0806ed72c7b2b84107ed7a53ff4
Java
martin-kolinek/c-compiler
/src/transformers/TypeBlockModifier.java
UTF-8
1,865
2.75
3
[]
no_license
package transformers; import declaration.ResolvedDeclaration; import expression.CastExpression; import expression.SizeofType; import statements.Statement; import toplevel.FunctionDefinition; import toplevel.FunctionParameter; public class TypeBlockModifier extends EmptyBlockModifier { private TypeModifierFactory tmf; private StatementModifierFactory smf; private ExpressionModifierFactory emf; public TypeBlockModifier(final TypeModifierFactory tmf) { this.tmf=tmf; emf = new ExpressionModifierFactory() { @Override public ExpressionModifier create() { return new TypeExpressionModifier(tmf); } }; smf = new StatementModifierFactory() { @Override public StatementModifier create() { return new ExpressionStatementModifier(emf); } }; } @Override public void visit(FunctionDefinition i) { i.returnType=TransformerUtil.transformType(i.returnType, tmf); for(FunctionParameter fp : i.parameters) { fp.type=TransformerUtil.transformType(fp.type, tmf);; } if(i.body!=null) i.body=TransformerUtil.transformStatement(i.body, smf); super.visit(i); } @Override public void visit(ResolvedDeclaration i) { i.type=TransformerUtil.transformType(i.type, tmf); if(i.initializer!=null) TransformerUtil.transformInitializer(i.initializer, emf); super.visit(i); } @Override public void visit(Statement i) { super.visit(TransformerUtil.transformStatement(i, smf)); } } class TypeExpressionModifier extends EmptyExpressionModifier { TypeModifierFactory mod; public TypeExpressionModifier(TypeModifierFactory fac) { mod=fac; } @Override public void visit(CastExpression e) { e.type = TransformerUtil.transformType(e.type, mod); super.visit(e); } @Override public void visit(SizeofType e) { e.type = TransformerUtil.transformType(e.type, mod); super.visit(e); } }
true
192caca863c535f5e95a8a83c1335e19e2e74fb6
Java
nanitight/Integrated-Data-Intelligence-Suite
/Analyse_Service/src/main/java/com/Analyse_Service/Analyse_Service/service/AnalyseServiceImpl.java
UTF-8
14,243
2.171875
2
[]
no_license
package com.Analyse_Service.Analyse_Service.service; import com.Analyse_Service.Analyse_Service.dataclass.ParsedData; import com.Analyse_Service.Analyse_Service.dataclass.TweetWithSentiment; import com.Analyse_Service.Analyse_Service.exception.InvalidRequestException; import com.Analyse_Service.Analyse_Service.request.*; import com.Analyse_Service.Analyse_Service.response.*; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.spark.ml.fpm.FPGrowth; import org.apache.spark.ml.fpm.FPGrowthModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.*; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; @Service public class AnalyseServiceImpl { public AnalyseDataResponse analyzeData(AnalyseDataRequest request) throws InvalidRequestException { if (request == null) { throw new InvalidRequestException("AnalyzeDataRequest Object is null"); } if (request.getDataList() == null){ throw new InvalidRequestException("DataList is null"); } ArrayList<ParsedData> dataList = request.getDataList(); //set data /*******************Find pattern******************/ ArrayList<String> sentiments = new ArrayList<>(); ArrayList<String> dataSendList = new ArrayList<>(); for (int i=0 ;i < dataList.size(); i++){ String row = ""; String text = dataList.get(i).getTextMessage(); String location = dataList.get(i).getLocation(); String date = dataList.get(i).getDate(); System.out.println("HERE IS THE DATE1 _______________________________ : " + date); date = date.replaceAll("\\s+","/"); System.out.println("HERE IS THE DATE2 _______________________________ : " + date); String likes = String.valueOf(dataList.get(i).getLikes()); FindSentimentRequest sentimentRequest = new FindSentimentRequest(dataList.get(i).getTextMessage()); FindSentimentResponse sentimentResponse = this.findSentiment(sentimentRequest); row = sentimentResponse.getSentiment().getCssClass() + " " + date + " "+ likes; dataSendList.add(row); } FindPatternRequest findPatternRequest = new FindPatternRequest(dataSendList); FindPatternResponse findPatternResponse = this.findPattern(findPatternRequest); FindRelationshipsRequest findRelationshipsRequest = new FindRelationshipsRequest(dataSendList); FindRelationshipsResponse findRelationshipsResponse = this.findRelationship(findRelationshipsRequest); GetPredictionRequest getPredictionRequest = new GetPredictionRequest(dataSendList); GetPredictionResponse getPredictionResponse = this.getPredictions(getPredictionRequest); return new AnalyseDataResponse(findPatternResponse.getPattenList(), findRelationshipsResponse.getPattenList(), getPredictionResponse.getPattenList()); } public FindPatternResponse findPattern(FindPatternRequest request) throws InvalidRequestException { if (request == null) { throw new InvalidRequestException("AnalyzeDataRequest Object is null"); } if (request.getDataList() == null){ throw new InvalidRequestException("DataList is null"); } SparkSession spark = SparkSession .builder() .appName("JavaFPGrowthExample") .master("local") .getOrCreate(); /*List<Row> data = Arrays.asList( RowFactory.create(Arrays.asList("Hatflied good popular".split(" "))), RowFactory.create(Arrays.asList("Hatflied good red popular".split(" "))), RowFactory.create(Arrays.asList("Hatflied good".split(" "))) );*/ ArrayList<String> reqData = request.getDataList(); List<Row> data = new ArrayList<>(); for(int i=0; i < reqData.size(); i++){ data.add( RowFactory.create(Arrays.asList(reqData.get(i).split(" ")))); } spark.sparkContext().setLogLevel("OFF"); List<Row> test = new ArrayList<>(); test.add(RowFactory.create(Arrays.asList("1 2 5".split(" ")))); System.out.println(test.get(0).toString()); StructType schema = new StructType(new StructField[]{ new StructField( "items", new ArrayType(DataTypes.StringType, true), false, Metadata.empty()) }); Dataset<Row> itemsDF = spark.createDataFrame(data, schema); FPGrowthModel model = new FPGrowth() .setItemsCol("items") .setMinSupport(0.5) .setMinConfidence(0.6) .fit(itemsDF); LogManager.getRootLogger().setLevel(Level.OFF); //model.freqItemsets().show(); // Display generated association rules. //model.associationRules().show(); List<Row> Adata = model.associationRules().select("antecedent","consequent","confidence","support").collectAsList(); //Double oi = (Double) Adata.get(0).get(2); //System.out.println(Adata.get(0).getList(0).toString()); ArrayList<String> row; ArrayList<ArrayList> results = new ArrayList<>(); for (int i = 0; i < Adata.size(); i++) { row = new ArrayList<>(); for (int j = 0; j < Adata.get(i).getList(0).size(); j++){ row.add(Adata.get(i).getList(0).get(j).toString()); } for (int k = 0; k < Adata.get(i).getList(1).size(); k++){ row.add(Adata.get(i).getList(1).get(k).toString()); } row.add(Adata.get(i).get(2).toString()); row.add(Adata.get(i).get(3).toString()); results.add(row); } System.out.println(results.toString()); // transform examines the input items against all the association rules and summarize the // consequents as prediction //model.transform(itemsDF).show(); // $example off$ spark.stop(); return new FindPatternResponse(results); } public FindRelationshipsResponse findRelationship(FindRelationshipsRequest request) throws InvalidRequestException { if (request == null) { throw new InvalidRequestException("FindRelationshipsRequest Object is null"); } if (request.getDataList() == null){ throw new InvalidRequestException("DataList is null"); } SparkSession sparkRelationships = SparkSession .builder() .appName("Relationships") .master("local") .getOrCreate(); List<Row> relationshipData = new ArrayList<>(); /*for (int i = 0; i < 100; i++) { //MOCK DATASET WITH 5 "features" ArrayList<String> attempt = new ArrayList<>(); for (int j = 0 ; j < 5 ; j++){ int unique = (int)(Math.random()*(9)+1); String adding = Integer.toString(unique); for (int k = 0; k < j; k ++) adding+= "i"; attempt.add(adding); } relationshipData.add(RowFactory.create(attempt)); }*/ ArrayList<String> reqData = request.getDataList(); for(int i=0; i < reqData.size(); i++){ relationshipData.add( RowFactory.create(Arrays.asList(reqData.get(i).split(" ")))); } StructType schema = new StructType(new StructField[]{ new StructField( "Tweets", new ArrayType(DataTypes.StringType, true), false, Metadata.empty()) }); Dataset<Row> itemsDF = sparkRelationships.createDataFrame(relationshipData, schema); itemsDF.show(); FPGrowthModel model = new FPGrowth() .setItemsCol("Tweets") .setMinSupport(0.15) .setMinConfidence(0.6) .fit(itemsDF); model.freqItemsets().show(); List<Row> Rdata = model.freqItemsets().collectAsList(); ArrayList<ArrayList> results = new ArrayList<>(); for (int i = 0; i < Rdata.size(); i++) { ArrayList<String> row = new ArrayList<>(); for (int j = 0; j < Rdata.get(i).getList(0).size(); j++){ row.add(Rdata.get(i).getList(0).get(j).toString()); } row.add(Rdata.get(i).get(1).toString()); results.add(row); } System.out.println(results.toString()); sparkRelationships.stop(); return new FindRelationshipsResponse(results); } public GetPredictionResponse getPredictions(GetPredictionRequest request) throws InvalidRequestException { if (request == null) { throw new InvalidRequestException("GetPredictionRequest Object is null"); } if (request.getDataList() == null){ throw new InvalidRequestException("DataList is null"); } SparkSession sparkPredictions = SparkSession .builder() .appName("Predictions") .master("local") .getOrCreate(); List<Row> PredictionsData = new ArrayList<>(); /*for (int i = 0; i < 100; i++) { //MOCK DATASET WITH 5 "features" ArrayList<String> attempt = new ArrayList<>(); for (int j = 0 ; j < 5 ; j++){ int unique = (int)(Math.random()*(9)+1); String adding = Integer.toString(unique); for (int k = 0; k < j; k ++) adding+= "i"; attempt.add(adding); } PredictionsData.add(RowFactory.create(attempt)); }*/ ArrayList<String> reqData = request.getDataList(); for(int i=0; i < reqData.size(); i++){ PredictionsData.add( RowFactory.create(Arrays.asList(reqData.get(i).split(" ")))); } StructType schema = new StructType(new StructField[]{ new StructField("Tweets", new ArrayType(DataTypes.StringType, true), false, Metadata.empty()) }); Dataset<Row> itemsDF = sparkPredictions.createDataFrame(PredictionsData, schema); itemsDF.show(); FPGrowthModel model = new FPGrowth() .setItemsCol("Tweets") .setMinSupport(0.15) .setMinConfidence(0.6) .fit(itemsDF); //MOCK DATA USED TO MAKE Prediction List<Row> testData = Arrays.asList( RowFactory.create(Arrays.asList("1 2i 3ii".split(" "))) ); Dataset<Row> tesRes = sparkPredictions.createDataFrame(testData,schema); Dataset<Row> Results = model.transform(itemsDF); //Results.show(); List<Row> Pdata = Results.collectAsList(); ArrayList<ArrayList> results = new ArrayList<>(); for (int i = 0; i < Pdata.size(); i++) { ArrayList<ArrayList> row = new ArrayList<>(); ArrayList<String> col1 = new ArrayList<>(); ArrayList<String> col2 = new ArrayList<>(); for (int j = 0; j < Pdata.get(i).getList(0).size(); j++){ col1.add(Pdata.get(i).getList(0).get(j).toString()); } for (int j = 0; j < Pdata.get(i).getList(1).size(); j++){ col1.add(Pdata.get(i).getList(1).get(j).toString()); } row.add(col1); row.add(col2); results.add(row); } System.out.println(results.toString()); sparkPredictions.stop(); return new GetPredictionResponse(results); } public FindSentimentResponse findSentiment(FindSentimentRequest request) throws InvalidRequestException { if (request == null) { throw new InvalidRequestException("FindSentimentRequest Object is null"); } if (request.getTextMessage() == null){ throw new InvalidRequestException("Text is null"); } String line = request.getTextMessage(); //Setup the Core NLP Properties properties = new Properties(); properties.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); StanfordCoreNLP stanfordCoreNLP = new StanfordCoreNLP(properties); int mainSentiment = 0; //apply NLP to each tweet AKA line if (line != null && !line.isEmpty()) { int longest = 0; Annotation annotation = stanfordCoreNLP.process(line); for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); String partText = sentence.toString(); if (partText.length() > longest) { mainSentiment = sentiment; longest = partText.length(); } } } TweetWithSentiment tweetWithSentiment = new TweetWithSentiment(line, toCss(mainSentiment)); return new FindSentimentResponse(tweetWithSentiment); } /******HELPER FUNCTIONS******/ private String toCss(int sentiment) { switch (sentiment) { case 0: return "Very_Negative"; case 1: return "Negative"; case 2: return "Neutral"; case 3: return "Positive"; case 4: return "Very_Positive"; default: return ""; } } private void removeSpaces(String line){ } }
true
55cb09252d9cc5d40a3d96b00fddd24df35f2344
Java
honeyflyfish/com.tencent.mm
/src/com/tencent/mm/protocal/b/acs.java
UTF-8
7,670
1.578125
2
[]
no_license
package com.tencent.mm.protocal.b; import java.util.LinkedList; public final class acs extends com.tencent.mm.ax.a { public String bFf; public int bFg; public String bFh; public String bFi; public String bFj; public int bFk; public String bFl; public int bFm; public int bFn; public String bFo; public String bFp; public String bFq; public String jDF; public String jDG; public String jNd; public ary jVS; public js jVT; public String jWK; public nc jWL; public String jwf; protected final int a(int paramInt, Object... paramVarArgs) { if (paramInt == 0) { paramVarArgs = (a.a.a.c.a)paramVarArgs[0]; if (jwf != null) { paramVarArgs.e(1, jwf); } if (jWK != null) { paramVarArgs.e(2, jWK); } if (bFf != null) { paramVarArgs.e(3, bFf); } paramVarArgs.cw(4, bFg); if (bFh != null) { paramVarArgs.e(5, bFh); } if (bFi != null) { paramVarArgs.e(6, bFi); } if (bFj != null) { paramVarArgs.e(7, bFj); } paramVarArgs.cw(8, bFk); if (bFl != null) { paramVarArgs.e(9, bFl); } if (jWL != null) { paramVarArgs.cx(10, jWL.iO()); jWL.a(paramVarArgs); } paramVarArgs.cw(11, bFm); paramVarArgs.cw(12, bFn); if (bFo != null) { paramVarArgs.e(13, bFo); } if (jVS != null) { paramVarArgs.cx(14, jVS.iO()); jVS.a(paramVarArgs); } if (bFp != null) { paramVarArgs.e(15, bFp); } if (bFq != null) { paramVarArgs.e(16, bFq); } if (jVT != null) { paramVarArgs.cx(17, jVT.iO()); jVT.a(paramVarArgs); } if (jDF != null) { paramVarArgs.e(20, jDF); } if (jDG != null) { paramVarArgs.e(21, jDG); } if (jNd != null) { paramVarArgs.e(22, jNd); } return 0; } if (paramInt == 1) { if (jwf == null) { break label1474; } } label1474: for (int i = a.a.a.b.b.a.f(1, jwf) + 0;; i = 0) { paramInt = i; if (jWK != null) { paramInt = i + a.a.a.b.b.a.f(2, jWK); } i = paramInt; if (bFf != null) { i = paramInt + a.a.a.b.b.a.f(3, bFf); } i += a.a.a.a.cu(4, bFg); paramInt = i; if (bFh != null) { paramInt = i + a.a.a.b.b.a.f(5, bFh); } i = paramInt; if (bFi != null) { i = paramInt + a.a.a.b.b.a.f(6, bFi); } paramInt = i; if (bFj != null) { paramInt = i + a.a.a.b.b.a.f(7, bFj); } i = paramInt + a.a.a.a.cu(8, bFk); paramInt = i; if (bFl != null) { paramInt = i + a.a.a.b.b.a.f(9, bFl); } i = paramInt; if (jWL != null) { i = paramInt + a.a.a.a.cv(10, jWL.iO()); } i = i + a.a.a.a.cu(11, bFm) + a.a.a.a.cu(12, bFn); paramInt = i; if (bFo != null) { paramInt = i + a.a.a.b.b.a.f(13, bFo); } i = paramInt; if (jVS != null) { i = paramInt + a.a.a.a.cv(14, jVS.iO()); } paramInt = i; if (bFp != null) { paramInt = i + a.a.a.b.b.a.f(15, bFp); } i = paramInt; if (bFq != null) { i = paramInt + a.a.a.b.b.a.f(16, bFq); } paramInt = i; if (jVT != null) { paramInt = i + a.a.a.a.cv(17, jVT.iO()); } i = paramInt; if (jDF != null) { i = paramInt + a.a.a.b.b.a.f(20, jDF); } paramInt = i; if (jDG != null) { paramInt = i + a.a.a.b.b.a.f(21, jDG); } i = paramInt; if (jNd != null) { i = paramInt + a.a.a.b.b.a.f(22, jNd); } return i; if (paramInt == 2) { paramVarArgs = new a.a.a.a.a((byte[])paramVarArgs[0], jrk); for (paramInt = com.tencent.mm.ax.a.a(paramVarArgs); paramInt > 0; paramInt = com.tencent.mm.ax.a.a(paramVarArgs)) { if (!super.a(paramVarArgs, this, paramInt)) { paramVarArgs.bve(); } } break; } if (paramInt == 3) { Object localObject1 = (a.a.a.a.a)paramVarArgs[0]; acs localacs = (acs)paramVarArgs[1]; paramInt = ((Integer)paramVarArgs[2]).intValue(); Object localObject2; boolean bool; switch (paramInt) { case 18: case 19: default: return -1; case 1: jwf = mMY.readString(); return 0; case 2: jWK = mMY.readString(); return 0; case 3: bFf = mMY.readString(); return 0; case 4: bFg = mMY.id(); return 0; case 5: bFh = mMY.readString(); return 0; case 6: bFi = mMY.readString(); return 0; case 7: bFj = mMY.readString(); return 0; case 8: bFk = mMY.id(); return 0; case 9: bFl = mMY.readString(); return 0; case 10: paramVarArgs = ((a.a.a.a.a)localObject1).vC(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject2 = (byte[])paramVarArgs.get(paramInt); localObject1 = new nc(); localObject2 = new a.a.a.a.a((byte[])localObject2, jrk); for (bool = true; bool; bool = ((nc)localObject1).a((a.a.a.a.a)localObject2, (com.tencent.mm.ax.a)localObject1, com.tencent.mm.ax.a.a((a.a.a.a.a)localObject2))) {} jWL = ((nc)localObject1); paramInt += 1; } case 11: bFm = mMY.id(); return 0; case 12: bFn = mMY.id(); return 0; case 13: bFo = mMY.readString(); return 0; case 14: paramVarArgs = ((a.a.a.a.a)localObject1).vC(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject2 = (byte[])paramVarArgs.get(paramInt); localObject1 = new ary(); localObject2 = new a.a.a.a.a((byte[])localObject2, jrk); for (bool = true; bool; bool = ((ary)localObject1).a((a.a.a.a.a)localObject2, (com.tencent.mm.ax.a)localObject1, com.tencent.mm.ax.a.a((a.a.a.a.a)localObject2))) {} jVS = ((ary)localObject1); paramInt += 1; } case 15: bFp = mMY.readString(); return 0; case 16: bFq = mMY.readString(); return 0; case 17: paramVarArgs = ((a.a.a.a.a)localObject1).vC(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject2 = (byte[])paramVarArgs.get(paramInt); localObject1 = new js(); localObject2 = new a.a.a.a.a((byte[])localObject2, jrk); for (bool = true; bool; bool = ((js)localObject1).a((a.a.a.a.a)localObject2, (com.tencent.mm.ax.a)localObject1, com.tencent.mm.ax.a.a((a.a.a.a.a)localObject2))) {} jVT = ((js)localObject1); paramInt += 1; } case 20: jDF = mMY.readString(); return 0; case 21: jDG = mMY.readString(); return 0; } jNd = mMY.readString(); return 0; } return -1; } } } /* Location: * Qualified Name: com.tencent.mm.protocal.b.acs * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
471302582ae4c6ee86d304e2ed9a4cde624e68ee
Java
fanxiaofei123/dragv4
/.svn/pristine/47/471302582ae4c6ee86d304e2ed9a4cde624e68ee.svn-base
UTF-8
56,478
1.695313
2
[]
no_license
package org.com.drag.web.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.poi.hssf.usermodel.*; import org.com.drag.common.page.PageBean; import org.com.drag.common.result.ResponseResult; import org.com.drag.common.util.*; import org.com.drag.model.*; import org.com.drag.service.*; import org.com.drag.service.impl.JobServiceImpl; import org.com.drag.service.oozie.api.IHdfsApi; import org.com.drag.service.oozie.api.IOozieApi; import org.com.drag.web.common.ModelUtils; import org.com.drag.web.common.WorkFlowXmlUtils; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.net.URLEncoder; import org.apache.hadoop.fs.FileSystem; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by cdyoue on 2016/11/21. */ @Controller @RequestMapping("drag/calculation") public class CalculationController { protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Autowired private CalculationHistoryService calculationHistoryService; @Autowired private WorkFlowService workFlowService; @Autowired private WorkSpaceService workSpaceService; @Autowired private JobService jobService; @Autowired private IHdfsApi iHdfsApi; @Autowired private IOozieApi iOozieApi; @Autowired private DatabaseConnectService databaseConnectService; @Autowired private DatabaseTypeService databaseTypeService; @Autowired private ModelTrainedService modelTrainedService; @Autowired private JobServiceImpl jobServiceImpl; @Autowired ServletContext servletContext; /** * 工作流的运行 * @param session * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "run", method = RequestMethod.POST) @ResponseBody public ResponseResult runCalculation(HttpServletRequest request,HttpSession session, String modelStr, String connectStr,String blocksStr,String notesStr, final Integer flowId,String flowName,String workSpaceName) { ResponseResult responseResult = new ResponseResult(HttpStatus.OK); User user = (User)session.getAttribute(Constants.USER_KEY); Integer userId=user.getId(); //保存工作流 WorkFlow workFlow = new WorkFlow(); workFlow.setId(flowId); workFlow.setUpdatTime(new Date()); JSONObject contextJson = new JSONObject(); contextJson.put("models", modelStr); contextJson.put("connects", connectStr); contextJson.put("blocks", blocksStr); contextJson.put("notes", notesStr); workFlow.setContext(contextJson.toString()); workFlowService.updateByPrimaryKeySelective(workFlow); WorkFlow workFlows = workFlowService.selectByPrimaryKey(flowId); WorkSpace workSpace = workSpaceService.selectByPrimaryKey(workFlows.getWorkspid()); JSONArray jsonArr = JSONArray.parseArray(modelStr); List<Model> models =JSON.parseArray(jsonArr.toJSONString(),Model.class); //生成配置xml文件,方法都在这里面写 Properties xmlProperties=getPropertiesXML(jsonArr, models, connectStr, user, flowId, workSpaceName, flowName, workSpace,this.servletContext,iHdfsApi,databaseConnectService,databaseTypeService,modelTrainedService); if(xmlProperties==null){ return new ResponseResult(HttpStatus.BAD_REQUEST, "配置信息错误,运行失败!"); } //加锁 ConcurrentHashMap<Integer,UserRunningInfo> mapList=new ConcurrentHashMap<Integer,UserRunningInfo>(); Integer total=0; String jobId=""; ReentrantLock queueLock = jobServiceImpl.getReentrantLock(); queueLock.lock(); //判断用户的任务量 try { mapList=jobServiceImpl.getMap(); Iterator<Integer> keys=mapList.keySet().iterator(); while (keys.hasNext()) { Integer m = mapList.get(keys.next()).getNum(); total += m; } if(total<= Integer.valueOf(MailAuthorSetting.SUBMIT_TASK_TOTAL_LIMIT)){ //判断个人用户的任务量 Boolean containUserId=mapList.containsKey(user.getId()); if(containUserId){ Integer number=mapList.get(user.getId()).getNum(); if(number >=Integer.valueOf(MailAuthorSetting.USER_TASK_NUM_LIMIT)){ return new ResponseResult(HttpStatus.BAD_REQUEST, "超过用户的运行个数!"); }else { UserRunningInfo userRI=mapList.get(user.getId()); HashMap workRunMap=userRI.getWorkRunMap(); if(workRunMap.containsKey(flowId)){ return new ResponseResult(HttpStatus.BAD_REQUEST, "重复提交了相同未完成任务!"); }else { //运行任务 jobId = jobService.run(xmlProperties,user.getId(),flowId,workFlows.getName(),null,models.size(),session,0,null,null); if(jobId!=null){ UserRunningInfo userRunningInfo = userRI; Integer num = userRunningInfo.getNum() + 1; userRunningInfo.setNum(num); userRunningInfo.getWorkRunMap().put(flowId,jobId); }else { return new ResponseResult(HttpStatus.BAD_REQUEST, "运行失败!"); } } } }else { //用户第一次运行的数量初始化 //运行任务 jobId = jobService.run(xmlProperties,user.getId(),flowId,workFlows.getName(),null,models.size(),session,0,null,null); if(jobId!=null) { UserRunningInfo userRInfo= new UserRunningInfo(); userRInfo.setNum(1); HashMap map=new HashMap(); map.put(flowId,jobId); userRInfo.setWorkRunMap(map); //userRInfo.getWorkRunMap().put(flowId,"NONE"); mapList.put(userId,userRInfo); }else { return new ResponseResult(HttpStatus.BAD_REQUEST, "运行失败!"); } } }else{ return new ResponseResult(HttpStatus.BAD_REQUEST, "超过最大可同时运行任务量了"); } }catch (Exception e){ LOGGER.error("加锁判断用户提交的任务量是否满足条件", e); }finally { queueLock.unlock(); } //运行任务 // String jobId = jobService.run(xmlProperties,user.getId(),flowId,workFlows.getName(),null,models.size(),session,0,null,null); session.setAttribute("jobId",jobId); //查询当前工作空间的历史记录 CalculationHistory ch = new CalculationHistory(); ch.setUserid(user.getId()); ch.setFlowId(flowId); List<CalculationHistory> results = calculationHistoryService.selectBySelectiveKey(ch); Map map = new HashMap(); map.put("historys", results); map.put("jobId", jobId); responseResult.setObj(map); return responseResult; } public Properties getPropertiesXML(JSONArray jsonArr,List<Model> models,String connectStr,User user,Integer flowId,String workSpaceName,String flowName,WorkSpace workSpace,ServletContext servletContext,IHdfsApi iHdfsApi,DatabaseConnectService databaseConnectService,DatabaseTypeService databaseTypeService,ModelTrainedService modelTrainedService){ Iterator<Object> arrIterator = jsonArr.iterator(); String filterOptValue = ""; String logicRules = ""; String filterBlockId = ""; while (arrIterator.hasNext()){ Object object = arrIterator.next(); com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)object; if(Integer.parseInt(jsonObject.get("id").toString()) == 125){ filterBlockId = jsonObject.get("BlockId").toString(); JSONArray jsonArr1 = (JSONArray)jsonObject.get("data"); Iterator<Object> iterator = jsonArr1.iterator(); while (iterator.hasNext()){ JSONArray jsonArray = (JSONArray)iterator.next(); Iterator<Object> iterator1 = jsonArray.iterator(); String optSingle = ""; String filterFun = ""; while(iterator1.hasNext()){ com.alibaba.fastjson.JSONObject dataObject = (com.alibaba.fastjson.JSONObject)iterator1.next(); if(dataObject.get("configName").toString().indexOf("filterFun") != -1){ filterFun = dataObject.get("configSelectVal").toString(); break; } } Iterator<Object> iterator2 = jsonArray.iterator(); while (iterator2.hasNext()){ com.alibaba.fastjson.JSONObject dataObject = (com.alibaba.fastjson.JSONObject)iterator2.next(); if(!"<=>".equals(filterFun) && !"∉".equals(filterFun)){ if(dataObject.get("configName").toString().indexOf("labelCol") != -1){ optSingle += "labelCol|" + dataObject.get("configVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("filterFun") != -1){ optSingle += "filterFun|" + dataObject.get("configSelectVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("filterType") != -1){ optSingle += "filterType|" + dataObject.get("configSelectVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("logicRule") != -1){ logicRules += dataObject.get("configVal").toString() + ","; } if(dataObject.get("configName").toString().contains("UpperThresholdVal")){ if(dataObject.get("configVal") == null || "".equals(dataObject.get("configVal").toString().trim())){ optSingle += "UpperThresholdVal|" + "null" + ","; }else{ optSingle += "UpperThresholdVal|" + dataObject.get("configVal").toString() + ","; } } if(dataObject.get("configName").toString().contains("LowerThresholdVal")){ if(dataObject.get("configVal") == null || "".equals(dataObject.get("configVal").toString().trim())){ optSingle += "LowerThresholdVal|" + "null" + ";"; }else{ optSingle += "LowerThresholdVal|" + dataObject.get("configVal").toString() + ";"; } } if(dataObject.get("configName").toString().contains("threshold")){ if(dataObject.get("configVal") == null || "".equals(dataObject.get("configVal").toString().trim())){ optSingle += "threshold|" + "null" + ","; }else{ optSingle += "threshold|" + dataObject.get("configVal").toString() + ","; } } }else{ if(dataObject.get("configName").toString().indexOf("labelCol") != -1){ optSingle += "labelCol|" + dataObject.get("configVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("filterFun") != -1){ optSingle += "filterFun|" + dataObject.get("configSelectVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("LowerThreshold") != -1 && !dataObject.get("configName").toString().contains("LowerThresholdVal")){ optSingle += "LowerThreshold|" + dataObject.get("configSelectVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("UpperThreshold") != -1 && !dataObject.get("configName").toString().contains("UpperThresholdVal")){ optSingle += "UpperThreshold|" + dataObject.get("configSelectVal").toString() + ","; } if(dataObject.get("configName").toString().indexOf("logicRule") != -1){ logicRules += dataObject.get("configVal").toString() + ","; } if(dataObject.get("configName").toString().contains("UpperThresholdVal")){ if(dataObject.get("configVal") == null || "".equals(dataObject.get("configVal").toString().trim())){ optSingle += "UpperThresholdVal|" + "null" + ","; }else{ optSingle += "UpperThresholdVal|" + dataObject.get("configVal").toString() + ","; } } if(dataObject.get("configName").toString().contains("LowerThresholdVal")){ if(dataObject.get("configVal") == null || "".equals(dataObject.get("configVal").toString().trim())){ optSingle += "LowerThresholdVal|" + "null" + ";"; }else{ optSingle += "LowerThresholdVal|" + dataObject.get("configVal").toString() + ";"; } } } } filterOptValue += optSingle; } jsonArr.remove(object); break; } } if(StringUtils.hasText(filterOptValue)){ filterOptValue = filterOptValue.substring(0,filterOptValue.length()-1); } if(StringUtils.hasText(logicRules)){ logicRules = logicRules.substring(0,logicRules.length()-1); } if(StringUtils.hasText(filterOptValue) && StringUtils.hasText(logicRules)){ String filterJsonStr = "{\"BlockName\":\"条件过滤(V4)\",\"BlockId\":\"" + filterBlockId + "\",\"data\":[{\"configName\":\"option\",\"configVal\":\"" + filterOptValue + "\"},{\"configName\":\"logicRule\",\"configVal\":\"" + logicRules + "\"}],\"id\":\"125\"}"; Object filterObject = JSONArray.parse(filterJsonStr); jsonArr.add(filterObject); } List<Connect> connects = JSON.parseArray(connectStr, Connect.class); //循环connects,设置connectType。 for(Connect connect : connects){ String sourceId = connect.getSourceId(); int modelId = 0; for(Model model : models){ if(sourceId.equals(model.getBlockId())){ modelId = model.getId(); } } if(Setting.getDoubleOutputDataModelIds().contains(modelId + "")){ if(Double.parseDouble(connect.getSourceAnchor().get(0)) < Double.parseDouble(connect.getTargetAnchor().get(0))){ connect.setConnectType("Square"); }else { connect.setConnectType("Circle"); } } if(Setting.getPythonAndRIds().contains(modelId + "")){ if(Double.parseDouble(connect.getSourceAnchor().get(0)) < Double.parseDouble(connect.getTargetAnchor().get(0))){ connect.setConnectType("Square"); }else { connect.setConnectType("Circle"); } } if(Setting.getDoubleOutputDataIds().contains(modelId + "")){ if(Double.parseDouble(connect.getSourceAnchor().get(0)) == 0.5){ connect.setConnectSourcePosition("Left"); }else{ connect.setConnectSourcePosition("Right"); } } } for(Connect connect : connects){ String targetId = connect.getTargetId(); int modelId = 0; for(Model model : models){ if(targetId.equals(model.getBlockId())){ modelId = model.getId(); } } if(Setting.getOrdinaryApplyV4Ids().contains(modelId + "")){ if(Double.parseDouble(connect.getTargetAnchor().get(0)) == 0.5){ connect.setConnectTargetPosition("Left"); }else{ connect.setConnectTargetPosition("Right"); } } } //用一个flag记录是否有python或者r算子。 boolean containsPythonR = false; boolean containsSinglePythonR = false; for(Model model : models){ //判断是否是自定义算子Py R if(model.getId()==83 || model.getId()==84){ containsPythonR = true; String modelId =model.getBlockId(); List<ModelAttribute> data1 = model.getData(); Iterator<ModelAttribute> iterator = data1.iterator(); for(ModelAttribute modelAttribute:data1){ if(modelAttribute.getMattribute().equals("textarea")){ String context=modelAttribute.getMvalue(); System.out.println(context); String uuid = UUID.randomUUID().toString(); //自定义算子路径 String customPyPath=savePyFile(flowId,modelId,context,model.getId(),uuid,servletContext); String scriptName; if(model.getId() == 83){ scriptName = flowId.toString()+"_"+modelId.substring(10) + "_" + uuid + ".py"; }else{ scriptName = flowId.toString()+"_"+modelId.substring(10) + "_" + uuid + ".r"; } String commonPythonRPath = MailAuthorSetting.PYTHON_R_DIR_PATH + scriptName; String userName = user.getLoginname(); iHdfsApi.uploadWorkFlowFile(customPyPath, commonPythonRPath, userName); FileSystem fs = iHdfsApi.getFileSystem("hdfs"); try { fs.setPermission(new Path(commonPythonRPath),new FsPermission("777")); } catch (IOException e) { e.printStackTrace(); } ModelAttribute scriptPathAttr = new ModelAttribute(); scriptPathAttr.setMattribute("scriptPath"); scriptPathAttr.setMvalue(commonPythonRPath); model.getData().add(scriptPathAttr); ModelAttribute scriptNameAttr = new ModelAttribute(); scriptNameAttr.setMattribute("scriptName"); scriptNameAttr.setMvalue(scriptName); model.getData().add(scriptNameAttr); ModelAttribute shellScriptName = new ModelAttribute(); shellScriptName.setMattribute("shellScriptName"); shellScriptName.setMvalue(PythonRUtils.getPythonRScriptName(model.getId()) + ".sh"); model.getData().add(shellScriptName); break; } } }else if(Setting.getPythonAndRSingleIds().contains(model.getId() + "")){ containsSinglePythonR = true; ModelAttribute shellScriptName = new ModelAttribute(); shellScriptName.setMattribute("shellScriptName"); shellScriptName.setMvalue(PythonRUtils.getPythonRScriptName(model.getId()) + ".sh"); model.getData().add(shellScriptName); } List<ModelAttribute> data = model.getData(); for(ModelAttribute modelAttribute : data){ if(modelAttribute.getConfigSelectVal() != null){ modelAttribute.setMvalue(modelAttribute.getConfigSelectVal()); } } //py文本->写文件->路径记录下来-> if(model.getId() == 55){ Integer trainedModelId = model.getTrainedModelId(); String inputPath = modelTrainedService.getInputPathById(trainedModelId); ModelAttribute modelAttribute = new ModelAttribute(); modelAttribute.setMattribute("inputPath"); modelAttribute.setMvalue(inputPath); model.getData().add(modelAttribute); String dataModelName=modelTrainedService.getDataModelNameById(trainedModelId); ModelAttribute modelAttribute2 = new ModelAttribute(); modelAttribute2.setMattribute("dataModelName"); modelAttribute2.setMvalue(dataModelName); model.getData().add(modelAttribute2); } //格式化model model=ModelUtils.updateModel(model); } String userName = user.getLoginname(); //简要检查数据格式 if(connects.size()==0 || models.size()==0){ return null; } //生成xml和properties ModelUtils modelUtils = new ModelUtils(); ModelXmlInfo modelXmlInfo; // boolean oldVersion = false; String version = Constants.OOZIE_GENXML_V4; Properties xmlProperties = null; // Properties prop = new Properties(); // Map<String,String> oozieVersionMap = new HashMap<>(); // try { // InputStream in = new BufferedInputStream (new FileInputStream("oozieVersion.properties")); // prop.load(in); // Iterator<String> it=prop.stringPropertyNames().iterator(); // while(it.hasNext()){ // String key=it.next(); // oozieVersionMap.put(key,prop.getProperty(key)); // } // for(String key : oozieVersionMap.keySet()){ // if(key.equals(Constants.OOZIE_GEN_VERSION)){ // version = oozieVersionMap.get(key); // } // } // in.close(); // } catch (Exception e) { // LOGGER.info(e.getMessage()); // e.printStackTrace(); // } if(version.equals(Constants.OOZIE_GENXML_V3)){ modelXmlInfo = modelUtils.getSortingFormatModels(models, connects,new StringBuffer(workSpaceName).append("/").append(flowName).toString(),userName,user.getId(),databaseConnectService,databaseTypeService); String pathPrefix = servletContext.getRealPath("/")+"upload" + System.getProperty("file.separator"); String tmpoFolderName = new StringBuffer(Constants.WORK_FLOW).append(UUID.randomUUID().toString()).toString(); String folderPath = new StringBuffer(pathPrefix).append(tmpoFolderName).toString(); File file = null; boolean uploadBooler; try { file = new File(folderPath); boolean mkdir = file.mkdir(); if(!mkdir){ return null; } String path = new StringBuffer(folderPath).append("/").append(Constants.WORK_FLOW).append(".xml").toString(); xmlProperties = WorkFlowXmlUtils.buildXml(modelXmlInfo, path, new StringBuffer(MailAuthorSetting.HDFS_PATH_FEIX).append(userName).append("/workspaces/").append(workSpace.getName()).append("/").append(flowName).toString(),flowName, userName); WorkFlowXmlUtils.updateXml(path, path); //上传xml到hdfs // HdfsFileUtil hdfsFileUtil = new HdfsFileUtil(); uploadBooler = iHdfsApi.uploadWorkFlowFile(path, new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append("workflow.xml").toString(), userName); } finally { if(file != null){ removedir(file); } } if(!uploadBooler){ return null; } }else if(version.equals(Constants.OOZIE_GENXML_V4)){ WorkflowNode startWorkflowNode = modelUtils.getStartNode(models, connects,new StringBuffer(workSpaceName).append("/") .append(flowName).toString(),userName,user.getId(),databaseConnectService,databaseTypeService); //把中间输出等属性添加上去 Map<String, WorkflowNode> nodeMap = modelUtils.getNodeMap(new HashMap<String, WorkflowNode>(), startWorkflowNode); Map<String, Integer> usedDoubleOutputPathCountMapOutputPath = ModelUtils.getUsedDoubleOutputPathCountMap(nodeMap); Map<String,Object> formatAttrMapOutputPath = new HashMap<>(); List<String> formatedIdsOutputPath = new ArrayList<>(); formatAttrMapOutputPath.put("usedDoubleOutputPathCountMap",usedDoubleOutputPathCountMapOutputPath); formatAttrMapOutputPath.put("formatedIds",formatedIdsOutputPath); ModelUtils.formatWorkflowNodeAttributeOutputPath(formatAttrMapOutputPath,nodeMap,startWorkflowNode,userName,user.getId(),flowId.toString(),databaseConnectService,databaseTypeService); Map<String, Integer> usedDoubleOutputPathCountMapInputPath = ModelUtils.getUsedDoubleOutputPathCountMap(nodeMap); Map<String,Object> formatAttrMapInputPath = new HashMap<>(); List<String> formatedIdsInputPath = new ArrayList<>(); formatAttrMapInputPath.put("usedDoubleOutputPathCountMap",usedDoubleOutputPathCountMapInputPath); formatAttrMapInputPath.put("formatedIds",formatedIdsInputPath); ModelUtils.formatWorkflowNodeAttributeInputPath(formatAttrMapInputPath,nodeMap,startWorkflowNode,userName,user.getId(),flowId.toString(),databaseConnectService,databaseTypeService); //给每个算子模型名称后面加上function名称 ModelUtils.addFuctionToStatModel(startWorkflowNode,new ArrayList<WorkflowNode>()); String pathPrefix =servletContext.getRealPath("/")+"upload" + System.getProperty("file.separator"); String tmpoFolderName = new StringBuffer(Constants.WORK_FLOW).append(UUID.randomUUID().toString()).toString(); String folderPath = new StringBuffer(pathPrefix).append(tmpoFolderName).toString(); File file = null; boolean uploadBooler = false; boolean uploadShell = false; boolean uploadSingleShell = false; try { file = new File(folderPath); boolean mkdir = file.mkdir(); if(!mkdir){ return null; } String path = new StringBuffer(folderPath).append("/").append(Constants.WORK_FLOW).append(".xml").toString(); xmlProperties = WorkFlowXmlUtils.builNewXml(startWorkflowNode, path, new StringBuffer(MailAuthorSetting.HDFS_PATH_FEIX).append(userName).append("/workspaces/").append(workSpace.getName()).append("/").append(flowName).toString().replace(" ",""),flowName, userName); WorkFlowXmlUtils.updateXml(path, path); //上传xml到hdfs // HdfsFileUtil hdfsFileUtil = new HdfsFileUtil(); // String xml = new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append("workflow.xml").toString(); String workflowPath = new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append("workflow.xml").toString().replace(" ",""); uploadBooler = iHdfsApi.uploadWorkFlowFile(path, workflowPath, userName); FileSystem fs = iHdfsApi.getFileSystem(userName); if(containsPythonR){ String shellPath = servletContext.getRealPath("/") + "shell" + System.getProperty("file.separator") + Constants.PYTHON_OR_R_SHELL_NAME; String uploadPath = new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append(Constants.PYTHON_OR_R_SHELL_NAME).toString().replace(" ",""); try { iHdfsApi.deleteFileOrDir(uploadPath,userName,false); boolean exists = fs.exists(new Path(uploadPath)); if(!exists){ uploadShell = iHdfsApi.uploadFile(shellPath,uploadPath,userName); } } catch (Exception e) { e.printStackTrace(); } } if(containsSinglePythonR){ for(Model model : models){ if(Setting.getPythonAndRSingleIds().contains(model.getId() + "")){ String uploadPath = new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append(PythonRUtils.getPythonRScriptName(model.getId())).append(".sh").toString().replace(" ",""); String shellPath = servletContext.getRealPath("/") + "shell" + System.getProperty("file.separator") + PythonRUtils.getPythonRScriptName(model.getId()) + ".sh"; try { iHdfsApi.deleteFileOrDir(uploadPath,userName,false); boolean exists = fs.exists(new Path(uploadPath)); if(!exists){ uploadSingleShell = iHdfsApi.uploadFile(shellPath,new StringBuffer(Constants.WORKSPACES_SUFFIX).append("/").append(workSpace.getName()).append("/").append(flowName).append("/").append(PythonRUtils.getPythonRScriptName(model.getId())).append(".sh").toString().replace(" ",""),userName); } } catch (Exception e) { e.printStackTrace(); } } } } } catch (Exception e) { e.printStackTrace(); } finally { if(file != null){ removedir(file); } } if(containsPythonR){ if(!uploadShell){ return null; } } if(!uploadBooler){ return null; } if(containsSinglePythonR){ if(!uploadSingleShell){ return null; } } } return xmlProperties; } public String savePyFile(Integer flowId,String BlockId,String context,Integer ModelId,String uuid,ServletContext servletContext){ //python头部文件地址 String pythonHead=servletContext.getRealPath("/")+"templateFile"+ System.getProperty("file.separator")+"python_head.py"; String pythonEnd=servletContext.getRealPath("/")+"templateFile"+ System.getProperty("file.separator")+"python_end.py"; String rHead=servletContext.getRealPath("/")+"templateFile"+ System.getProperty("file.separator")+"r_head.r"; String rEnd=servletContext.getRealPath("/")+"templateFile"+ System.getProperty("file.separator")+"r_end.r"; String pathPrefix = servletContext.getRealPath("/")+"pythonR" + System.getProperty("file.separator"); String fileName=flowId.toString()+"_"+BlockId.substring(10); String customPyPath =""; if(ModelId==83){ //拼接python文件 context=(readFileToString(pythonHead)+"\n"+context+"\n"+readFileToString(pythonEnd)).replaceAll("\t"," "); customPyPath = new StringBuffer(pathPrefix).append(fileName).append("_").append(uuid).append(".py").toString(); }else { //拼接r文件 context=readFileToString(rHead)+context+readFileToString(rEnd); customPyPath = new StringBuffer(pathPrefix).append(fileName).append("_").append(uuid).append(".r").toString(); } try { File f=new File(customPyPath); if(f.exists()){ System.out.println("文件存在"); }else { System.out.println("文件不存在"); f.createNewFile(); } PrintWriter w = new PrintWriter(new OutputStreamWriter( new FileOutputStream(f), "UTF-8")); w.write(context); System.out.println("input"); w.close(); }catch (Exception e){ e.printStackTrace(); } return customPyPath; } public String readFileToString(String filePath){ File f=new File(filePath); BufferedReader bfr=null; StringBuffer sb=new StringBuffer(); try { bfr = new BufferedReader(new FileReader(f)); String line = null; while ((line = bfr.readLine()) != null) { sb.append(line+System.getProperty("line.separator")); } return sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (bfr != null) { try { bfr.close(); } catch (IOException e) { e.printStackTrace(); } } } return ""; } public void removedir(File file) { File[] files=file.listFiles(); for(File f:files) { if(f.isDirectory())//递归调用 { removedir(f); } else { f.delete(); } } //一层目录下的内容都删除以后,删除掉这个文件夹 file.delete(); } @RequestMapping(value = "pause",method = RequestMethod.POST) @ResponseBody public ResponseResult calculationPause(String jobId,Integer workFlowId){ // OozieClientServiceImpl oc = new OozieClientServiceImpl(MailAuthorSetting.HADOOP_OOZIECLIENT_PATH); boolean b = iOozieApi.oozieWorkflowSuspend(jobId,MailAuthorSetting.HADOOP_OOZIECLIENT_PATH); if(b){ WorkFlow workFlow = new WorkFlow(); workFlow.setId(workFlowId); workFlow.setJobstatus(3); workFlowService.updateByPrimaryKeySelective(workFlow); } return b ? new ResponseResult(HttpStatus.OK):new ResponseResult(HttpStatus.FORBIDDEN); } @RequestMapping(value = "ifRun",method = RequestMethod.GET) @ResponseBody public Boolean ifRun(){ CalculationHistory calculationHistory = new CalculationHistory(); calculationHistory.setStatus(1); List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveKey(calculationHistory); return calculationHistories.size() == 0 ? false : true; } /** * 分页查询用户的运行记录 * @return */ @RequestMapping(value = "history",method = RequestMethod.POST) @ResponseBody public PageBean selectHistory(Integer page ,HttpSession session){ User user = (User) session.getAttribute(Constants.USER_KEY); CalculationHistory calculationHistory = new CalculationHistory(); calculationHistory.setUserid(user.getId()); PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveKey(calculationHistory); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); ws.setUserNmae(user.getLoginname()); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 查询后端所有用户的日志记录 * @param page * @param session * @return */ @RequestMapping(value = "historyAll",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryAll(Integer page ,HttpSession session){ PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveAll(); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 查询前段所有用户日志 * @param page * @param session * @return */ @RequestMapping(value = "historyFAll",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryFAll(Integer page ,HttpSession session){ PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveF(); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 查询用户后台日志 * @param page * @param session * @return */ @RequestMapping(value = "historyHAll",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryHAll(Integer page ,HttpSession session){ User user = (User) session.getAttribute(Constants.USER_KEY); CalculationHistory calculationHistory = new CalculationHistory(); calculationHistory.setUserid(user.getId()); PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelective(calculationHistory); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 通过时间段查询后台日志记录 * @param page * @param session * @return */ @RequestMapping(value = "historyTime",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryTime(Integer page ,HttpSession session,CalculationHistory calculationHistory){ if(null != calculationHistory ){ if(null != calculationHistory.getStartTime()){ calculationHistory.setStartTime(calculationHistory.getStartTime().toString().trim()); } if(null != calculationHistory.getEndTime()){ calculationHistory.setEndTime(calculationHistory.getEndTime().toString().trim()); } } PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveTime(calculationHistory); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal((int)pageInfos.getTotal()); pageBean.setTotalPage(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /* * * 通过时间段查询前台日志记录 * @param page * @param session * @return*/ @RequestMapping(value = "historyTimeF",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryTimeF(Integer page ,HttpSession session,CalculationHistory calculationHistory){ if(null != calculationHistory ){ if(null != calculationHistory.getStartTime()){ calculationHistory.setStartTime(calculationHistory.getStartTime().toString().trim()); } if(null != calculationHistory.getEndTime()){ calculationHistory.setEndTime(calculationHistory.getEndTime().toString().trim()); } } PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveFTime(calculationHistory); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 通过时间段查询用户日志记录 * @param page * @param session * @return*/ @RequestMapping(value = "historyHTime",method = RequestMethod.POST) @ResponseBody public PageBean selectHistoryHTime(Integer page ,HttpSession session,CalculationHistory calculationHistory){ if(null != calculationHistory ){ if(null != calculationHistory.getStartTime()){ calculationHistory.setStartTime(calculationHistory.getStartTime().toString().trim()); } if(null != calculationHistory.getEndTime()){ calculationHistory.setEndTime(calculationHistory.getEndTime().toString().trim()); } } User user = (User) session.getAttribute(Constants.USER_KEY); calculationHistory.setUserid(user.getId()); PageBean pageBean = new PageBean(); if(page == null || page == 0){ page = 1; } PageHelper.startPage(page,10); // 核心分页代码 测试 List<CalculationHistory> calculationHistories = calculationHistoryService.selectBySelectiveHTime(calculationHistory); //设置返回的总记录数 PageInfo<CalculationHistory> pageInfos=new PageInfo<CalculationHistory>(calculationHistories); if(page == 1){ pageBean.setPrevious(page); }else{ pageBean.setPrevious(page-1); } if(page < pageInfos.getPages()){ pageBean.setNext(page+1); }else{ pageBean.setNext(page); } pageBean.setTotal(pageInfos.getPages()); pageBean.setCurPage(page); if(calculationHistories != null && calculationHistories.size()>0){ for(CalculationHistory ws :calculationHistories){ if(ws.getStatus() == 1){ ws.setStatusName("运行中"); }else if(ws.getStatus() == 2){ ws.setStatusName("运行成功"); }else{ ws.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ws.setCreateTimes(dateformat.format(ws.getCreateTime())); } } pageBean.setRows(calculationHistories); return pageBean; } /** * 批量导出 * @param request * @param resp * @param cal * @throws IOException */ @ResponseBody @RequestMapping(value="exportExcelAll") public void exportExcelAll(HttpServletRequest request, HttpServletResponse resp,CalculationHistory cal) throws IOException { try { if (null == request || null == resp) { return; } if(null != cal ){ if(null != cal.getStartTime()){ if(cal.getStartTime().equals("")){ cal.setStartTime(null); }else{ cal.setStartTime(cal.getStartTime().toString().trim()); } } if(null != cal.getEndTime()){ if(cal.getEndTime().equals("")){ cal.setEndTime(null); }else{ cal.setEndTime(cal.getEndTime().toString().trim()); } } } List<CalculationHistory> listContent = calculationHistoryService.selectBySelectiveTime(cal); //生成Excel文件 exportExcel(request, resp, listContent); } catch (Exception e1) { LOGGER.info("=====导出excel异常===="); } } /** * 导出指定的 * @param request * @param resp * @param cal * @throws IOException */ @ResponseBody @RequestMapping(value="exportExcel") public void exportExcels(HttpServletRequest request, HttpServletResponse resp,CalculationHistory cal) throws IOException { try { if (null == request || null == resp) { return; } List<CalculationHistory> listContent = calculationHistoryService.selectBySelectiveKey(cal); //生成Excel文件 exportExcel(request, resp, listContent); } catch (Exception e1) { LOGGER.info("=====导出excel异常===="); } } /** * excel导出交易记录 * @param request * @param resp * @throws UnsupportedEncodingException */ public void exportExcel(HttpServletRequest request,HttpServletResponse resp,List<CalculationHistory> listContent) throws UnsupportedEncodingException { HSSFWorkbook wb = new HSSFWorkbook(); request.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/x-download"); String fileName = "日志记录.xls"; fileName = URLEncoder.encode(fileName, "UTF-8"); resp.addHeader("Content-Disposition", "attachment;filename=" + fileName); HSSFSheet sheet = wb.createSheet("日志记录"); sheet.setDefaultRowHeight((short) (2 * 256)); sheet.setColumnWidth(0, 50 * 160); HSSFFont font = wb.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 16); HSSFRow row = sheet.createRow((int) 0); sheet.createRow((int) 1); sheet.createRow((int) 2); sheet.createRow((int) 3); sheet.createRow((int) 4); sheet.createRow((int) 5); HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell cell = row.createCell(0); cell.setCellValue("执行者 "); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("工作流名称 "); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellStyle(style); cell.setCellValue("结果状态"); cell = row.createCell(3); cell.setCellStyle(style); cell.setCellValue("时间"); cell = row.createCell(4); cell.setCellStyle(style); cell.setCellValue("原因"); cell = row.createCell(5); List<CalculationHistory> vUserOrder = listContent; for (int i = 0; i < vUserOrder.size(); i++) { HSSFRow row1 = sheet.createRow((int) i + 1); CalculationHistory vuserOrder = vUserOrder.get(i); /*row1.createCell(0).setCellValue(i + 1);*/ if(vuserOrder.getStatus() == 1){ vuserOrder.setStatusName("运行中"); }else if(vuserOrder.getStatus() == 2){ vuserOrder.setStatusName("运行成功"); }else{ vuserOrder.setStatusName("运行失败"); } SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); vuserOrder.setCreateTimes(dateformat.format(vuserOrder.getCreateTime())); row1.createCell(0).setCellValue(vuserOrder.getEmail());//执行者 row1.createCell(1).setCellValue(vuserOrder.getWay());//工作流名称 row1.createCell(2).setCellValue(vuserOrder.getStatusName());//结果 row1.createCell(3).setCellValue(vuserOrder.getCreateTimes());//时间 row1.createCell(4).setCellValue(vuserOrder.getResason());//原因 } try { OutputStream out = resp.getOutputStream(); wb.write(out); out.close(); } catch (Exception e1) { LOGGER.info("=====导出excel异常===="); } } }
true
d3eb91c8c8e230c6beceaed052c94d6248ac3b44
Java
JarikDev/JL253optionalItem
/src/com/Main2.java
UTF-8
432
3.015625
3
[]
no_license
package com; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main2 { public static void main(String[] args) { Pattern p3 = Pattern.compile("Feb(ruary)? 23(rd)?"); //?? Matcher m3 =p3.matcher("February 23rd, February 23, Feb 23rd, Feb 23"); while (m3.find()){ System.out.println(m3.start()+" "+m3.group()+" "); } System.out.println(""); } }
true
3878ce018316da1ca6a795399175c4c3a9360951
Java
alexteixeira4379/science-back-end-movida
/src/br/com/project/beans/Usuario.java
UTF-8
4,744
2.65625
3
[]
no_license
package br.com.project.beans; import java.util.ArrayList; import java.util.List; /** * The type Usuario. */ public class Usuario { /** * The Id. */ public int id; /** * The Email. */ public String email; /** * The Senha. */ public String senha; /** * The Nome completo. */ public String nome_completo; /** * The Telefone. */ public String telefone; /** * The Celular. */ public String celular; /** * The Enderecos. */ public List<Endereco> enderecos; /** * Instantiates a new Usuario. */ public Usuario() { this.setTudo( 0, "", "","","","", new ArrayList<Endereco>()); } /** * Instantiates a new Usuario. * * @param id the id * @param email the email * @param senha the senha * @param nome_completo the nome completo * @param telefone the telefone * @param celular the celular * @param enderecos the enderecos */ public Usuario(int id, String email, String senha, String nome_completo, String telefone, String celular, List<Endereco> enderecos) { this.setTudo( id, email, senha,nome_completo,telefone,celular,enderecos ); } /** * Gets id. * * @return the id */ public int getId() { return id; } /** * Sets id. * * @param id the id */ public void setId(int id) { this.id = id; } /** * Gets email. * * @return the email */ public String getEmail() { return email; } /** * Sets email. * * @param email the email */ public void setEmail(String email) { this.email = email; } /** * Gets senha. * * @return the senha */ public String getSenha() { return senha; } /** * Sets senha. * * @param senha the senha */ public void setSenha(String senha) { this.senha = senha; } /** * Gets nome completo. * * @return the nome completo */ public String getNomeCompleto() { return nome_completo; } /** * Sets nome completo. * * @param nome_completo the nome completo */ public void setNomeCompleto(String nome_completo) { this.nome_completo = nome_completo; } /** * Gets telefone. * * @return the telefone */ public String getTelefone() { return telefone; } /** * Sets telefone. * * @param telefone the telefone */ public void setTelefone(String telefone) { this.telefone = telefone; } /** * Gets celular. * * @return the celular */ public String getCelular() { return celular; } /** * Sets celular. * * @param celular the celular */ public void setCelular(String celular) { this.celular = celular; } /** * Gets enderecos. * * @return the enderecos */ public List<Endereco> getEnderecos() { return enderecos; } /** * Sets enderecos. * * @param enderecos the enderecos */ public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } /** * Sets tudo. * * @param id the id * @param email the email * @param senha the senha * @param nome_completo the nome completo * @param telefone the telefone * @param celular the celular * @param enderecos the enderecos */ public void setTudo(int id, String email, String senha, String nome_completo, String telefone, String celular, List<Endereco> enderecos) { this.setId(id); this.setEmail(email); this.setSenha(senha); this.setNomeCompleto(nome_completo); this.setTelefone(telefone); this.setCelular(celular); this.setEnderecos(enderecos); } /** * Gets tudo. * * @return the tudo */ public String getTudo() { String result = "id: " + this.getId() +"\n"+ "email: " + this.getEmail() +"\n"+ "nome_completo: " + this.getNomeCompleto() +"\n"+ "telefone: " + this.getTelefone() +"\n"+ "celular: " + this.getCelular() +"\n"; for ( Endereco endereco : this.enderecos ) result = result + ( "\n\n" + endereco.getTudo() + "\n" ); return result; } }
true