text
stringlengths 10
2.72M
|
|---|
package com.liferay.mobile.screens.messageboardscreenlet.view;
import com.liferay.mobile.screens.base.list.view.BaseListViewModel;
/**
* Created by darshan on 6/8/15.
*/
public interface MyListViewModel<E> extends BaseListViewModel<E> {
void setListCount(int totalCount);
void setAdapter(String adapterClassName, int layoutId, int progressLayoutId);
}
|
package com.cpz.Demo04;
import java.util.ArrayList;
public class Mymain {
public static void main(String[] args) {
Manger manger=new Manger("群主",1000);
Member one= new Member("成员A",0);
Member two= new Member("成员B",0);
Member there= new Member("成员C",0);
manger.show();
one.show();
two.show();
there.show();
System.out.println("========");
ArrayList<Integer> redListt=manger.send(20,3);
one.receive(redListt);
two.receive(redListt);
there.receive(redListt);
manger.show();
one.show();
two.show();
there.show();
}
}
|
package com.tirthal.learning;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.NotifyBuilder;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
public class HelloWorldTest {
@Autowired
private CamelContext camelContext;
@Test
public void contextLoads() {
// we expect that one or more messages is automatic done by the Camel route as it uses a timer to trigger
NotifyBuilder notify = new NotifyBuilder(camelContext).whenDone(5).create();
assertTrue(notify.matches(10, TimeUnit.SECONDS));
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import edu.tsinghua.lumaqq.models.Group;
import edu.tsinghua.lumaqq.models.ModelRegistry;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.packets.BasicInPacket;
import edu.tsinghua.lumaqq.qq.packets.InPacket;
import edu.tsinghua.lumaqq.qq.packets.in.ReceiveIMPacket;
/**
* 消息队列实现类
*
* * @author luma
*/
public class MessageQueue {
// 总队列
private Queue<InPacket> queue;
// 系统消息队列
private Queue<InPacket> sysQueue;
// 延迟处理队列
private Queue<InPacket> postponeQueue;
// 用户消息队列映射哈希表
private Map<Integer, Queue<InPacket>> userQueueMap;
// 用户临时会话消息映射哈希表
private Map<Integer, Queue<InPacket>> tempSessionQueueMap;
// 短消息队列
private Queue<InPacket> smsQueue;
// true表示收到的消息应该延迟处理
private boolean postpone;
/**
* 私有构造函数,singleton模式
*/
public MessageQueue() {
queue = new LinkedList<InPacket>();
sysQueue = new LinkedList<InPacket>();
postponeQueue = new LinkedList<InPacket>();
userQueueMap = new HashMap<Integer, Queue<InPacket>>();
tempSessionQueueMap = new HashMap<Integer, Queue<InPacket>>();
smsQueue = new LinkedList<InPacket>();
postpone = false;
}
/**
* 情况所有数据
*/
public void clear() {
queue.clear();
sysQueue.clear();
postponeQueue.clear();
userQueueMap.clear();
}
/**
* 添加一个短消息到队列末尾
*
* @param in
* 要添加的消息包对象
*/
public void putSMS(InPacket in) {
if(in != null) {
smsQueue.offer(in);
queue.offer(in);
}
}
/**
* 得到队列中第一条短消息,并且把它从队列中删除
*
* @return
* InPacket,如果队列为空,返回null
*/
public InPacket getSMS() {
InPacket ret = smsQueue.poll();
queue.remove(ret);
return ret;
}
/**
* 得到下一条手机短信
*
* @param qq
* @return
*/
public InPacket getSMS(int qq) {
int size = smsQueue.size();
while(size-- > 0) {
ReceiveIMPacket packet = (ReceiveIMPacket)smsQueue.poll();
if(packet.sms.sender == qq) {
queue.remove(packet);
return packet;
} else
smsQueue.offer(packet);
}
return null;
}
/**
* 得到下一条手机短信
*
* @param mobile
* @return
*/
public InPacket getSMS(String mobile) {
int size = smsQueue.size();
while(size-- > 0) {
ReceiveIMPacket packet = (ReceiveIMPacket)smsQueue.poll();
if(packet.sms.sender == 0 && packet.sms.senderName.equals(mobile)) {
queue.remove(packet);
return packet;
} else
smsQueue.offer(packet);
}
return null;
}
/**
* 把一个普通消息包推入消息队列
* @param packet
* 消息包对象
*/
public void putMessage(BasicInPacket packet) {
putMessage(packet, true);
}
/**
* @param packet
* 消息包对象
* @param global
* true表示添加这个消息到总队列中。推到总队列中的效果是这条消息会在tray中
* 闪烁。有时候消息是不需要在tray中闪烁的,比如把群消息设为只显示计数,不显示
* 提示时。
*/
public void putMessage(InPacket packet, boolean global) {
ReceiveIMPacket im = (ReceiveIMPacket)packet;
if(im.header.type == QQ.QQ_RECV_IM_TEMP_SESSION) {
putTempSessionMessage(im);
return;
}
// 得到QQ号,判断是否已经存在该用户的消息队列,如果这个是群消息,这个其实就是群的内部ID
int qq;
if(im.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER)
qq = im.clusterIM.clusterId;
else
qq = im.header.sender;
Queue<InPacket> userQueue = null;
if(!userQueueMap.containsKey(qq)) {
userQueue = new LinkedList<InPacket>();
userQueueMap.put(qq, userQueue);
} else {
userQueue = userQueueMap.get(qq);
}
// 消息推入用户队列组队列和总队列
userQueue.offer(packet);
if(global)
queue.offer(packet);
}
/**
* 把临时会话消息推入队列
*
* @param packet
*/
protected void putTempSessionMessage(ReceiveIMPacket packet) {
int qq = packet.tempSessionIM.sender;
Queue<InPacket> tempQueue = null;
if(tempSessionQueueMap.containsKey(qq))
tempQueue = tempSessionQueueMap.get(qq);
else {
tempQueue = new LinkedList<InPacket>();
tempSessionQueueMap.put(qq, tempQueue);
}
tempQueue.offer(packet);
queue.offer(packet);
}
/**
* 把一个系统消息推入队列
* @param packet
*/
public void putSystemMessage(BasicInPacket packet) {
sysQueue.offer(packet);
queue.offer(packet);
}
/**
* 得到一条普通消息,并把他从队列中删除
*
* @param qq
* 发送消息的好友QQ号
* @return
* 如果有消息在返回消息,否则返回null
*/
public InPacket getMessage(int qq) {
// 检查是否有这个队列,有则取第一个消息,如果取后队列为空,删除这个队列
if(userQueueMap.containsKey(qq)) {
Queue<InPacket> userQueue = userQueueMap.get(qq);
InPacket p = userQueue.poll();
if(p == null)
return null;
// 从总队列中删除
queue.remove(p);
// 如果用户消息队列为空,删除这个队列
if(userQueue.isEmpty())
userQueueMap.remove(qq);
return p;
} else
return null;
}
/**
* 得到一条普通消息,不把他从队列中删除
*
* @param qq
* 发送消息的好友QQ号
* @return
* 如果有消息在返回消息,否则返回null
*/
public InPacket peekMessage(int qq) {
// 检查是否有这个队列,有则取第一个消息,如果取后队列为空,删除这个队列
if(userQueueMap.containsKey(qq)) {
Queue<InPacket> userQueue = userQueueMap.get(qq);
return userQueue.peek();
} else
return null;
}
/**
* 把qq号指定的好友或者群的所有消息删除
*
* @param qq
* 可能是好友的QQ号,也可能是群的内部ID
*/
public void removeMessage(int qq) {
// 检查是否有这个队列
if(userQueueMap.containsKey(qq)) {
Queue<InPacket> userQueue = userQueueMap.remove(qq);
for(InPacket p : userQueue)
queue.remove(p);
}
}
/**
* 得到一条普通消息,这条消息是该组内队列的第一条
*
* @param g
* Group
* @return
* 如果有则返回消息,否则返回null
*/
public InPacket getGroupMessage(Group g) {
int nextSender = nextGroupSender(g);
if(nextSender == -1)
return null;
else {
Queue<InPacket> userQueue = userQueueMap.get(nextSender);
InPacket ret = userQueue.poll();
queue.remove(ret);
return ret;
}
}
/**
* 得到系统消息队列的第一个包,但是不删除它
*
* @return
* 系统消息包对象
*/
public InPacket peekSystemMessage() {
InPacket ret = sysQueue.peek();
return ret;
}
/**
* 得到一条系统消息,并把他从队列删除
*
* @return
* 如果有消息,返回消息,否则返回null
*/
public InPacket getSystemMessage() {
InPacket ret = sysQueue.poll();
queue.remove(ret);
return ret;
}
/**
* 检查是否某个好友还有消息未读
*
* @param qqNum
* 好友QQ号
* @return
* true如果有消息未读
*/
public boolean hasMessage(int qqNum) {
return userQueueMap.containsKey(qqNum);
}
/**
* 检查是否有某个用户的临时会话消息
*
* @param qqNum
* QQ号
* @return
* true表示有临时会话消息未读
*/
public boolean hasTempSessionMessage(int qqNum) {
return tempSessionQueueMap.containsKey(qqNum);
}
/**
* 得到下一条临时会话消息
*
* @param qqNum
* @return
*/
public InPacket getTempSessionMessage(int qqNum) {
if(hasTempSessionMessage(qqNum)) {
Queue<InPacket> tempQueue = tempSessionQueueMap.get(qqNum);
InPacket p = tempQueue.poll();
if(p == null)
return null;
// 从总队列中删除
queue.remove(p);
// 如果用户消息队列为空,删除这个队列
if(tempQueue.isEmpty())
tempSessionQueueMap.remove(qqNum);
return p;
} else
return null;
}
/**
* 得到下一条临时会话消息,不从队列中删除
*
* @param qqNum
* @return
*/
public InPacket peekTempSessionMessage(int qqNum) {
if(hasTempSessionMessage(qqNum)) {
Queue<InPacket> tempQueue = tempSessionQueueMap.get(qqNum);
return tempQueue.peek();
} else
return null;
}
/**
* 检查是否某个群下面有讨论组的消息,如果父群id是0,则检查
* 是否有多人对话消息
*
* @param parentClusterId
* 父群id,0表示多人对话容器
* @return
* 子群id,如果为-1表示没有子群有消息
*/
public int hasSubClusterIM(int parentClusterId) {
for(InPacket p : queue) {
if(p instanceof ReceiveIMPacket) {
ReceiveIMPacket packet = (ReceiveIMPacket)p;
switch(packet.header.type) {
case QQ.QQ_RECV_IM_TEMP_CLUSTER:
if(packet.clusterIM.externalId == parentClusterId)
return packet.clusterIM.clusterId;
default:
break;
}
}
}
return -1;
}
/**
* 检查某个组是否有消息未读
*
* @param g
* Group
* @return
* true如果有消息未读
*/
public boolean hasGroupMessage(Group g) {
return nextGroupSender(g) != -1;
}
/**
* @return
* true如果还有任何消息未读
*/
public boolean hasNext() {
return !queue.isEmpty();
}
/**
* @return
* true如果还有系统消息未读
*/
public boolean hasSystemMessage() {
return !sysQueue.isEmpty();
}
/**
* @return
* true如果还有短消息
*/
public boolean hasSMS() {
return !smsQueue.isEmpty();
}
/**
* 好友的下一条消息是不是临时会话消息
*
* @param qq
* @return
*/
public boolean isNextTempSessionMessage(int qq) {
InPacket normal = peekMessage(qq);
InPacket temp = peekTempSessionMessage(qq);
if(temp == null && normal == null)
return false;
if(temp == null)
return false;
for(InPacket in : queue) {
if(in == normal)
return false;
if(temp == in)
return true;
}
return false;
}
/**
* @return
* 下一条消息的发送者的QQ号,如果是0,表示是系统消息,-1表示
* 无消息如果是群消息,返回的将是群的内部ID
*/
public int nextSender() {
InPacket packet = queue.peek();
if(packet == null)
return -1;
if(packet instanceof ReceiveIMPacket) {
ReceiveIMPacket im = (ReceiveIMPacket)packet;
if(im.header.type == QQ.QQ_RECV_IM_SYS_MESSAGE)
return 0;
else if(im.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER)
return im.clusterIM.clusterId;
else
return im.header.sender;
} else
return 0;
}
/**
* 返回下一个消息的来源,对于普通消息,返回QQ_IM_FROM_FRIEND,对于
* 系统消息,返回QQ_IM_FROM_SYS,对于群消息,有两种情况,因为群消息
* 包含了普通消息和通知消息,对于普通消息,我们返回QQ_IM_FROM_CLUSTER,
* 对于通知消息,我们返回QQ_IM_FROM_SYS
*
* @return
* 消息来源标识常量
*/
public int nextMessageSource() {
InPacket packet = queue.peek();
if(packet == null)
return -1;
if(packet instanceof ReceiveIMPacket) {
ReceiveIMPacket im = (ReceiveIMPacket)packet;
return im.getMessageCategory();
} else
return QQ.QQ_IM_FROM_SYS;
}
/**
* 返回该组内下一条消息发送者的QQ号
*
* @param g
* Group
* @return
* QQ号,如果没有消息,返回-1
*/
public int nextGroupSender(Group g) {
for(InPacket p : queue) {
if(p instanceof ReceiveIMPacket) {
ReceiveIMPacket packet = (ReceiveIMPacket)p;
if(packet.header.type == QQ.QQ_RECV_IM_BIND_USER || packet.header.type == QQ.QQ_RECV_IM_MOBILE_QQ)
continue;
// 得到下一个包的发送者QQ号
int sender = packet.header.sender;
if(packet.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER)
sender = packet.clusterIM.clusterId;
// 在g指定的组中查找是否有这个好友
if(ModelRegistry.hasUser(sender)) {
if(ModelRegistry.getUser(sender).group == g)
return sender;
} else if(ModelRegistry.hasCluster(sender)) {
if(ModelRegistry.getCluster(sender).group == g)
return sender;
}
}
}
return -1;
}
/**
* @return
* 下一个应该闪烁的消息的发送者
*/
public int nextBlinkableIMSender() {
for(InPacket p : queue) {
if(p instanceof ReceiveIMPacket) {
ReceiveIMPacket packet = (ReceiveIMPacket)p;
switch(packet.header.type) {
case QQ.QQ_RECV_IM_FRIEND:
case QQ.QQ_RECV_IM_STRANGER:
case QQ.QQ_RECV_IM_TEMP_SESSION:
return packet.header.sender;
default:
break;
}
}
}
return -1;
}
/**
* @return
* 下一条群消息的群号,-1表示没有
*/
public int nextClusterIMSender() {
for(InPacket p : queue) {
if(p instanceof ReceiveIMPacket) {
ReceiveIMPacket packet = (ReceiveIMPacket)p;
switch(packet.header.type) {
case QQ.QQ_RECV_IM_CLUSTER:
return packet.header.sender;
case QQ.QQ_RECV_IM_TEMP_CLUSTER:
return packet.clusterIM.clusterId;
default:
break;
}
}
}
return -1;
}
/**
* 一个消息在好友列表还没得到之前到达了,延迟处理这个消息
*
* @param packet
* 消息包
*/
public void postponeMessage(InPacket packet) {
postponeQueue.offer(packet);
}
/**
* 返回下一个延迟处理的消息
*
* @return
* 如果有则返回消息,没有返回null
*/
public InPacket getPostponedMessage() {
return postponeQueue.poll();
}
/**
* @return Returns the postpone.
*/
public synchronized boolean isPostpone() {
return postpone;
}
/**
* @param postpone The postpone to set.
*/
public synchronized void setPostpone(boolean postpone) {
this.postpone = postpone;
}
}
|
package com.github.emailtohl.integration.core.user.entities;
public enum Gender {
MALE, FEMALE, UNSPECIFIED
}
|
package com.polyvelo.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.polyvelo.beans.Order;
import com.polyvelo.beans.Product;
import com.polyvelo.beans.Reminder;
import com.polyvelo.beans.User;
/**
* Servlet gérant la page personnel d'un user, qu'il soit Client, Livreur ou bien Marchand.
* Gère à la fois l'affichage du panier et la prise en compte des ajouts/maj de produits dans son panier par un client.
* @author Erwan Matrat & Charles Daumont
* @version 1.0
*/
public class ClientPageServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public static final String VUE_CLIENT = "/WEB-INF/restricted/client/clientPage.jsp";
public static final String VUE_DELIVER = "/WEB-INF/restricted/deliver/clientPage.jsp";
public static final String VUE_MERCHANT = "/WEB-INF/restricted/merchant/clientPage.jsp";
public static final String VUE_ERREUR = "/WEB-INF/restricted/common/erreur.jsp";
public static final String ATT_SESSION_USER ="userSession";
public static final String POSTITS_INFOS ="postits_infos";
public static final String POSTITS_COMMANDS ="postits_commands";
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
managePage(request, response);
}
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
managePage(request, response);
}
/**
* Met à jour les post-its du livreur. Récupère les informations sur le bouton qui a été cliqué.
* Suivant le bouton qui a été cliqué et avec l'id de l'order concerné,
* on met à jour l'état de la commande dans la BDD.
* @param request
* @param response
*/
private void updateStateOrder(HttpServletRequest request,
HttpServletResponse response) {
try{
int id_order = Integer.parseInt(request.getParameter("id_order_support"));
Order order = Order.getOrderById(id_order);
order.setState("en route");
order.updateStateBDD();
}catch(NumberFormatException e){
}
try{
int id_order = Integer.parseInt(request.getParameter("id_order_finished"));
Order order = Order.getOrderById(id_order);
order.setState("terminee");
order.updateStateBDD();
}catch(NumberFormatException e){
}
}
/**
* Charge les commandes qu'un livreur doit assurer. Le résultat est mis dans un attribut de requête.
* @param request
* @param response
*/
private void orderLoad(HttpServletRequest request,
HttpServletResponse response) {
ArrayList<Reminder> informations = Reminder.getInfoReminders();
request.setAttribute(POSTITS_INFOS, informations);
User user = (User)request.getSession().getAttribute(ATT_SESSION_USER);
if(user!=null && user.getType().equals("delivery")){
int id_user = user.getId();
ArrayList<Order> deliveries = Order.getDeliveriesByDeliverId(id_user);
request.setAttribute(POSTITS_COMMANDS, deliveries);
}
}
/**
* Gère l'affichage personnalisé suivant que l'utilisateur soit un client, un livreur ou un marchand.
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void managePage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute( ATT_SESSION_USER );
if(user!=null){
if(user.getType().equals("client")){
//affichage de la page résumant les commandes d'un client.
List<Order> list = Order.getOrdersByClientId(user.getId());
request.setAttribute("list", list);
this.getServletContext().getRequestDispatcher( VUE_CLIENT ).forward( request, response );
}else if(user.getType().equals("delivery")){
//affichage de la page listant les livraisons que doit assurer le livreur
updateStateOrder(request, response);
orderLoad(request, response);
this.getServletContext().getRequestDispatcher( VUE_DELIVER ).forward( request, response );
}else{
//affichage de la page listant les commandes faites à un marchand.
String addr = (String)request.getParameter("address");
if(addr!=null){
User.updateMerchantAddress(user.getId(), addr);
}
String address = User.getMerchantAdressById(user.getId());
request.setAttribute("address", address);
HashMap<Product, Integer> list = Product.getProductsOrderByMerchantId(user.getId());
request.setAttribute("list", list);
this.getServletContext().getRequestDispatcher( VUE_MERCHANT).forward( request, response );
}
}else{
//affichage de la page d'erreur si rien ne correspond.
this.getServletContext().getRequestDispatcher( VUE_ERREUR ).forward( request, response );
}
}
}
|
package searching;
public class ThePaintersPartition {
public static void main(String[] args) {
int arr[] = { 5, 10, 30, 20, 15 };
int k = 3;
int n = 5;
System.out.println(midTime(arr, n, k));
}
static int midTime(int arr[], int n, int k) {
int low = 0;
int high = 1;
for (int e : arr) {
low = Math.max(low, e);
high += e;
}
int ans = 0;
while (low <= high) {
int mid = (low + high) >> 1;
if (isPrintPossible(arr, n, mid, k)) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
private static boolean isPrintPossible(int[] arr, int n, int mid, int k) {
int count = 1;
int sum = arr[0];
for (int i = 1; i < n; i++) {
if (sum + arr[i] <= mid) {
sum += arr[i];
} else {
count++;
sum = arr[i];
}
}
if (count > k) {
return false;
} else {
return true;
}
}
}
|
package test3.suiteEx;
import org.testng.annotations.Test;
public class Test3 {
@Test
public void t3_1() {
System.out.println("t3");
}
}
|
/*
* Copyright (C) 2014 - 2015 Marko Salmela, http://fuusio.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fuusio.api.flow;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import org.fuusio.api.component.Component;
import org.fuusio.api.dependency.DependencyScopeOwner;
import org.fuusio.api.mvp.View;
import java.util.List;
/**
* {@link Flow} defines an interface for components that implement UI flow logic controlling Views
* and Presenter according to received user interaction events. A concrete {@link Flow} implementation
* also provides a {@link FlowScope} for dependency injection.
*/
public interface Flow extends Component, DependencyScopeOwner, FragmentManager.OnBackStackChangedListener {
/**
* Gets the currently active Views.
*
* @return A {@link List} containing the currently active Views as {@link View}s.
*/
List<View> getActiveViews();
/**
* Adds the given {@link View} to the set of active Views.
*
* @param view A {@link View} to be added.
* @return The given {@link View} if it was not already in the set of active Views.
*/
View addActiveView(View view);
/**
* Removes the given {@link View} from the set of active Views.
*
* @param view A {@link View} to be removed.
* @return The given {@link View} if it was included in the set of active Views.
*/
View removeActiveView(View view);
/**
* A {@link Flow} implementation can use this method to activate i.e. to make visible the given
* {@link View}.
*
* @param view A {@link View} to be activated. May not be {@link null}.
*/
void activateView(View view);
/**
* Tests if the given {@link View} is currently active one.
*
* @param view A {@link View}.
* @return A {@code boolean} value.
*/
boolean isActiveView(View view);
/**
* Gets the {@link FlowManager} that started this {@link Flow}.
*
* @return A {@link FlowManager}.
*/
FlowManager getFlowManager();
/**
* Sets the {@link FlowManager} that started this {@link Flow}.
*
* @param manager A {@link FlowManager}.
*/
void setFlowManager(FlowManager manager);
/**
* This method is invoked to pause this {@link Flow}.
*/
void pause();
/**
* This method is invoked to resume this {@link Flow}.
*/
void resume();
/**
* This method is invoked to restart this {@link Flow}.
*/
void restart();
/**
* This method is invoked to start this {@link Flow}. The method is not intended to be invoked
* directly by a developer, but via invoking {@link FlowManager#startFlow(Flow, Bundle)}.
*
* @param params A {@link Bundle} containing parameters for starting the {@link Flow}.
*/
void start(final Bundle params);
/**
* This method is invoked to stop this {@link Flow}.
*/
void stop();
/**
* This method is invoked to destroy this {@link Flow}.
*/
void destroy();
/**
* This method is invoked by {@link Flow#pause()} when this {@link Flow} is paused.
*/
void onPause();
/**
* This method is invoked by {@link Flow#resume()} when this {@link Flow} is resumed.
*/
void onResume();
/**
* This method is invoked by {@link Flow#restart()} when this {@link Flow} is restarted.
*/
void onRestart();
/**
* This method is invoked by {@link Flow#start(Bundle)} when this {@link Flow} is started.
*
* @param params A {@link Bundle} containing parameters for starting the {@link Flow}.
*/
void onStart(Bundle params);
/**
* This method is invoked by {@link Flow#stop()} when this {@link Flow} is stopped.
*/
void onStop();
/**
* This method is invoked by {@link Flow#destroy()} when this {@link Flow} is destroyed.
*/
void onDestroy();
/**
* Tests if this {@link Flow} handles the back pressed event.
*
* @return A {@code boolean} value.
*/
boolean isBackPressedEventHandler();
/**
* Clears the back stack managed by {@link FragmentManager}.
*/
void clearBackStack();
/**
* Tests if the previous {@link View} can be navigated back to.
*
* @return A {@code boolean} value.
*/
boolean canGoBack();
/**
* Goes back to previous {@link View}.
*/
void goBack();
/**
* Invoked when the given {@link View} has been brought back to foreground and resumed.
*
* @param view A {@link View}.
*/
void onNavigatedBackTo(View view);
boolean isPaused();
boolean isRestarted();
boolean isResumed();
boolean isStarted();
boolean isStopped();
}
|
package domain;
import java.util.Collection;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.Valid;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
@Entity
@Access(AccessType.PROPERTY)
public class Volume extends DomainEntity {
private String title;
private String description;
private String year;
private double price;
private User creator;
private Collection<Customer> customers;
private Collection<Newspaper> newspapers;
public Volume() {
super();
}
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
@NotBlank
@SafeHtml(whitelistType = WhiteListType.NONE)
@Column(length = Integer.MAX_VALUE)
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
@NotBlank
@Pattern(regexp = "^(\\d{4})$")
public String getYear() {
return this.year;
}
public void setYear(final String year) {
this.year = year;
}
@Digits(fraction = 2, integer = 15)
@Min(value = 0)
public double getPrice() {
return this.price;
}
public void setPrice(final double price) {
this.price = price;
}
@Valid
@NotNull
@ManyToOne(optional = false)
public User getCreator() {
return this.creator;
}
public void setCreator(final User creator) {
this.creator = creator;
}
@NotNull
@ManyToMany(mappedBy = "volumes")
public Collection<Customer> getCustomers() {
return this.customers;
}
public void setCustomers(final Collection<Customer> customers) {
this.customers = customers;
}
@NotNull
@ManyToMany
public Collection<Newspaper> getNewspapers() {
return this.newspapers;
}
public void setNewspapers(final Collection<Newspaper> newspapers) {
this.newspapers = newspapers;
}
}
|
package com.usnoozeulose.app.alarm.alert;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.usnoozeulose.app.alarm.Alarm;
import com.usnoozeulose.app.alarm.Ball;
import com.usnoozeulose.app.alarm.R;
import com.usnoozeulose.app.alarm.activities.AlarmActivity;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class BallActivity extends Activity implements SensorEventListener {
int total;
int minutes;
int seconds;
boolean draw = true;
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
boolean complete;
boolean stop = false;
boolean level1 = false;
boolean level2 = false;
boolean level3 = false;
boolean restart = true;
boolean buttonActivate = false;
String time = " 0";
CountDownTimer timer;
boolean fail;
private Paint paint = new Paint();
AnimatedView animatedView = null;
Ball b1 = new Ball(0, 25);
Ball b2 = new Ball(0, 35);
Ball b3 = new Ball(0, 45);
Ball b4 = new Ball(0, 55);
Ball b5 = new Ball(0, 65);
boolean isPop = false;
Ball[] ballArray = new Ball[]{b1, b2, b3, b4, b5};
ShapeDrawable ball1 = new ShapeDrawable();
ShapeDrawable ball2 = new ShapeDrawable();
ShapeDrawable ball3 = new ShapeDrawable();
ShapeDrawable ball4 = new ShapeDrawable();
ShapeDrawable ball5 = new ShapeDrawable();
private int holeX;
private int holeY;
private int holeS;
ShapeDrawable hole = new ShapeDrawable();
//public static int x;
//public static int y;
public static int phoneHeight;
public static int phoneWidth;
boolean actionUpFlag;
int[] androidColors;
private Button start;
private TextView title;
private View.OnClickListener onClickListener;
private Alarm alarm;
private Vibrator vibrator;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = { 1000, 200, 200, 200 };
vibrator.vibrate(pattern, 0);
Bundle bundle = this.getIntent().getExtras();
alarm = (Alarm) bundle.getSerializable("alarm");
if(bundle.getSerializable("total") == null){
total = 0;
}
else
total = (Integer) bundle.getSerializable("total");
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
phoneHeight = displaymetrics.heightPixels;
phoneWidth = displaymetrics.widthPixels;
holeX = (int)(Math.random()*1100 + 150);
holeY = (int)(Math.random()*2000 + 250);
while(holeY <= phoneHeight/3 + 300 && holeY >= phoneHeight/3 - 250){
holeY = (int)(Math.random()*2000 + 250);
}
holeY = (int)(Math.random()*180 + 250);
holeS = 110 * 2;
androidColors = getResources().getIntArray(R.array.androidcolors);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(BallActivity.this);
setContentView(animatedView);
timer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
minutes = (int) TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished);
seconds = (int) TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)-
(int) TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished));
time = ("Time Left: "+String.format("%d min, %d sec", minutes, seconds));
}
public void onFinish() {
minutes = 0;
seconds = 0;
time =("TOO LATE YOU MUST'VE SNOOZED");
}
}.start();
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
int inHoleCounter = 0;
for(int i = 0; i < ballArray.length; i++){
int x = ballArray[i].getX();
int y = ballArray[i].getY();
int xChange = (int)(event.values[0] * ballArray[i].getSpeed());
int yChange = (int)Math.round(event.values[1] * ballArray[i].getSpeed());
int dia = ballArray[i].getRadius() * 2;
ballArray[i].setInHole(holeX, holeY, holeS);
if(x >= 0 && x <= phoneWidth - dia && !ballArray[i].getInHole()) {
if (i % 2 == 1) {
ballArray[i].setX(x + xChange);
} else {
ballArray[i].setX(x - xChange);
}
if(ballArray[i].getX() < 0){
ballArray[i].setX(0);
}
if(ballArray[i].getX() >= phoneWidth - dia){
ballArray[i].setX(phoneWidth - dia);
}
}
if(y >= 0 && y <= phoneHeight - dia - 300 && !ballArray[i].getInHole()){
if(i % 2 == 1){
ballArray[i].setY(y - yChange);
}
else {
ballArray[i].setY(y + yChange);
}
if(ballArray[i].getY() < 0){
ballArray[i].setY(0);
}
if(ballArray[i].getY() >= phoneHeight - dia - 300){
ballArray[i].setY(phoneHeight - dia - 300);
}
}
}
}
}
public class AnimatedView extends ImageView {
static final int width = 175;
static final int height = 175;
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
//BALL IS CREATED LMAO
ball1 = new ShapeDrawable(new OvalShape());
ball2 = new ShapeDrawable(new OvalShape());
ball3 = new ShapeDrawable(new OvalShape());
ball4 = new ShapeDrawable(new OvalShape());
ball5 = new ShapeDrawable(new OvalShape());
ball1.getPaint().setColor(androidColors[new Random().nextInt(androidColors.length)]);
ball2.getPaint().setColor(androidColors[new Random().nextInt(androidColors.length)]);
ball3.getPaint().setColor(androidColors[new Random().nextInt(androidColors.length)]);
ball4.getPaint().setColor(androidColors[new Random().nextInt(androidColors.length)]);
ball5.getPaint().setColor(androidColors[new Random().nextInt(androidColors.length)]);
hole = new ShapeDrawable(new RectShape());
}
@Override
protected void onDraw(Canvas canvas) {
if(draw && restart){
ball1.setBounds(b1.getX(), b1.getY(), b1.getX() + 2 * b1.getRadius(), b1.getY() + 2 * b1.getRadius());
ball2.setBounds(b2.getX(), b2.getY(), b2.getX() + 2 * b2.getRadius(), b2.getY() + 2 * b2.getRadius());
ball3.setBounds(b3.getX(), b3.getY(), b3.getX() + 2 * b3.getRadius(), b3.getY() + 2 * b3.getRadius());
ball4.setBounds(b4.getX(), b4.getY(), b4.getX() + 2 * b4.getRadius(), b4.getY() + 2 * b4.getRadius());
ball5.setBounds(b5.getX(), b5.getY(), b5.getX() + 2 * b5.getRadius(), b5.getY() + 2 * b5.getRadius());
hole.setBounds(holeX, holeY - 100, holeX + holeS, holeY + holeS - 100);
hole.draw(canvas);
ball5.draw(canvas);
ball4.draw(canvas);
ball3.draw(canvas);
ball2.draw(canvas);
ball1.draw(canvas);
complete = true;
paint.setTextSize(140);
paint.setColor(Color.MAGENTA);
int i = 0;
while (complete && i < 5) {
if (!ballArray[i].getInHole()) {
complete = false;
}
i++;
}
paint.setColor(Color.BLACK);
paint.setTextSize(80);
canvas.drawText(time, 40, 90, paint);
buttonActivate = false;
fail = false;
if (minutes == 0 && seconds == 0) {
fail = true;
paint.setColor(Color.BLACK);
paint.setTextSize(140);
restart = false;
buttonActivate = true;
stop = true;
if (vibrator != null)
vibrator.cancel();
vibrator.cancel();
Intent intent = new Intent(getApplicationContext(), AlarmAlertActivity.class);
intent.putExtra("alarm", alarm);
total += 5;
intent.putExtra("total", total);
//BILL THE CUSTOMER HERE RAAAAA
startActivity(intent);
} else if (complete && !fail && !stop) {
timer.cancel();
paint.setTextSize(140);
paint.setColor(Color.MAGENTA);
restart = false;
buttonActivate = true;
vibrator.cancel();
Intent intent = new Intent(getApplicationContext(), AlarmActivity.class);
intent.putExtra("snoozeOn", false);
intent.putExtra("total", total);
startActivity(intent);
}
invalidate();
}
else{
draw = false;
}
}
}
}
|
package com.example.shopping.repository;
import com.example.shopping.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, RevisionRepository<Product, Long, Integer> {
}
|
/*
* 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 MapaeoBD;
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.Table;
/**
*
* @author Rodrigo_Rivera
*/
@Entity
@Table(name = "biblioteca") // si tiene que ir como en la de la base
public class Biblioteca {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
//colmnas de la base
@Column(name = "id") // nombre de la columana
private long biblioteca_id;// como lo vamos a manejar
@Column(name = "nombre")
private String biblioteca_nombre;
public Biblioteca() {
this.biblioteca_nombre = null;
}
public long getLibro_id() {
return biblioteca_id;
}
public void setLibro_id(long libro_id) {
this.biblioteca_id = libro_id;
}
public String getLibro_nombre() {
return biblioteca_nombre;
}
public void setLibro_nombre(String libro_nombre) {
this.biblioteca_nombre = libro_nombre;
}
}
|
package GUI_Components;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* BEGEOT_BUNOUF_CustomJFrame is extending the JFrame class
* It contains various optimized prefabs for creating a JFrame, including a setting class iteration.
* @author Hugues Begeot
*/
public abstract class BEGEOT_BUNOUF_CustomJFrame extends JFrame
{
protected final static String PATH_LOGO = "./src/pictures/logo.png";
protected final static String PATH_LOGO_FULL = "./src/pictures/logoFull.png";
/**
* default @BEGEOT_BUNOUF_CustomJFrame's constructor.
* @deprecated We'll prefer using the other constructor
* */
@Deprecated
public BEGEOT_BUNOUF_CustomJFrame()
{
setPreferredSize(new Dimension(500, 500));
}
/**
* Regular @BEGEOT_BUNOUF_CustomJFrame's constructor.
* <p>
* @param title Type of the JFrame we want to create.
* @param closeOnExit if true, the program is closed when we exit the JFrame
* @param dimX width of the JFrame
* @param dimY height of the JFrame
* */
protected BEGEOT_BUNOUF_CustomJFrame(String title, boolean closeOnExit, int dimX, int dimY)
{
try { setIconImage(ImageIO.read(new File(PATH_LOGO)) ); }
catch (IOException e) { System.out.println("Icon not found"); }
setTitle(title);
setPreferredSize(new Dimension(dimX, dimY));
setMinimumSize(new Dimension(dimX, dimY));
//setResizable(false);
setAlwaysOnTop(false);
if(closeOnExit) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
/**
* Centre les valeurs d'une JTable passée en argument
* <p>
* @param table JTable à centrer
* */
protected void centrerJTable(JTable table)
{
DefaultTableCellRenderer custom = new DefaultTableCellRenderer();
// centre les données de ton tableau
custom.setHorizontalAlignment(JLabel.CENTER);
// centre chaque cellule de ton tableau
for (int i=0 ; i < table.getColumnCount() ; i++)
table.getColumnModel().getColumn(i).setCellRenderer(custom);
((DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
table.setEnabled(false);
}
}
|
package tree;
import javax.net.ssl.CertPathTrustManagerParameters;
import java.util.Collections;
/**
* Create by coldwarm on 2018/9/19.
* java实现单链表
*/
public class SingleLinkedList {
private Node head;
private Node current;
private int size;
public SingleLinkedList(){
head = current =new Node(null); //初始时令head和current都是头指针,即下一结点为头结点,即数据域为空。换句话来讲,单链表的头指针只是个指针,不含数据
size=0;
}
public void add(Object object){
Node newNode = new Node(object);
current = head.next;
while (current.next != null){
current = current.next;
}
current.next = newNode;
newNode.next = null;
size++;
}
public void insert(int i,Object object){
Node newNode = new Node(object);
Node prve = head;
current = head.next;
int j = 0;
while (current != null && j < i){
prve = current;
current = current.next;
j++;
}
newNode.next = current;
prve.next = newNode;
size++;
}
public void delete(int i){
Node prev = head;
current = head.next;
int j = 0;
while (current != null&&j<i){
prev = current;
current = current.next;
}
prev.next = current.next;
size--;
}
//反转单链表
public Node fanzhuan(Node node){
if (node == null)
return node;
Node pre = node; //上一节点
Node cur = node.next; //当前节点
Node temp; //临时节点,用于保存当前节点的下一节点
while (cur != null){
temp = cur.next;
cur.setNext(pre);//改变当前节点的指针
//指针向下移动
pre = cur;
cur = temp;
}
head.setNext(null);
return pre;
}
}
|
package pages;
import driversConfig.DriverManager;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.WebElementFacade;
@Getter
@Slf4j
public class RegistrationPage extends BasePage{
@FindBy(css = ".header__menu-link")
private WebElementFacade buttonLogIn;
public void goToRegistrationPage(){
DriverManager driverManager = new DriverManager();
driverManager.newDriver().get("https://eldritch-foundry.com/");
}
}
|
package Poker;
public class Card {
public String color;
public String Csize;
public Card(String color, String csize) {
this.color = color;
Csize = csize;
}
@Override
public String toString() {
return "(" + color + Csize +")" ;
}
}
|
package com.leepc.chat;
import com.leepc.chat.service.MessageService;
import com.leepc.chat.util.Constant;
import com.leepc.chat.util.TokenUtils;
import io.jsonwebtoken.Claims;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ChatApplicationTests {
@Autowired
MessageService ms;
@Test
void contextLoads() {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1ODQ1MDkwODEsImlkIjoxLCJ1c2VybmFtZSI6ImhhaGEiLCJleHAiOjE1ODQ1MTI2ODF9.dIMYckSCxGH90aiitMRT2GY8Nx_2DPyml0-XIG--N30";
TokenUtils.parseJWT(token);
}
@Test
void testToken() {
String token = TokenUtils.createToken(1,"haha", Constant.JWT_TTL);
System.out.println(token);
Claims claims = TokenUtils.parseJWT(token);
System.out.println(claims);
}
}
|
/*
Copyright (C) 2009, Bioingenium Research Group
http://www.bioingenium.unal.edu.co
Author: Alexander Pinzon Fernandez
JNukak3D is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
JNukak3D is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with JNukak3D; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA,
or see http://www.gnu.org/copyleft/gpl.html
*/
package edu.co.unal.bioing.jnukak3d.ui;
import edu.co.unal.bioing.jnukak3d.nkUtil;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
/**
*
* @author Alexander Pinzon Fernandez
*/
public class nkAbout extends JFrame{
public nkAbout() {
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.gridheight=3;
ImageIcon logo=nkUtil.getImageIcon("edu.co.unal.bioing.jnukak3d.ui.nkAbout", "../resources/icons/clouds_Small.jpg");
JPanel iconPanel=new JPanel();
JLabel iconLabel=new JLabel();
iconLabel.setIcon(logo);
iconPanel.add(iconLabel,BorderLayout.CENTER);
iconPanel.setPreferredSize(new Dimension(logo.getIconWidth(),logo.getIconHeight()));
getContentPane().add(iconPanel,c);
c.gridx=1;
c.gridheight=1;
JLabel title=new JLabel("JNukak 3d");
title.setFont(new Font(Font.SERIF, Font.BOLD, 14));
c.insets=new Insets(15, 15, 0, 10);
c.anchor=GridBagConstraints.NORTHWEST;
getContentPane().add(title,c);
JTextArea textDescription=new JTextArea("Nukak about Nukak about Nukak about \n" +
"Nukak about Nukak about Nukak about \n" +
"Nukak about Nukak about Nukak about \n\n" +
"Bioingenium Research Group\n" +
"http://www.bioingenium.unal.edu.co");
textDescription.setEditable(false);
textDescription.setBackground(null);
c.gridy=1;
c.insets.top=15;
getContentPane().add(textDescription,c);
JButton okButton=new JButton("Ok");
okButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
);
c.gridy=2;
c.anchor=GridBagConstraints.BASELINE_TRAILING;
c.insets.right=10;
getContentPane().add(okButton,c);
//setSize(300, 200);
this.pack();
this.setTitle("About");
this.setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
}
}
|
package com.example.ta;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ta.Adapter.ViewPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class tabExamscheduleFragment extends Fragment {
private ViewPagerAdapter viewPagerAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
private int FINE_LOCATION_ACCESS_REQUEST_CODE = 10001;
private int BACKGROUND_LOCATION_ACCESS_REQUEST_CODE = 10002;
public tabExamscheduleFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
enableUserLocation();
enableBackgroundLocation();
return inflater.inflate(R.layout.fragment_tab_examschedule, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager =(ViewPager) view.findViewById(R.id.view_Examschedule);
tabLayout = (TabLayout) view.findViewById(R.id.tab_examschedule);
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPagerAdapter.addFragment(new ExamUtsFragment(), "UTS");
viewPagerAdapter.addFragment(new ExamscheduleFragment(), "UAS");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
private void enableUserLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
//ask for permission
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
//We need to show user a dialog for displaying why the permission is needed and then ask for the permission
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
}
}
}
private void enableBackgroundLocation(){
if (Build.VERSION.SDK_INT >= 29){
//Background Permission
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_BACKGROUND_LOCATION)== PackageManager.PERMISSION_GRANTED){
}
else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_BACKGROUND_LOCATION)){
//show dialog and ask for permission
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, BACKGROUND_LOCATION_ACCESS_REQUEST_CODE);
}else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, BACKGROUND_LOCATION_ACCESS_REQUEST_CODE);
}
}
}else {
}
}
}
|
package util;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.CategoryAxis;
import org.primefaces.model.chart.LineChartModel;
import org.primefaces.model.chart.LineChartSeries;
import dao.CulturaDAO;
import dao.RegistroDAO;
import models.Cultura;
import models.Registro;
@ManagedBean
@SessionScoped
public class RegistrosGraficosUtil implements Serializable {
private LineChartModel registrosGraficos;
private Date dataInicial;
private Date dataFinal;
private Registro registro;
private Set<Cultura> listaCulturas;
private ArrayList<Cultura> listaCulturasSelecionadas;
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
@PostConstruct
public void init() {
CulturaDAO dao = new CulturaDAO();
listaCulturas = dao.findByCulturaRegistro();
listaCulturasSelecionadas = new ArrayList<>();
createLineModels();
}
public LineChartModel getRegistrosGraficos() {
return registrosGraficos;
}
private void createLineModels() {
RegistroDAO registroDao = new RegistroDAO();
if (!listaCulturasSelecionadas.isEmpty()) {
List<List<Registro>> registroList = registroDao.gerarGraficoProjetado(dataInicial, dataFinal,
listaCulturasSelecionadas);
registrosGraficos = initCategoryModel(registroList);
registrosGraficos.setTitle("Registros");
registrosGraficos.setLegendPosition("e");
registrosGraficos.setShowPointLabels(true);
registrosGraficos.getAxes().put(AxisType.X, new CategoryAxis("Período"));
Axis yAxis = registrosGraficos.getAxis(AxisType.Y);
yAxis.setLabel("Escala");
yAxis.setMin(0);
yAxis.setMax(20);
} else {
registrosGraficos = null;
}
}
private LineChartModel initCategoryModel(List<List<Registro>> registroList) {
LineChartModel model = new LineChartModel();
LineChartSeries culturas = new LineChartSeries();
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i < registroList.size(); i++) {
culturas.setLabel(registroList.get(i).get(0).getCultura().getNome());
// String[] data = registro.getDataRegistro().toString().split("-");
for (int j = 0; j < registroList.get(i).size(); j++) {
culturas.set(formato.format(registroList.get(i).get(j).getDataRegistro()).toString(), registroList.get(i).get(j).getCultura().getEscalaPonderada());
//culturas = new LineChartSeries();
}
model.addSeries(culturas);
culturas = new LineChartSeries();
}
return model;
}
public String mostrarGrafico() {
createLineModels();
return "/graficos/graficos_ocorrencias.xhtml?faces-redirect=true";
}
public Registro getRegistro() {
return registro;
}
public void setRegistro(Registro registro) {
this.registro = registro;
}
public Set<Cultura> getListaCulturas() {
return listaCulturas;
}
public void setListaCulturas(Set<Cultura> listaCulturas) {
this.listaCulturas = listaCulturas;
}
public Date getDataInicial() {
return dataInicial;
}
public void setDataInicial(Date dataInicial) {
this.dataInicial = dataInicial;
}
public Date getDataFinal() {
return dataFinal;
}
public void setDataFinal(Date dataFinal) {
this.dataFinal = dataFinal;
}
public ArrayList<Cultura> getListaCulturasSelecionadas() {
return listaCulturasSelecionadas;
}
public void setListaCulturasSelecionadas(ArrayList<Cultura> listaCulturasSelecionadas) {
this.listaCulturasSelecionadas = listaCulturasSelecionadas;
}
}
|
package jour29;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Exception2 {
public static void main(String[] args) {
// C/ Yeni dosyayi programa ekleyiniz
//FileNotFoundException ve ArithmeticException hatalari var
try {
FileInputStream ekle =new FileInputStream("C/");
}
catch (FileNotFoundException e) {
System.out.println("Baba aku yok");
//e.printStackTrace();
}
catch (Exception e) {
System.out.println("Arabanin calismama sebeplerini bul");
//e.printStackTrace();
}
}
}
|
package com.kdgm.webservice;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TumYerKodlariGetirWsResult" type="{http://kaysis.gov.tr/}SonucResYerKod" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"tumYerKodlariGetirWsResult"
})
@XmlRootElement(name = "TumYerKodlariGetirWsResponse")
public class TumYerKodlariGetirWsResponse {
@XmlElement(name = "TumYerKodlariGetirWsResult")
protected SonucResYerKod tumYerKodlariGetirWsResult;
/**
* Gets the value of the tumYerKodlariGetirWsResult property.
*
* @return
* possible object is
* {@link SonucResYerKod }
*
*/
public SonucResYerKod getTumYerKodlariGetirWsResult() {
return tumYerKodlariGetirWsResult;
}
/**
* Sets the value of the tumYerKodlariGetirWsResult property.
*
* @param value
* allowed object is
* {@link SonucResYerKod }
*
*/
public void setTumYerKodlariGetirWsResult(SonucResYerKod value) {
this.tumYerKodlariGetirWsResult = value;
}
}
|
//import org.apache.log4j.BasicConfigurator;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
public class BranchServer {
public static BranchHandler handler;
public static Branch.Processor<BranchHandler> processor;
public static void main(String[] args){
int portNumber;
String branchName;
if(args.length != 2){
System.out.println("Please provide server name and port number in order");
System.exit(0);
}
try{
portNumber = Integer.parseInt(args[1]);
branchName = args[0];
handler = new BranchHandler(branchName);
processor = new Branch.Processor<BranchHandler>(handler);
//BasicConfigurator.configure();
simple(processor,portNumber);
}
catch(NumberFormatException e){
System.out.println("Please provide server name and port number in order");
System.exit(0);
}
}
public static void simple(Branch.Processor<BranchHandler> processor, int portNumber){
//System.out.println("port number is "+portNumber);
try{
TServerTransport serverTransport = new TServerSocket(portNumber);
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
System.out.println("Branch server started in port number "+portNumber);
server.serve();
}
catch(TTransportException e){
System.out.println("Provided port number is in use. Please provide different port number");
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package backjoon.graph;
import java.io.*;
import java.util.*;
public class Backjoon16234 {
static class Index{
int row, col;
public Index (int row, int col){
this.row = row;
this.col = col;
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int N, L, R;
static int graph[][];
static boolean check[][];
static int result;
static int[] rowArr = new int[]{0, 1, 0, -1};
static int[] colArr = new int[]{1, 0, -1, 0};
public static void main(String[] args) throws IOException{
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
L = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
// 그래프 선언
graph = new int[N + 1][N + 1];
check = new boolean[N + 1][N + 1];
// 그래프 초기화
for(int i = 1; i <= N; i++){
st = new StringTokenizer(br.readLine());
for(int j = 1; j <= N; j++){
graph[i][j] = Integer.parseInt(st.nextToken());
}
}
solve();
bw.write(result + "\n");
bw.close();
br.close();
}
static void solve() throws IOException{
while(true){
boolean flag = false;
for(boolean[] arr : check){
Arrays.fill(arr, false);
}
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
if(check[i][j] == false) {
if(bfs(i, j)) flag = true;
}
}
}
if(flag == false) break;
result++;
}
}
static boolean bfs(int row, int col){
int sum = 0;
int count = 0;
Queue<Index> queue = new LinkedList<>();
List<Index> list = new ArrayList<>();
queue.add(new Index(row, col));
check[row][col] = true;
list.add(new Index(row, col));
while(!queue.isEmpty()){
Index curIndex = queue.poll();
int curRow = curIndex.row;
int curCol = curIndex.col;
sum += graph[curRow][curCol];
count++;
for(int i = 0 ; i < rowArr.length; i++){
int toRow = curRow + rowArr[i];
int toCol = curCol + colArr[i];
// 범위 벗어나면 pass
if(toRow > N || toCol > N || toRow < 1 || toCol < 1) continue;
// 기 방문점이면 pass
if(check[toRow][toCol] == true) continue;
int absValue = Math.abs(graph[curRow][curCol] - graph[toRow][toCol]);
// 차이가 주어진 조건에 벗어나면 pass
if(absValue < L || absValue > R) continue;
queue.add(new Index(toRow, toCol));
list.add(new Index(toRow, toCol));
check[toRow][toCol] = true;
}
}
int value = sum / count;
for (Index index : list) {
graph[index.row][index.col] = value;
}
if(count > 1) return true;
else return false;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.keygen;
import org.apache.hudi.DataSourceWriteOptions;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.avro.generic.GenericRecord;
import java.util.Arrays;
import java.util.List;
/**
* Simple key generator, which takes names of fields to be used for recordKey and partitionPath as configs.
*/
public class SimpleKeyGenerator extends BuiltinKeyGenerator {
protected final String recordKeyField;
protected final String partitionPathField;
protected final boolean hiveStylePartitioning;
protected final boolean encodePartitionPath;
public SimpleKeyGenerator(TypedProperties props) {
this(props, props.getString(DataSourceWriteOptions.PARTITIONPATH_FIELD_OPT_KEY()));
}
public SimpleKeyGenerator(TypedProperties props, String partitionPathField) {
super(props);
this.recordKeyField = props.getString(DataSourceWriteOptions.RECORDKEY_FIELD_OPT_KEY());
this.partitionPathField = partitionPathField;
this.hiveStylePartitioning = props.getBoolean(DataSourceWriteOptions.HIVE_STYLE_PARTITIONING_OPT_KEY(),
Boolean.parseBoolean(DataSourceWriteOptions.DEFAULT_HIVE_STYLE_PARTITIONING_OPT_VAL()));
this.encodePartitionPath = props.getBoolean(DataSourceWriteOptions.URL_ENCODE_PARTITIONING_OPT_KEY(),
Boolean.parseBoolean(DataSourceWriteOptions.DEFAULT_URL_ENCODE_PARTITIONING_OPT_VAL()));
}
@Override
public String getRecordKey(GenericRecord record) {
return KeyGenUtils.getRecordKey(record, recordKeyField);
}
@Override
public String getPartitionPath(GenericRecord record) {
return KeyGenUtils.getPartitionPath(record, partitionPathField, hiveStylePartitioning, encodePartitionPath);
}
@Override
public List<String> getRecordKeyFields() {
return Arrays.asList(recordKeyField);
}
@Override
public List<String> getPartitionPathFields() {
return Arrays.asList(partitionPathField);
}
}
|
package ba.bitcamp.LabS09D05.generics;
import java.util.Collection;
/**
* Class ArrayList of Integers
*
* @author nermingraca
*
*/
public class ArrayList<T> {
private T[] array;
private int size;
private final int DEFAULT_SIZE = 1;
/**
* Constructor of object ArrayListInt, set to default values
*/
public ArrayList() {
this.array = (T[])(new Object[DEFAULT_SIZE]);
this.size = 0;
}
/**
* Getter of value size
* @return
*/
public int getSize() {
return size;
}
/**
* Method add variable value in to the array, also checks if array is full
* @param value = Integer which is put into the array
*/
public void add(T value) {
if (size == array.length) {
resize();
}
array[size] = value;
size++;
}
public void addAt(T value, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
for (int i = index; i < size; i++) {
array[i] = array[i+1];
}
size--;
}
/**
* Method removes element of array at given index
* @param index = Element in array which will be removed
*/
public void removeAt(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
for (int i = index; i < size; i++) {
array[i] = array[i+1];
}
size--;
}
/**
* Method to String for printing to console
*/
public String toString() {
String str = "[ ";
for (int i = 0; i <size -1; i++) {
str += array[i] + ", ";
}
return str += array[size -1] + " ]";
}
/**
* Method resizes array to double size of previous one
*/
private void resize() {
T[] temp = (T[])(new Object[size * 2]);
for (int i = 0; i < size; i++) {
temp[i] = array[i];
}
this.array = temp;
}
}
|
import javax.swing.*;
import java.awt.*;
public class FirstView extends JPanel {
private DefaultListModel<Student> listModel;
private JList<Student> list;
private StudentContainer container;
FirstView(StudentContainer container) {
this.container = container;
listModel = new DefaultListModel<Student>();
list = new JList<Student>(listModel);
this.setLayout(new BorderLayout());
this.add(list, BorderLayout.CENTER);
}
void update() {
listModel.removeAllElements();
container.stream().forEach(x -> listModel.addElement(x));
list.updateUI();
}
}
|
package com.ssgl.controller;
import com.ssgl.service.FacultyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/*
* 功能:
* User: jiajunkang
* email:jiajunkang@outlook.com
* Date: 2018/1/1 0001
* Time: 14:16
*/
@Controller
@RequestMapping("/faculty/")
public class FacultyController {
@Autowired
public FacultyService facultyService;
@ResponseBody
@RequestMapping(value = "selectAllFaculties",produces = "text/json;charset=utf-8")
public String selectAllFaculties(){
try {
return facultyService.selectAllFaculties();
}catch (Exception e){
throw new RuntimeException("出错了");
}
}
@ResponseBody
@RequestMapping(value = "selectAllFacultiesByFacultyId",produces = "text/json;charset=utf-8")
public String selectAllFacultiesByFacultyId(String facultyid){
try {
return facultyService.selectAllFacultiesByFacultyId(facultyid);
}catch (Exception e){
throw new RuntimeException("出错了");
}
}
}
|
package com.sharpower.action;
import com.opensymphony.xwork2.ActionSupport;
import com.sharpower.entity.Fun;
import com.sharpower.fun.control.FunControl;
import com.sharpower.scada.exception.PlcException;
public class AjaxFunControlAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private Fun fun;
private float limitVal;
private FunControl funControl;
private String result;
public Fun getFun() {
return fun;
}
public void setFun(Fun fun) {
this.fun = fun;
}
public float getLimitVal() {
return limitVal;
}
public void setLimitVal(float limitVal) {
this.limitVal = limitVal;
}
public FunControl getFunControl() {
return funControl;
}
public void setFunControl(FunControl funControl) {
this.funControl = funControl;
}
public String getResult() {
return result;
}
public String run(){
try {
funControl.run(fun);
result=fun.getName()+" 启动命令已下达。符合启动条件时风机自动启动。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 启动命令未执行:,"+e.getMessage();
return SUCCESS;
}
}
public String stop(){
try {
funControl.stop(fun);
result=fun.getName()+" 停机命令已执行。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 停机命令未执行,"+e.getMessage();
return SUCCESS;
}
}
public String reset(){
try {
funControl.reset(fun);
result=fun.getName()+" 复位命令已执行。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 复位命令未执行,"+e.getMessage();
return SUCCESS;
}
}
public String service(){
try {
funControl.service(fun);
result=fun.getName()+" 维护模式已执行。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 维护模式未执行,"+e.getMessage();
return SUCCESS;
}
}
public String powerLimit(){
try {
funControl.powerLimit(fun, limitVal);
result=fun.getName()+" 限功率命令已执行。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 限功率命令未执行,"+e.getMessage();
return SUCCESS;
}
}
public String powerLimitCancel(){
try {
funControl.powerLimitCancel(fun);
result=fun.getName()+" 取消功率限制已执行。";
return SUCCESS;
} catch (PlcException e) {
e.printStackTrace();
result=fun.getName()+" 取消功率限制未执行,"+e.getMessage();
return SUCCESS;
}
}
}
|
package com.trushil.aopdemo;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyDemoLoggingAspect {
@Pointcut("execution(* com.trushil.aopdemo.*.*(..))")
private void forDAOpackage() {
}
@Pointcut("execution(* com.trusihl.aopdemo.*.get*(..))")
private void removeGetLog() {
}
@Pointcut("execution(* com.trusihl.aopdemo.*.set*(..))")
private void removeSetLog() {
}
@Pointcut("forDAOpackage() && !(removeGetLog() || removeSetLog())")
private void methodLogging() {}
@Before("methodLogging()")
public void beforeAddAccount() {
System.out.println("============= Executing before add account");
}
}
|
/*
* Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights
* reserved. ParameterCSVC.java is PROPRIETARY/CONFIDENTIAL built in 2013. Use
* is subject to license terms.
*/
package com.frank.svm.config;
import java.util.Map.Entry;
import libsvm.svm_parameter;
import com.frank.math.SparseVector;
/**
* C-SVC: The configuration for standard support vector classification in cost
* parameter.
*
* @author <a href="mailto:jiangfan0576@gmail.com">Frank Jiang</a>
* @version 1.0.0
*/
public class ParameterCSVC extends AbstractParameter
{
/**
* The cost parameter {@code C}, {@code C}∈(0,+∞) (default 1.0).
*/
protected double cost;
/**
* The weights vector for cost.
* <p>
* The weights set the parameter C of class i to weight*C, for C-SVC.
* </p>
*/
protected SparseVector.Double weights;
/**
* Construct a default <tt>ParameterCSVC</tt>.
*/
public ParameterCSVC()
{
this(1.0, null);
}
/**
* Construct an instance of <tt>ParameterCSVC</tt> with specified cost
* parameter.
*
* @param cost
* the cost parameter {@code C}, {@code C}∈(0,+∞)
* (default 1.0)
*/
public ParameterCSVC(double cost)
{
this(cost, null);
}
/**
* Construct an instance of <tt>ParameterCSVC</tt> with weights vector.
*
* @param weights
* the weights vector
*/
public ParameterCSVC(SparseVector.Double weights)
{
this(1.0, weights);
}
/**
* Construct an instance of <tt>ParameterCSVC</tt> with specified cost
* parameter and weights vector.
*
* @param cost
* the cost parameter
* @param weights
* the weights vector
*/
public ParameterCSVC(double cost, SparseVector.Double weights)
{
setCost(cost);
svmType = svm_parameter.C_SVC;
this.weights = weights;
}
/**
* @see com.frank.svm.config.AbstractParameter#configParameter(libsvm.svm_parameter)
*/
protected void configParameter(svm_parameter param)
{
super.configParameter(param);
param.C = cost;
if (weights != null && !weights.isEmpty())
{
int size = weights.size();
param.weight = new double[size];
param.weight_label = new int[size];
int i = 0;
for (Entry<Integer, Double> e : weights.entrySet())
{
param.weight[i] = e.getValue();
param.weight_label[i] = e.getKey();
i++;
}
}
}
/**
* Returns the cost parameter {@code C}, {@code C}∈(0,+∞)
* (default 1.0).
*
* @return the cost parameter
*/
public double getCost()
{
return cost;
}
/**
* Set the cost parameter {@code C}, {@code C}∈(0,+∞) (default
* 1.0).
*
* @param cost
* the value of parameter {@code C}, {@code C}∈(0,+∞)
* (default 1.0)
*/
public void setCost(double cost)
{
if (cost <= 0)
throw new IllegalArgumentException(String.format(
"C(%g) must be positive.", cost));
this.cost = cost;
}
/**
* Returns the weights vector.
*
* @return the weights vector
*/
public SparseVector.Double getWeights()
{
return weights;
}
/**
* Set the weights vector.
* <p>
* The weights set the parameter C of class i to weight*C, for C-SVC. It can
* be null or empty, if need all 1.
* </p>
*
* @param weights
* the weights vector
*/
public void setWeights(SparseVector.Double weights)
{
this.weights = weights;
}
}
|
package org.codeshifts.spring.batch.reader.csv.person.accessor;
import org.codeshifts.spring.batch.reader.csv.person.PersonReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.stereotype.Component;
/**
* Created by werner.diwischek on 07.05.17.
*/
@Component
@StepScope
public class PersonReaderWithAccessor extends PersonReader<PersonAccessorBuilder> {
private static final Logger LOG = LoggerFactory.getLogger(PersonReaderWithAccessor.class);
public PersonReaderWithAccessor() {
super();
setLineMapper(new PersonLineMapper());
}
private class PersonLineMapper extends DefaultLineMapper<PersonAccessorBuilder> {
public PersonLineMapper() {
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(",");
tokenizer.setNames(PersonAccessorBuilder.FIELD_NAMES);
setLineTokenizer(tokenizer);
setFieldSetMapper(new PersonFieldSetMapper());
}
}
private class PersonFieldSetMapper implements FieldSetMapper<PersonAccessorBuilder> {
@Override
public PersonAccessorBuilder mapFieldSet(final FieldSet fieldSet) {
return new PersonAccessorBuilder(fieldSet);
}
}
}
|
package com.dev.hotelBiling;
public interface HotelInterface {
public HotelBill delete(int itemCode);
public HotelBill add(HotelBill h);
public String update(String foodName);
public double priceTotal(int foodItem, int count);
}
|
package kr.highthon.common.api;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
public class Error {
private String fieldName;
private String message;
public Error(String fieldName, String message) {
this.fieldName = fieldName;
this.message = message;
}
}
|
package ull.patrones.estrategia;
import ull.patrones.auxilares.Fecha;
public interface IEvento extends Runnable
{
public long getIdTipoEvento();
public Fecha getFecha();
public void start();
}
|
package com.gauro.rabbitmqfanoutexchangeconsumer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RabbitmqFanoutExchangeConsumerApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.zjh.design;
import com.zjh.design.store.ICommodity;
import com.zjh.design.store.impl.CouponCommodityService;
import com.zjh.design.store.impl.PhoneCommodityService;
import com.zjh.design.store.impl.ShoppingCardCommodityService;
/**
* @author : zhaojh
* @date : 2020/12/7 14:56
* @description :
*/
public class Store {
public ICommodity getCommodity(Integer type) throws Exception {
if (Integer.valueOf("1").equals(type)) {
return new CouponCommodityService();
}
if (Integer.valueOf("2").equals(type)) {
return new PhoneCommodityService();
}
if (Integer.valueOf("3").equals(type)) {
return new ShoppingCardCommodityService();
}
throw new Exception("没有该类型的奖品");
}
}
|
package com.ziroom.service;
import com.ziroom.dao.LogDAO;
import com.ziroom.entity.LogEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* <p></p>
* <p>
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhangxiuli
* @version 1.0
* @date 2018/10/9 18:30
* @since 1.0
*/
@Service("logService")
@Transactional
public class LogServiceImpl implements LogService {
@Autowired
private LogDAO logDAO;
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
@Override
public List<LogEntity> queryAll() {
return logDAO.queryAll();
}
}
|
import java.util.Scanner;
public class struct_array {
static int g_num;
static String g_name;
static String g_type;
int num;
String name;
String type;
public static boolean Search(String sc) {
//Scanner sc1 = new Scanner(System.in);
boolean flag = true;
int k = 0;
struct_array[] room = new struct_array[6] ;
for(int i = 0; i < room.length; i++){
room[i] = new struct_array();
}
room[0].num = 1;
room[0].name = "yamada";
room[0].type = "MeetingRoom";
room[1].num = 2;
room[1].name = "takahashi";
room[1].type = "Office";
room[2].num = 3;
room[2].name = "tanaka";
room[2].type = "Lab";
room[3].num = 4;
room[3].name = "Tom";
room[3].type = "Office";
room[4].num = 5;
room[4].name = "motoda";
room[4].type = "Office";
room[5].num = 100;
room[5].name = "Lin";
room[5].type = "Lab";
// while(flag){
System.out.println("部屋番号を入力してください:");
String room_num = sc;
Integer answer = null;
try {
answer = Integer.parseInt(room_num);
} catch (NumberFormatException e) {
System.out.println("入力に間違いがあった!");
//sc.nextLine();
//continue;
return false;
}
for(int j = 0; j < room.length; j++){
if(room[j].num == answer)
{ k=1;
g_num = room[j].num;
g_name = room[j].name;
g_type = room[j].type;
System.out.println(room[j].num +"---"+ room[j].name +"---"+ room[j].type);
// flag=false;
//break;
}
//else continue;
}
if(k == 0){
System.out.println("この部屋が存在しない"); //room[i] = new struct_array();
return false;
}
// }
return true;
}
}
|
package com.example.duy.thread_asyntask_handler;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by duy on 29/05/2017.
*/
public class AsnycTask extends AsyncTask<Void , Integer ,Void> {
private Activity activity;
public AsnycTask(Activity activity) {
this.activity = activity;
}
@Override
protected void onPreExecute() { // hàm khởi tạo khi bắt đầu tiến
super.onPreExecute();
Toast.makeText(activity,"Start",Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(Void... params) {
for(int i = 0;i<=100;i++){
SystemClock.sleep(500);
publishProgress(i);
}
return null;
}
// hàm gọi khi kết thúc tiến
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(activity,"Game Over",Toast.LENGTH_SHORT).show();
}
//cập nhật giao diện lúc run time
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//đối số truyền vào values là một giá trị integer nên chỉ có 1 phần tử
int percent = values[0];
//set giá trị phần trăm cho progres bar
((ProgressBar)activity.findViewById(R.id.id_pro)).setProgress(percent);
//set gia trị phần trăm cho Text view
((TextView)activity.findViewById(R.id.id_async)).setText(percent+"%");
}
}
|
package br.com.cc.varzeafc.controllers;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.cc.varzeafc.conf.UsuarioSistema;
import br.com.cc.varzeafc.daos.EquipeDAO;
import br.com.cc.varzeafc.daos.UsuarioDAO;
import br.com.cc.varzeafc.models.Campeonato;
import br.com.cc.varzeafc.models.Equipe;
import br.com.cc.varzeafc.models.Grupo;
import br.com.cc.varzeafc.models.Presidente;
import br.com.cc.varzeafc.models.Usuario;
@Controller
@Transactional
@RequestMapping("/")
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class HomeController {
@Autowired
private UsuarioDAO usuarioDAO;
@Autowired
private EquipeDAO equipeDAO;
@RequestMapping(method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView view = new ModelAndView("index");
Equipe equipe = equipeDAO.buscaEquipePorIdPresidente(getUsuarioLogado().getId());
Campeonato campeonatoAberto = equipe.buscaCampeonatoAberto();
view.addObject("equipe", campeonatoAberto.getNome());
return view;
}
@RequestMapping("add")
public String addAdm() {
Usuario usuario = new Usuario();
List<Grupo> grupos = new ArrayList<>();
Grupo grupo = new Grupo();
grupo.setId(1);
grupos.add(grupo);
usuario.setGrupos(grupos);
usuario.setLogin("thiago");
usuario.setSenha(new BCryptPasswordEncoder().encode("123"));
usuarioDAO.salva(usuario);
return "redirect:/login";
}
@RequestMapping(method = RequestMethod.GET, value = "login")
public ModelAndView login() {
return new ModelAndView("login/login");
}
@RequestMapping(method = RequestMethod.GET, value = "cadastro")
public ModelAndView cadastro(Presidente presidente) {
return new ModelAndView("cadastro");
}
@RequestMapping(method = RequestMethod.POST, value = "usuario/add")
public ModelAndView addPresidente(@Valid Presidente presidente, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return cadastro(presidente);
}
presidente.setGrupos(addGrupo());
presidente.getEquipe().setDataCriacao(Calendar.getInstance());
presidente.setSenha(presidente.criptografarSenha(presidente.getSenha()));
presidente.getEquipe().setPresidente(presidente);
usuarioDAO.salva(presidente);
redirectAttributes.addFlashAttribute("mensagem", "Cadastro realizado com sucesso.");
return new ModelAndView("redirect:/login");
}
private List<Grupo> addGrupo() {
Grupo grupo = new Grupo();
List<Grupo> grupos = new ArrayList<>();
grupo.setId(2);
grupos.add(grupo);
return grupos;
}
@RequestMapping("/varzeafc")
public ModelAndView varzeaFc() {
ModelAndView view = new ModelAndView("varzeafc/home/index");
Equipe equipe = equipeDAO.buscaEquipePorIdPresidente(getUsuarioLogado().getId());
Campeonato campeonatoAberto = equipe.buscaCampeonatoAberto();
view.addObject("equipe", equipe.getNome());
return view;
}
private UsuarioSistema getUsuarioLogado() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UsuarioSistema usuario = (UsuarioSistema) auth.getPrincipal();
return usuario;
}
}
|
package WebBot;
import java.io.Serializable;
public class Account implements Serializable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
private String name;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.name = firstName + "+" + this.lastName;
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.name = this.firstName + "+" + lastName;
this.lastName = lastName;
}
private String firstName;
private String lastName;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
email = email.replace("@", "%40");
this.email = email;
}
private String tel;
private String address;
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
String[] parts = address.split("\\s+");
for(int i= 0; i <parts.length; i++) {
if(i>0) {
parts[i] = parts[i-1] + "+" + parts[i];
address = parts[i];
}
}
this.address = address;
}
private String apt;
private String zip;
private String city;
private String state;
private String country;
private String page;
private String number;
public String getApt() {
return apt;
}
public void setApt(String apt) {
this.apt = apt;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
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;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
String[] parts = number.split("\\s+");
for(int i= 0; i <parts.length; i++) {
if(i>0) {
parts[i] = parts[i-1] + "+" + parts[i];
number = parts[i];
}
}
this.number = number;
}
private String month;
private String year;
private String cvv;
private int hour;
private int minute;
private int seconds;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.time = hour*3600000+ this.minute* 60000 + this.seconds* 1000;
System.out.println(this.time);
this.hour = hour;
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.time = this.hour*3600000+ minute* 60000 + this.seconds* 1000;
System.out.println(this.time);
this.minute = minute;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.time = this.hour*3600000+ this.minute* 60000 + seconds* 1000;
System.out.println(this.time);
this.seconds = seconds;
}
private int time;
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String title;
}
|
package ac.kr.ajou.dirt;
class DirtySample {
Item[] items;
public DirtySample(Item[] items) { this.items = items; }
public void updateQuality() {
for (Item item : items) {
if (!item.name.equals("Sulfuras, Hand of Ragnaros")) { item.sellIn -= 1; }
if (item.name.equals("Aged Brie")) {
increaseOneItemQuality(item);
if (item.sellIn < 0) { increaseOneItemQuality(item); }
} else if (item.name.equals("Backstage passes to a TAFKAL80ETC concert")) {
increaseOneItemQuality(item);
if (item.sellIn < 11) { increaseOneItemQuality(item); }
if (item.sellIn < 6) { increaseOneItemQuality(item); }
if (item.sellIn < 0) { item.quality = 0; }
} else if (item.name.equals("Sulfuras, Hand of Ragnaros")) {
} else {
decreaseOneItemQuality(item);
if (item.sellIn < 0) { decreaseOneItemQuality(item); }
}
}
}
private void increaseOneItemQuality(Item item) {
if (item.quality < 50) { item.quality += 1; }
}
private void decreaseOneItemQuality(Item item) {
if (item.quality > 0) { item.quality -= 1; }
}
}
|
package com.accp.domain;
public class Staff {
private String sid;
private String sname;
private String ssex;
private Integer shpid;
private Integer detid;
private String susername;
private Integer stnid;
private String sbody;
private String sheight;
private String snative;
private String snation;
private String smarriage;
private String seducation;
private String sschool;
private String smajor;
private String sstatus;
private String sproperty;
private String sdegree;
private String sauthorized;
private String sidentity;
private String sregistered;
private String spresent;
private String sphone;
private String snumber;
private String semail;
private String sbank;
private String sbankaccount;
private String surgency;
private String surgencyphone;
private String shiredate;
private String sexpiration;
private String sbirth;
private String sstart;
private String sfinish;
private String sselfmotion;
private String sinterior;
private String sreferrer;
private String selement;
private String stime;
private String scommodity;
private String mitigate;
private String sphotopath;
private String smitigate;
private String seducations;
private String sfamily;
private String sreward;
private String sopinion;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
public Integer getShpid() {
return shpid;
}
public void setShpid(Integer shpid) {
this.shpid = shpid;
}
public Integer getDetid() {
return detid;
}
public void setDetid(Integer detid) {
this.detid = detid;
}
public String getSusername() {
return susername;
}
public void setSusername(String susername) {
this.susername = susername;
}
public Integer getStnid() {
return stnid;
}
public void setStnid(Integer stnid) {
this.stnid = stnid;
}
public String getSbody() {
return sbody;
}
public void setSbody(String sbody) {
this.sbody = sbody;
}
public String getSheight() {
return sheight;
}
public void setSheight(String sheight) {
this.sheight = sheight;
}
public String getSnative() {
return snative;
}
public void setSnative(String snative) {
this.snative = snative;
}
public String getSnation() {
return snation;
}
public void setSnation(String snation) {
this.snation = snation;
}
public String getSmarriage() {
return smarriage;
}
public void setSmarriage(String smarriage) {
this.smarriage = smarriage;
}
public String getSeducation() {
return seducation;
}
public void setSeducation(String seducation) {
this.seducation = seducation;
}
public String getSschool() {
return sschool;
}
public void setSschool(String sschool) {
this.sschool = sschool;
}
public String getSmajor() {
return smajor;
}
public void setSmajor(String smajor) {
this.smajor = smajor;
}
public String getSstatus() {
return sstatus;
}
public void setSstatus(String sstatus) {
this.sstatus = sstatus;
}
public String getSproperty() {
return sproperty;
}
public void setSproperty(String sproperty) {
this.sproperty = sproperty;
}
public String getSdegree() {
return sdegree;
}
public void setSdegree(String sdegree) {
this.sdegree = sdegree;
}
public String getSauthorized() {
return sauthorized;
}
public void setSauthorized(String sauthorized) {
this.sauthorized = sauthorized;
}
public String getSidentity() {
return sidentity;
}
public void setSidentity(String sidentity) {
this.sidentity = sidentity;
}
public String getSregistered() {
return sregistered;
}
public void setSregistered(String sregistered) {
this.sregistered = sregistered;
}
public String getSpresent() {
return spresent;
}
public void setSpresent(String spresent) {
this.spresent = spresent;
}
public String getSphone() {
return sphone;
}
public void setSphone(String sphone) {
this.sphone = sphone;
}
public String getSnumber() {
return snumber;
}
public void setSnumber(String snumber) {
this.snumber = snumber;
}
public String getSemail() {
return semail;
}
public void setSemail(String semail) {
this.semail = semail;
}
public String getSbank() {
return sbank;
}
public void setSbank(String sbank) {
this.sbank = sbank;
}
public String getSbankaccount() {
return sbankaccount;
}
public void setSbankaccount(String sbankaccount) {
this.sbankaccount = sbankaccount;
}
public String getSurgency() {
return surgency;
}
public void setSurgency(String surgency) {
this.surgency = surgency;
}
public String getSurgencyphone() {
return surgencyphone;
}
public void setSurgencyphone(String surgencyphone) {
this.surgencyphone = surgencyphone;
}
public String getShiredate() {
return shiredate;
}
public void setShiredate(String shiredate) {
this.shiredate = shiredate;
}
public String getSexpiration() {
return sexpiration;
}
public void setSexpiration(String sexpiration) {
this.sexpiration = sexpiration;
}
public String getSbirth() {
return sbirth;
}
public void setSbirth(String sbirth) {
this.sbirth = sbirth;
}
public String getSstart() {
return sstart;
}
public void setSstart(String sstart) {
this.sstart = sstart;
}
public String getSfinish() {
return sfinish;
}
public void setSfinish(String sfinish) {
this.sfinish = sfinish;
}
public String getSselfmotion() {
return sselfmotion;
}
public void setSselfmotion(String sselfmotion) {
this.sselfmotion = sselfmotion;
}
public String getSinterior() {
return sinterior;
}
public void setSinterior(String sinterior) {
this.sinterior = sinterior;
}
public String getSreferrer() {
return sreferrer;
}
public void setSreferrer(String sreferrer) {
this.sreferrer = sreferrer;
}
public String getSelement() {
return selement;
}
public void setSelement(String selement) {
this.selement = selement;
}
public String getStime() {
return stime;
}
public void setStime(String stime) {
this.stime = stime;
}
public String getScommodity() {
return scommodity;
}
public void setScommodity(String scommodity) {
this.scommodity = scommodity;
}
public String getMitigate() {
return mitigate;
}
public void setMitigate(String mitigate) {
this.mitigate = mitigate;
}
public String getSphotopath() {
return sphotopath;
}
public void setSphotopath(String sphotopath) {
this.sphotopath = sphotopath;
}
public String getSmitigate() {
return smitigate;
}
public void setSmitigate(String smitigate) {
this.smitigate = smitigate;
}
public String getSeducations() {
return seducations;
}
public void setSeducations(String seducations) {
this.seducations = seducations;
}
public String getSfamily() {
return sfamily;
}
public void setSfamily(String sfamily) {
this.sfamily = sfamily;
}
public String getSreward() {
return sreward;
}
public void setSreward(String sreward) {
this.sreward = sreward;
}
public String getSopinion() {
return sopinion;
}
public void setSopinion(String sopinion) {
this.sopinion = sopinion;
}
}
|
package mando.sirius.bot.commands.discord.habbo;
import com.eu.habbo.Emulator;
import mando.sirius.bot.Sirius;
import mando.sirius.bot.structures.Command;
import mando.sirius.bot.structures.SiriusUser;
import net.dv8tion.jda.api.entities.Message;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class OnlinesCommand extends Command {
public OnlinesCommand() {
super("online", "a", new String[]{"onlines", "userson"}, new String[]{}, false);
}
@Override
public boolean execute(@Nonnull Message message, @Nullable SiriusUser selfUser, String... args) {
if (Emulator.getGameEnvironment().getHabboManager().getOnlineCount() > 0)
message.getChannel().sendMessage(Sirius.getTexts().getValue("sirius.bot.cmd_onlines.sucess")
.replace("%players%", String.valueOf(Emulator.getGameEnvironment().getHabboManager().getOnlineCount()))).queue();
else
message.getChannel().sendMessage(Sirius.getTexts().getValue("sirius.bot.cmd_onlines.no_users")).queue();
return true;
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.extrt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vanadis.core.collections.Generic;
import vanadis.core.lang.ToString;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
final class DependencyTracker<T extends ManagedFeature<?,?>> implements Iterable<T> {
private static final Logger log = LoggerFactory.getLogger(DependencyTracker.class);
private final Set<String> complete = Generic.set();
private final Set<String> requiredIncomplete = Generic.set();
private final Set<String> incomplete = Generic.set();
private final Map<String, T> trackees = Generic.map();
public T track(T trackee) {
if (trackee.isComplete()) {
throw new IllegalStateException(this + " is already complete");
}
String name = trackee.getFeatureName();
if (trackees.containsKey(name)) {
throw new IllegalArgumentException
(this + " failed to setup injectorDependencyTracker, duplicate injection: " + name);
}
trackees.put(name, trackee);
if (trackee.isRequired()) {
requiredIncomplete.add(name);
}
incomplete.add(name);
return trackee;
}
public boolean isTracking(String featureName) {
return trackees.containsKey(featureName);
}
public void progress(String name) {
checkArgument(name);
if (incomplete.contains(name) && trackee(name).isComplete()) {
incomplete.remove(name);
requiredIncomplete.remove(name);
complete.add(name);
if (log.isDebugEnabled()) {
log.debug(this + " completed " + name);
}
} else {
if (log.isDebugEnabled()) {
log.debug(this + " progressing: " + name);
}
}
}
public T setback(String name) {
checkArgument(name);
T trackee = trackee(name);
if (complete.contains(name) && !trackee.isComplete()) {
complete.remove(name);
incomplete.add(name);
if (trackee.isRequired()) {
requiredIncomplete.add(name);
}
return trackees.get(name);
}
return null;
}
@Override
public Iterator<T> iterator() {
return trackees.values().iterator();
}
public Iterable<T> requiredIncomplete() {
return trackees(requiredIncomplete);
}
public Iterable<T> incomplete() {
return trackees(incomplete);
}
public Iterable<T> complete() {
return trackees(complete);
}
public Collection<String> completeNames() {
return complete;
}
public boolean isRequiredComplete() {
return requiredIncomplete.isEmpty();
}
public void reset() {
complete.clear();
requiredIncomplete.clear();
incomplete.clear();
trackees.clear();
}
private T trackee(String name) {
return trackees.get(name);
}
private Iterable<T> trackees(Collection<String> names) {
Collection<T> inc = Generic.list(names.size());
for (String name : names) {
inc.add(trackee(name));
}
return inc;
}
private void checkArgument(String name) {
if (!trackees.containsKey(name)) {
throw new IllegalStateException("Unknown property: " + name);
}
}
@Override
public String toString() {
return ToString.of(this, "tracking", trackees.keySet(),
"complete", complete.size(),
"requiredIncomplete", requiredIncomplete.size(),
"incomplete", incomplete.size());
}
}
|
package com.voksel.electric.pc.security;
import com.voksel.electric.pc.component.MenuTreeItem;
import com.voksel.electric.pc.domain.entity.Role;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.Collection;
public interface AuthenticationService extends UserDetailsService{
Collection<MenuTreeItem> loadMenuItems();
Collection<MenuTreeItem> loadMenuItemsByRole(String role);
}
|
import java.util.Arrays;
import java.util.Scanner;
public class Random23 {
public static int findMinWeight(int[] arr, int k) {
int all = 0;
int n = arr.length;
int sum = 0;
for(int i=0;i<n;i++) {
all+=arr[i];
}
Arrays.sort(arr);
k = Math.min(k,n-k);
for(int i=0;i<k;i++)
sum+=arr[i];
return all-2*sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter");
int t = scanner.nextInt();
while(t-->0) {
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = scanner.nextInt();
System.out.println(findMinWeight(arr,k));
}
scanner.close();
}
}
|
package com.weigs.singleton;
/**
* @author weigs
* @date 2017/7/1 0001
*/
public class SingleObjectTest {
public static void main(String[] args) {
SingleObject singleObject1 = SingleObject.getSingleObject();
SingleObject singleObject2 = SingleObject.getSingleObject();
if (singleObject1 == singleObject2) {
System.out.println("相同");
}
}
}
|
package com.tencent.mm.plugin.emoji.f;
import com.tencent.map.lib.gl.model.GLIcon;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.plugin.emoji.model.i;
import com.tencent.mm.protocal.c.adi;
import com.tencent.mm.protocal.c.adj;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class o extends l implements k {
public static int iiS = 0;
public static int iiT = 1;
public static int iiU = 1;
public static int iiV = 2;
public static int iiW = GLIcon.TOP;
private final b diG;
private e diJ;
private int iiX;
private String iil;
public o(String str, int i) {
a aVar = new a();
aVar.dIG = new adi();
aVar.dIH = new adj();
aVar.uri = "/cgi-bin/micromsg-bin/mmgetemotionreward";
aVar.dIF = 822;
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
this.iil = str;
this.iiX = i;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.emoji.NetSceneGetEmotionReward", "errType:%d, errCode:%d", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3)});
if (i2 == 0 && i3 == 0) {
if (this.iiX == iiS) {
com.tencent.mm.storage.emotion.l lVar = i.aEA().igC;
String str2 = this.iil;
adj aES = aES();
if (bi.oW(str2) || aES == null) {
x.w("MicroMsg.emoji.EmotionRewardInfoStorage", "saveEmotionRewardResponseWithPID failed. productId or response is null.");
} else {
try {
com.tencent.mm.storage.emotion.k kVar = new com.tencent.mm.storage.emotion.k();
kVar.field_productID = str2;
kVar.field_content = aES.toByteArray();
if (lVar.diF.replace("EmotionRewardInfo", "productID", kVar.wH()) > 0) {
x.i("MicroMsg.emoji.EmotionRewardInfoStorage", "saveEmotionRewardResponseWithPID success. ProductId:%s", new Object[]{str2});
} else {
x.i("MicroMsg.emoji.EmotionRewardInfoStorage", "saveEmotionRewardResponseWithPID failed. ProductId:%s", new Object[]{str2});
}
} catch (Throwable e) {
x.e("MicroMsg.emoji.EmotionRewardInfoStorage", "saveEmotionRewardResponseWithPID exception:%s", new Object[]{bi.i(e)});
}
}
}
if (aES() == null || aES().rHP == null) {
x.i("MicroMsg.emoji.NetSceneGetEmotionReward", "getEmotionRewardRespone is null. so i think no such product reward information");
i.aEA().igE.dg(this.iil, iiW);
i.aEB().bh(this.iil, iiW);
} else {
i.aEA().igE.dg(this.iil, aES().rHP.rbZ);
i.aEB().bh(this.iil, aES().rHP.rbZ);
}
} else if (i3 == 1) {
i.aEA().igE.dg(this.iil, iiW);
i.aEB().bh(this.iil, iiW);
}
this.diJ.a(i2, i3, str, this);
}
public final int getType() {
return 822;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
adi adi = (adi) this.diG.dID.dIL;
adi.rem = this.iil;
adi.qZc = this.iiX;
return a(eVar, this.diG, this);
}
public final adj aES() {
return (adj) this.diG.dIE.dIL;
}
}
|
package com.example.raghav.multilibrariesproject.mvp;
/**
* Created by raghav on 9/26/16.
*/
public interface IEmployeeDetailInteractor
{
void getEmployeeDetais();
void setPresenter(IEmployeePresenter employeePresenter);
}
|
package com.stem.entity;
public class TigerOpt {
private Integer id;
private String optName;
private String optCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOptName() {
return optName;
}
public void setOptName(String optName) {
this.optName = optName;
}
public String getOptCode() {
return optCode;
}
public void setOptCode(String optCode) {
this.optCode = optCode;
}
}
|
package com.openclassrooms.KatzenheimLibrariesApp.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.openclassrooms.KatzenheimLibrariesApp.entities.Borrow;
import com.openclassrooms.KatzenheimLibrariesApp.entities.LibraryUser;
import com.openclassrooms.KatzenheimLibrariesApp.service.BorrowService;
import com.openclassrooms.KatzenheimLibrariesApp.service.LibraryUserService;
@Controller
public class IdentificateAccountController {
@Autowired
LibraryUserService libraryUserService;
@Autowired
BorrowService borrowService;
private final Logger logger = LoggerFactory.getLogger(BooksListAndFormController.class);
private UserDetails userDetails;
private LibraryUser currentLibraryUser;
private ModelAndView mav;
private void libraryUserAuthentication(Authentication authentication) {
userDetails = (UserDetails) authentication.getPrincipal();
logger.info("userDetails" + userDetails.getUsername());
currentLibraryUser = libraryUserService.findLibraryUserByEmail(userDetails.getUsername());
logger.info("currentLibraryUser"+ currentLibraryUser.getFirstName());
}
@RequestMapping(value ="/identification",method = RequestMethod.GET)
@ResponseBody
public ModelAndView showLoginForm() {
logger.info("HTTP GET request received at /identification in showLoginForm");
mav = new ModelAndView("identification");
return mav;
}
@RequestMapping(value ="/monCompte",method = RequestMethod.GET)
@ResponseBody
public ModelAndView showLibraryUserInfos (Authentication authentication, ModelMap modelMap) {
logger.info("HTTP GET request received at /monCompte in showLibraryUserInfos");
libraryUserAuthentication(authentication);
modelMap.addAttribute("userDetails", userDetails);
modelMap.addAttribute("currentLibraryUser", currentLibraryUser);
modelMap.addAttribute("borrows", currentLibraryUser.getBorrows());
mav = new ModelAndView("monCompte");
return mav;
}
@RequestMapping(value ="/modifierMonCompte",method = RequestMethod.GET)
@ResponseBody
public ModelAndView editLibraryUserInfos(Model model) {
logger.info("HTTP GET request received at /monCompte in editLibraryUserInfos");
model.addAttribute("userDetails", userDetails);
model.addAttribute("currentLibraryUser", currentLibraryUser);
mav = new ModelAndView("modifierMonCompte");
return mav;
}
@RequestMapping(value ="/modifierMonCompteInfosPerso",method = RequestMethod.POST)
@ResponseBody
public ModelAndView editLibraryUserInfos(String firstName, String lastName, String address, String phone) {
logger.info("HTTP POST request received at /monCompte in editLibraryUserInfos");
libraryUserService.libraryUserInfosModification(currentLibraryUser,firstName,lastName,address,phone);
mav = new ModelAndView("redirect:/monCompte");
return mav;
}
@RequestMapping(value ="/modifierMonMotDePasse",method = RequestMethod.POST)
@ResponseBody
public ModelAndView editLibraryUserPassword(String password) {
logger.info("HTTP POST request received at /monCompte in editLibraryUserInfos");
libraryUserService.libraryUserPasswordModification(currentLibraryUser, password);
mav = new ModelAndView("redirect:/monCompte");
return mav;
}
@RequestMapping(value ="/modifierMonAdresseEmail",method = RequestMethod.POST)
@ResponseBody
public ModelAndView editLibraryUserEmail(Authentication authentication,String email) {
logger.info("HTTP POST request received at /monCompte in editLibraryUserInfos");
libraryUserAuthentication(authentication);
libraryUserService.libraryUserEmailModification(currentLibraryUser, email);
mav = new ModelAndView("redirect:/logout");
return mav;
}
@RequestMapping(value ="/prolongerUnLivre",method = RequestMethod.GET)
@ResponseBody
public ModelAndView extendABorrow(Integer id) {
logger.info("HTTP GET request received at /monCompte in extendABorrow");
Borrow borrow = borrowService.findOneBorrowById(id);
if(borrow.isAlreadyExtended()==true){
mav = new ModelAndView("redirect:/monCompte");
return mav;
} else {
borrowService.extendBorrow(borrow);
}
mav = new ModelAndView("redirect:/monCompte");
return mav;
}
}
|
package com.app.main.dto;
import java.io.Serializable;
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.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String userEmail;
private String userName;
private long userPhoneNumber;
private String userAdddress;
private String userPassword;
private String userDob;
private String typeOfUser;
/*
* @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy =
* "userEmail") private Order1 order;
*/
public User() {
super();
}
public User(String userEmail, String userName, long userPhoneNumber, String userAdddress, String userPassword,
String userDob, String typeOfUser) {
super();
this.userEmail = userEmail;
this.userName = userName;
this.userPhoneNumber = userPhoneNumber;
this.userAdddress = userAdddress;
this.userPassword = userPassword;
this.userDob = userDob;
this.typeOfUser = typeOfUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public long getUserPhoneNumber() {
return userPhoneNumber;
}
public void setUserPhoneNumber(long userPhoneNumber) {
this.userPhoneNumber = userPhoneNumber;
}
public String getUserAdddress() {
return userAdddress;
}
public void setUserAdddress(String userAdddress) {
this.userAdddress = userAdddress;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserDob() {
return userDob;
}
public void setUserDob(String userDob) {
this.userDob = userDob;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
@Override
public String toString() {
return "User [userEmail=" + userEmail + ", userName=" + userName + ", userPhoneNumber=" + userPhoneNumber
+ ", userAdddress=" + userAdddress + ", userPassword=" + userPassword + ", userDob=" + userDob
+ ", typeOfUser=" + typeOfUser + "]";
}
}
|
// Tests that incompatible variable assigns in functions error.
int main() {
return 0;
}
int f(IncompatClassFuncParamAssignClass1 a) {
a = new IncompatClassFuncParamAssignClass2();
return 0;
}
class IncompatClassFuncParamAssignClass1 {
}
class IncompatClassFuncParamAssignClass2 {
}
|
/**
* Bitcoind
* The REST API can be enabled with the `-rest` option. The interface runs on the same port as the JSON-RPC interface, by default port `8332` for **mainnet**, port `18332` for **testnet**, and port `18443` for **regtest**.
*
* OpenAPI spec version: 0.16
* Contact: johan@lepetitbloc.net
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import io.swagger.client.model.BIPReject;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class BIP {
@SerializedName("id")
private String id = null;
@SerializedName("version")
private Integer version = null;
@SerializedName("reject")
private BIPReject reject = null;
/**
* The BIP number, or ? before being assigned
**/
@ApiModelProperty(value = "The BIP number, or ? before being assigned")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* The BIP version number
**/
@ApiModelProperty(value = "The BIP version number")
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
/**
**/
@ApiModelProperty(value = "")
public BIPReject getReject() {
return reject;
}
public void setReject(BIPReject reject) {
this.reject = reject;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BIP BIP = (BIP) o;
return (this.id == null ? BIP.id == null : this.id.equals(BIP.id)) &&
(this.version == null ? BIP.version == null : this.version.equals(BIP.version)) &&
(this.reject == null ? BIP.reject == null : this.reject.equals(BIP.reject));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.id == null ? 0: this.id.hashCode());
result = 31 * result + (this.version == null ? 0: this.version.hashCode());
result = 31 * result + (this.reject == null ? 0: this.reject.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BIP {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" version: ").append(version).append("\n");
sb.append(" reject: ").append(reject).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
package petko.osm.model.facade;
import java.util.List;
public interface OsmDataStore {
public List<OsmNode> getNodes();
public List<OsmRelation> getRelations();
public List<OsmWay> getWays();
}
|
package com.tencent.mm.model;
import java.util.List;
public interface ai {
List<ah> getDataTransferList();
}
|
package enthu_l;
public class e_1099 {
public static void main(String args[]){
int x = 0;
labelA: for (int i=10; i<0; i--){
int j = 0;
labelB:
while (j < 10){
if (j > i) break labelB;
if (i == j){
x++;
continue labelA;
}
j++;
}
x--;
}
System.out.println(x);
}
}
|
package com.caicai.dao;
import com.caicai.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserDao {
Integer createUser(User user);
User getUserById(@Param("id") Integer id);
}
|
package com.gotkx.utils.bubbleSort;
public class bubbleSortImp {
public static void main(String[] args) {
int[] nums = {1, 9, 5, 7, 9, 2, 10, 14, 8, 77, 66, 99};
long startTime = System.currentTimeMillis();
bubbleSort(nums);
long endTime = System.currentTimeMillis();
//System.out.println("总耗时:" + (endTime - startTime) + "ms");
for (int i = 0; i < nums.length; i++) {
if (i == nums.length - 1) {
System.out.print(nums[i]);
} else {
System.out.print(nums[i] + ", ");
}
}
}
public static void bubbleSort(int[] nums) {
int j, k,count = 0;
int flag = nums.length;
while (flag > 0) {
count++;
//System.out.println("执行while的次数:" +count);
//System.out.println("边界值: " + flag);
k = flag;
flag = 0;
for (j = 1; j < k; j++) {
System.out.println("K 值" + k);
//System.out.println("进入for循环");
// 前面的数字大于后面的数字就交换
if (nums[j - 1] > nums[j]) {
System.out.println("前一个值:" + nums[j - 1] + "后一个值:"+nums[j]);
// 交换a[j-1]和a[j]
int temp;
temp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = temp;
// 表示交换过数据;
flag = j;// 记录最新的尾边界.
System.out.println("最新边界值: " + flag);
}
}
System.out.println("结束for循环: " + count);
}
}
}
|
package cn.czfshine.network.project.cs.dto;
import lombok.Data;
import java.io.Serializable;
/**登出消息
* @author:czfshine
* @date:2019/4/4 13:57
*/
@Data
public class Logout implements Serializable {
private String username;
}
|
package com.sneaker.mall.api.task.impl;
import com.google.common.base.Strings;
import com.sneaker.mall.api.dao.info.GeoLocationDao;
import com.sneaker.mall.api.model.GeoLocation;
import com.sneaker.mall.api.task.Task;
import com.sneaker.mall.api.util.BaiduLocationUtil;
import com.sneaker.mall.api.util.Gps2BaiDu;
import com.sneaker.mall.api.util.geo.GeoBaidu;
import com.sneaker.mall.api.util.geo.GeoPoint;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
* 将经维图信息转换成地图位置信息
*/
public class AnalysisGeoLocation extends Task {
@Autowired
private GeoLocationDao geoLocationDao;
@Autowired
private BaiduLocationUtil baiduLocationUtil;
@Override
public void run() {
List<GeoLocation> geoLocations = this.geoLocationDao.findNoBaiduAddress();
if (geoLocations != null && geoLocations.size() > 0) {
//更新地址信息
geoLocations.stream().forEach(geoLocation -> {
String x = null;
String y = null;
String address = null;
//转换成获取百度地址
if (!Strings.isNullOrEmpty(geoLocation.getLatitude()) && !Strings.isNullOrEmpty(geoLocation.getLonggitude())) {
x = geoLocation.getLatitude();
y = geoLocation.getLonggitude();
if (x.length() > 9) x = x.substring(0, 9);
if (y.length() > 10) y = y.substring(0, 10);
GeoPoint geoPoint = Gps2BaiDu.getBaiduGeoPoint(x, y);
if (geoPoint != null) {
x = String.valueOf(geoPoint.getX());
y = String.valueOf(geoPoint.getY());
GeoBaidu geoBaidu = this.baiduLocationUtil.analysis(y, x);
if (geoBaidu == null) {
address = "服务器无法解析地址";
} else {
address = geoBaidu.getResult().getFormatted_address();
}
} else {
address = "无法将GPS数据转换为百度坐标";
}
} else {
address = "地址无法解析";
}
this.geoLocationDao.updateBaiduAddress(address, geoLocation.getId(), x, y);
});
}
}
}
|
package com.zjm.design.d16_iterator;
public class ListCollection implements CollectionTest {
public String string[] = {"A","B","C","D","E"};
@Override
public ItratorTest iterator() {
return new ListIterator(this);
}
@Override
public Object get(int i) {
return string[i];
}
@Override
public int size() {
return string.length;
}
}
|
package com.witt.norm;
/**
*
* 见名知意
* 驼峰命名
* 不能用关键字
* */
public class SysMonitoring {
private boolean flag = true;
// 首字母小写
public void fileExist(){
//...
}
}
|
package com.jadn.cc.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.jadn.cc.R;
import com.jadn.cc.core.CarCastApplication;
import com.jadn.cc.core.Config;
import com.jadn.cc.util.Updater;
public class DownloadProgress extends BaseActivity implements Runnable {
final Handler handler = new Handler();
Updater updater;
@Override
protected void onContentService() {
String status = contentService.encodedDownloadStatus();
boolean idle = false;
if (status.equals("")) {
idle = true;
} else {
if (status.split(",")[0].equals("done")) {
idle = true;
}
}
Button startDownloads = (Button) findViewById(R.id.startDownloads);
Button abort = (Button) findViewById(R.id.AbortDownloads);
startDownloads.setEnabled(idle);
abort.setEnabled(!idle);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_progress);
final Button startDownloads = (Button) findViewById(R.id.startDownloads);
startDownloads.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(DownloadProgress.this);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (app_preferences.getBoolean("wifiDownload", true) && (!wifi.isWifiEnabled() || wifi.getConnectionInfo().getIpAddress() == 0)
&& app_preferences.getBoolean("wifiWarning", true)
) {
String title = "WIFI is not enabled.";
if (wifi.getConnectionInfo().getIpAddress() == 0) title = "WIFI is not connected.";
new AlertDialog.Builder(DownloadProgress.this).setTitle(title).setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Do you want to use your carrier? You may use up your data plan's bandwidth allocation or incur overage charges...")
.setNegativeButton("Yikes, no", null).setPositiveButton("Sure, go ahead", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doDownloads();
}
}).show();
} else {
//either WIFI is enabled or settings indicate WIFI is not required for auto download, so go ahead
doDownloads();
}
}
});
final Button abort = (Button) findViewById(R.id.AbortDownloads);
abort.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
mNotificationManager.cancel(22);
mNotificationManager.cancel(23);
// Crude... but effective...
System.exit(-1);
}
});
final Button downloadDetails = (Button) findViewById(R.id.downloadDetails);
downloadDetails.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
startActivity(new Intent(DownloadProgress.this, Downloader.class));
}
});
startDownloads.setEnabled(false);
abort.setEnabled(false);
reset();
}
//Do the downloads
private void doDownloads()
{
reset();
contentService.startDownloadingNewPodCasts(new Config(contentService).getMax());
findViewById(R.id.AbortDownloads).setEnabled(true);
findViewById(R.id.startDownloads).setEnabled(false);
}
@Override
protected void onPause() {
super.onPause();
// stop display thread
updater.allDone();
}
@Override
protected void onResume() {
super.onResume();
updater = new Updater(handler, this);
}
private void reset() {
TextView labelSubscriptionSites = (TextView) findViewById(R.id.labelSubscriptionSites);
TextView scanning = (TextView) findViewById(R.id.scanning);
TextView downloadingLabel = (TextView) findViewById(R.id.downloadingLabel);
TextView progressSimple = (TextView) findViewById(R.id.progressSimple);
TextView progressBytes = (TextView) findViewById(R.id.progressBytes);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress);
TextView subscriptionName = (TextView) findViewById(R.id.subscriptionName);
TextView title = (TextView) findViewById(R.id.title);
labelSubscriptionSites.setVisibility(TextView.INVISIBLE);
scanning.setVisibility(TextView.INVISIBLE);
downloadingLabel.setVisibility(TextView.INVISIBLE);
progressSimple.setVisibility(TextView.INVISIBLE);
progressBytes.setVisibility(TextView.INVISIBLE);
progressBar.setVisibility(TextView.INVISIBLE);
scanning.setText("");
progressSimple.setText("");
progressBytes.setText("");
progressBar.setProgress(0);
subscriptionName.setText("");
title.setText("");
}
// Called once a second in the UI thread to update the screen.
@Override public void run() {
String downloadStatus = null;
try {
downloadStatus = contentService.encodedDownloadStatus();
if (!downloadStatus.equals("")) {
updateFromString(downloadStatus);
}
if (downloadStatus.equals("") || downloadStatus.startsWith("done,")) {
findViewById(R.id.startDownloads).setEnabled(true);
findViewById(R.id.AbortDownloads).setEnabled(false);
} else {
// wasStarted = true;
findViewById(R.id.startDownloads).setEnabled(false);
findViewById(R.id.AbortDownloads).setEnabled(true);
}
} catch (Exception e) {
CarCastApplication.esay(new RuntimeException("downloadStatus was: " + downloadStatus, e));
}
}
private void updateFromString(String downloadStatus) {
// Toss out first comma separated value (busy or idle)
List<String> fullStatus = new ArrayList<String>(Arrays.asList(downloadStatus.split(",")));
fullStatus.remove(0);
String[] status = fullStatus.toArray(new String[fullStatus.size()]);
TextView labelSubscriptionSites = (TextView) findViewById(R.id.labelSubscriptionSites);
TextView scanning = (TextView) findViewById(R.id.scanning);
labelSubscriptionSites.setVisibility(TextView.VISIBLE);
scanning.setVisibility(TextView.VISIBLE);
TextView downloadingLabel = (TextView) findViewById(R.id.downloadingLabel);
TextView progressSimple = (TextView) findViewById(R.id.progressSimple);
TextView progressBytes = (TextView) findViewById(R.id.progressBytes);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress);
labelSubscriptionSites.setVisibility(TextView.VISIBLE);
scanning.setText(" Scanning sites " + status[0] + "/" + status[1]);
if (status[3].equals("0")) {
downloadingLabel.setVisibility(TextView.INVISIBLE);
progressSimple.setVisibility(TextView.INVISIBLE);
progressBytes.setVisibility(TextView.INVISIBLE);
progressBar.setVisibility(TextView.INVISIBLE);
progressBar.setProgress(0);
} else {
downloadingLabel.setVisibility(TextView.VISIBLE);
progressSimple.setVisibility(TextView.VISIBLE);
progressBytes.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(TextView.VISIBLE);
progressSimple.setText(" Podcast " + status[2] + "/" + status[3]);
long cb = Long.parseLong(status[4]);
long tb = Long.parseLong(status[5]);
if (tb == 0) {
progressBytes.setText("");
progressBar.setProgress(0);
} else {
progressBytes.setText(" " + cb / 1024 + "k/" + tb / 1024 + "k");
progressBar.setProgress((int) ((cb * 100) / tb));
}
}
TextView subscriptionName = (TextView) findViewById(R.id.subscriptionName);
TextView title = (TextView) findViewById(R.id.title);
subscriptionName.setText(status[6]);
title.setText(status[7]);
if (downloadStatus.startsWith("done,")) {
if (status[3].equals("0")) {
progressSimple.setVisibility(TextView.VISIBLE);
progressSimple.setText(" No new podcasts found.");
}
subscriptionName.setText("");
title.setText(" *** COMPLETED ***");
}
}
}
|
/*
* Purpose:-Write a static function sqrt to compute the square root
* of a nonnegative number c given in the input using Newton's method:
*
*@Author:-Arpana kumari
*version:-1.0
*@since:-20 April, 2018
*/
package com.bridgeit.algorithmprogram;
import com.bridgeit.utility.Utility;
public class Sqrt {
public static void main(String[] args) {
double c = Double.parseDouble(args[0]);
Utility.sqrt(c);
}
}
|
package com.ims.persistence.hibernate.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.ims.dto.ProductGroupMapDTO;
import com.ims.dto.ProductMasterDTO;
import com.ims.exception.IPersistenceErrorCode;
import com.ims.persistence.hibernate.PersistenceException;
public class ProductMasterDAOImpl implements IProductMasterDAO {
private Logger logger = Logger.getLogger("com.biz");
private Session session;
public ProductMasterDAOImpl(Session session) {
this.session = session;
}
@Override
public ProductMasterDTO saveProductMaster(ProductMasterDTO productMasterDTO) throws PersistenceException {
// TODO Auto-generated method stub
logger.info("Entry");
logger.info("ProductMasterDTO ="+productMasterDTO);
try {
session.saveOrUpdate(productMasterDTO);
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw new PersistenceException(e,
IPersistenceErrorCode.DATABASE_PROBLEM);
}
logger.info("Exit");
return productMasterDTO;
}
@Override
public ProductMasterDTO getProductMaster(int id) throws PersistenceException {
// TODO Auto-generated method stub
ProductMasterDTO pm=null;
try {
pm=(ProductMasterDTO) session.load(ProductMasterDTO.class, id);
logger.info(pm);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return pm;
}
@Override
public ProductMasterDTO updateProductMaster(ProductMasterDTO productMasterDTO) throws PersistenceException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ProductMasterDTO> listProductMaster() throws PersistenceException {
// TODO Auto-generated method stub
logger.info("Entry");
List<ProductMasterDTO> list=null;
try {
Criteria q=session.createCriteria(ProductMasterDTO.class);
list=q.list();
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw new PersistenceException(e,
IPersistenceErrorCode.DATABASE_PROBLEM);
}
logger.info("Exit");
return list;
}
@Override
public List<ProductMasterDTO> listProductMasterByGroupId(int groupId) throws PersistenceException {
// TODO Auto-generated method stub
logger.info("Entry");
List<ProductMasterDTO> list=null;
try {
Criteria q=session.createCriteria(ProductMasterDTO.class);
ProductGroupMapDTO pGroupMapDTO=new ProductGroupMapDTO();
pGroupMapDTO.setId(groupId);
q.add(Restrictions.eq("prGroupMapDTO", pGroupMapDTO));
list=q.list();
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
throw new PersistenceException(e,
IPersistenceErrorCode.DATABASE_PROBLEM);
}
logger.info("Exit");
return list;
}
}
|
package io.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.model.Address;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.UUID;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* employee object
*/
@Schema(description = "employee object")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-03-01T04:02:41.003Z[GMT]")
public class Employee {
@JsonProperty("id")
private UUID id = null;
@JsonProperty("firstName")
private String firstName = null;
@JsonProperty("lastName")
private String lastName = null;
@JsonProperty("address")
private Address address = null;
public Employee id(UUID id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "")
@Valid
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public Employee firstName(String firstName) {
this.firstName = firstName;
return this;
}
/**
* Get firstName
* @return firstName
**/
@Schema(example = "Rabiya", description = "")
@Size(min=2,max=100) public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Employee lastName(String lastName) {
this.lastName = lastName;
return this;
}
/**
* Get lastName
* @return lastName
**/
@Schema(example = "Yuksel", description = "")
@Size(min=2,max=100) public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Employee address(Address address) {
this.address = address;
return this;
}
/**
* Get address
* @return address
**/
@Schema(description = "")
@Valid
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employee employee = (Employee) o;
return Objects.equals(this.id, employee.id) &&
Objects.equals(this.firstName, employee.firstName) &&
Objects.equals(this.lastName, employee.lastName) &&
Objects.equals(this.address, employee.address);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName, address);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Employee {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.elepy.annotations;
import com.elepy.dao.CrudFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A link to the {@link CrudFactory} to be used to singleCreate Crud implementations for this
* {@link RestModel}. The default is whatever is configured with {@link com.elepy.Elepy#withDefaultCrudFactory(Class)}
*
* @see CrudFactory
* @see com.elepy.Elepy#withDefaultCrudFactory(Class)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface DaoFactory {
Class<? extends CrudFactory> value();
}
|
package com.freejavaman;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class UI_ImgBtn extends Activity {
ImageButton btn;
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (ImageButton)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.txt1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
txt.setText("please press button");
}
});
}
}
|
/*
* 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.
*/
/**
*
* @author Rogelio Chacón
*/
public class Secundaria {
public int Atributo1 = 10;
private int Atributo2 = 20;
protected int Atributo3 = 30;
int Atributo4 = 40;
}
class DefaultSecun{
public int Atributo1 = 10;
private int Atributo2 = 20;
protected int Atributo3 = 30;
int Atributo4 = 40;
}
|
package com.sebprunier.jobboard.serialization;
import java.util.List;
import com.sebprunier.jobboard.Job;
public interface JobSerializer {
String marshall(Job job);
String marshallAll(List<Job> jobs);
Job unmarshall(String text);
List<Job> unmarshallAll(String text);
}
|
package com.tencent.mm.plugin.game.model;
import com.tencent.mm.sdk.platformtools.x;
public class am$a {
public int eiF;
public String jOg;
public am$a(int i, String str) {
this.eiF = i;
this.jOg = str;
}
public static am$a g(int i, Object... objArr) {
am$a am_a = new am$a();
am_a.eiF = i;
StringBuilder stringBuilder = new StringBuilder();
int length = objArr.length - 1;
for (int i2 = 0; i2 < length; i2++) {
stringBuilder.append(String.valueOf(objArr[i2])).append(',');
}
stringBuilder.append(String.valueOf(objArr[length]));
am_a.jOg = stringBuilder.toString();
if (l.bPH > 0) {
x.i("MicroMsg.AppReportService", "appStat logID=%d, vals.size=%d, val = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(objArr.length), stringBuilder.toString()});
} else {
x.d("MicroMsg.AppReportService", "appStat logID=%d, vals.size=%d, val = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(objArr.length), stringBuilder.toString()});
}
return am_a;
}
}
|
package jdbchomework.dao.jdbc;
import jdbchomework.dao.model.CustomersDao;
import jdbchomework.entity.Customer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CustomersJdbcDao extends AbstractJdbcDao<Customer> implements CustomersDao {
public CustomersJdbcDao(Connection connection, String table) {
super(connection, table);
}
@Override
protected Customer createEntity(ResultSet resultSet) throws SQLException {
return new Customer(resultSet.getInt("id"),
resultSet.getString("name"));
}
}
|
package com.tech.blog.dao;
import com.tech.blog.entities.User;
import java.sql.Connection;
import java.sql.*;
public class UserDao {
private Connection con;
public UserDao(Connection con) {
this.con = con;
}
public boolean saveUser(User user)
{
boolean f=false;
try
{
String query="insert into user(name,email,password,gender) values(?,?,?,?)";
PreparedStatement pstm=this.con.prepareStatement(query);
pstm.setString(1, user.getName());
pstm.setString(2,user.getEmail());
pstm.setString(3,user.getPassword());
pstm.setString(4,user.getGender());
pstm.executeUpdate();
f=true;
}
catch(Exception e)
{
e.printStackTrace();
}
return f;
}
//get user by email and password
public User getUserByEmailAndPassword(String email,String password)
{
User user=null;
try
{
String query="select * from user where email= ? and password= ?";
PreparedStatement stmt=con.prepareStatement(query);
stmt.setString(1, email);
stmt.setString(2,password);
ResultSet rst=stmt.executeQuery();
if(rst.next())
{
user=new User();
String name=rst.getString("Name");
user.setName(name);
user.setId(rst.getInt("id"));
user.setEmail(rst.getString("Email"));
user.setGender(rst.getString("Gender"));
user.setDateTime(rst.getTimestamp("Reg_date"));
user.setPassword(rst.getString("Password"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
return user;
}
}
|
/*
*/
package com.cleverfishsoftware.loadgenerator.message.receiver;
/**
*
* @author peter
*/
public interface MessageReceiverRunner {
}
|
package com.supconit.kqfx.web.fxzf.warn.services.Impl;
import hc.base.domains.AjaxMessage;
import hc.base.domains.Pageable;
import hc.business.dic.services.DataDictionaryService;
import hc.orm.AbstractBasicOrmService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.supconit.kqfx.web.analysis.entities.JgZcd;
import com.supconit.kqfx.web.analysis.services.JgZcdService;
import com.supconit.kqfx.web.fxzf.avro.qbbItemInfo;
import com.supconit.kqfx.web.fxzf.avro.redis_BoardData;
import com.supconit.kqfx.web.fxzf.avro.redis_BoardInfo;
import com.supconit.kqfx.web.fxzf.avro.redis.ChargeRedisService;
import com.supconit.kqfx.web.fxzf.avro.redis.ReadRedisService;
import com.supconit.kqfx.web.fxzf.avro.redis.WriteRedisService;
import com.supconit.kqfx.web.fxzf.msg.services.MsgService;
import com.supconit.kqfx.web.fxzf.qbb.entities.QbbBfxx;
import com.supconit.kqfx.web.fxzf.qbb.services.QbbBfxxService;
import com.supconit.kqfx.web.fxzf.search.entities.Fxzf;
import com.supconit.kqfx.web.fxzf.warn.daos.WarnHistoryDao;
import com.supconit.kqfx.web.fxzf.warn.entities.Config;
import com.supconit.kqfx.web.fxzf.warn.entities.WarnHistory;
import com.supconit.kqfx.web.fxzf.warn.entities.WarnInfo;
import com.supconit.kqfx.web.fxzf.warn.services.ConfigService;
import com.supconit.kqfx.web.fxzf.warn.services.WarnHistoryService;
import com.supconit.kqfx.web.fxzf.warn.services.WarnInfoService;
import com.supconit.kqfx.web.util.DateUtil;
import com.supconit.kqfx.web.util.EncodeTransforUtil;
import com.supconit.kqfx.web.util.IDGenerator;
import com.supconit.kqfx.web.util.SysConstants;
@Service("taizhou_offsite_enforcement_warnHistory_service")
public class WarnHistoryServiceImpl extends AbstractBasicOrmService<WarnHistory, String> implements WarnHistoryService {
//治超站数据字典项code
private static final String DETECT_CODE = "DETECTIONSTATION";
//治超站数据字典项code
private static final String OVERLOADSTATUS_CODE = "OVERLOADSTATUS";
@Autowired
private WarnHistoryDao warnHistoryDao;
@Autowired
private ConfigService configService;
@Autowired
private WarnInfoService warnInfoService;
@Autowired
private QbbBfxxService qbbBfxxService;
@Autowired
private WriteRedisService writeRedisService;
@Autowired
private ReadRedisService readRedisService;
@Autowired
private DataDictionaryService dataDictionaryService;
@Autowired
private MsgService msgService;
@Autowired
private JgZcdService jgZcdService;
@Autowired
private ChargeRedisService chargeRedisService;
@Value("${qbb.circle.time}")
private long circleTime;
@Override
public Pageable<WarnHistory> findByPager(Pageable<WarnHistory> pager, WarnHistory condition) {
return warnHistoryDao.findByPager(pager, condition);
}
@Override
public WarnHistory getById(String id) {
return this.warnHistoryDao.getById(id);
}
@Override
public void insert(WarnHistory entity) {
this.warnHistoryDao.insert(entity);
}
@Override
public void update(WarnHistory entity) {
this.warnHistoryDao.update(entity);
}
@Override
public void delete(WarnHistory entity) {
this.warnHistoryDao.delete(entity);
}
@Override
public Boolean IsPublishWarnMessage(String license, String plateColor) {
double againTime = this.configService.getValueByCode(SysConstants.WARN_AGAIN_TIME);
if (0 != againTime) {
List<WarnHistory> result = this.warnHistoryDao.findAgainTimeData(license, plateColor, againTime);
return !CollectionUtils.isEmpty(result) ? true : false;
} else {
return false;
}
}
/**
* 发布告警信息到情报板
*/
@Override
@Transactional
public AjaxMessage publishToQbb(Fxzf fxzf) {
try {
//数据库入库预警信息
if (!StringUtil.isEmpty(fxzf.getDetectStation())) {
WarnInfo warnInfo = new WarnInfo();
warnInfo.setDetectStation(fxzf.getDetectStation());
warnInfo.setWarnType(fxzf.getWarnType());
warnInfo = this.warnInfoService.getByTempletTypeAndStation(warnInfo);
//获取系统默认情报板停留时间
Config config = this.configService.getByCode(SysConstants.QBB_STAY_TIME);
if (null != warnInfo) {
WarnHistory warnHistory = new WarnHistory();
warnHistory.setFxzfId(fxzf.getId());
warnHistory.setDeleted(0);
warnHistory.setLicense(fxzf.getLicense());
warnHistory.setPlateColor(fxzf.getLicenseColor());
//设置为情报板报警
warnHistory.setWarnType(1);
warnHistory.setWarnTime(fxzf.getCaptureTime());
warnHistory.setWarnInfo(EncodeTransforUtil.getXxnrResult(this.getWarnInfo(fxzf, warnInfo), null));//根据告警模板匹配信息并截取信息
warnHistory.setId(IDGenerator.idGenerator());
this.warnHistoryDao.insert(warnHistory);
QbbBfxx qbbBfxx = new QbbBfxx();
qbbBfxx.setId(IDGenerator.idGenerator());
qbbBfxx.setXxnr(this.getWarnInfo(fxzf, warnInfo));//根据告警模板匹配信息
qbbBfxx.setCzfs(warnInfo.getQbbmbxx().getCzfs());
qbbBfxx.setFont(warnInfo.getQbbmbxx().getFont());
qbbBfxx.setColor(warnInfo.getQbbmbxx().getColor());
//默认循环时间缺省值
qbbBfxx.setCircleTime(circleTime);
//默认停留时间缺省值
qbbBfxx.setRemainTime(config.getValue().longValue());
qbbBfxx.setPublishTime(new Date());
qbbBfxx.setLocation(fxzf.getDetectStation());
//自动发布
qbbBfxx.setType("0");
qbbBfxx.setDeleted(0);
/** 获取情报板实时内容,目前无法进行读取情报板 */
redis_BoardData boardData = this.readRedisService.ReadBoardData(fxzf.getDetectStation());
/** 插入情报板播放列表中 */
this.qbbBfxxService.insert(qbbBfxx);
redis_BoardInfo boardInfo = new redis_BoardInfo();
List<qbbItemInfo> itemList = new ArrayList<qbbItemInfo>();
itemList.add(QbbBfxx.translateToQbbItem(qbbBfxx));
boardInfo.setSQbbItems(itemList);
this.writeRedisService.WriteBoardInfo(boardInfo, fxzf.getDetectStation());
// 将实时播放内容保存到 BoardData_Prefix = "QBB_INFO_01/2";中便于读取
redis_BoardData boardData2 = new redis_BoardData();
boardData2.setSQbb(qbbBfxx.getXxnr());
this.writeRedisService.WriteBoardData(boardData2, fxzf.getDetectStation());
// 回归之前获取情报板内容
this.qbbBfxxService.restoreLastQbb(config.getValue().longValue(), null != boardData ? String.valueOf(boardData.getSQbb()) : "", fxzf.getDetectStation(), 0);
}
}
return AjaxMessage.success();
} catch (Exception e) {
return AjaxMessage.error(e.toString());
}
//写入情报板信息至redis中
}
@Override
@Transactional
public AjaxMessage publishToWeb(Fxzf fxzf) {
//数据库入库预警信息
try {
if (!StringUtil.isEmpty(fxzf.getDetectStation()) && !StringUtil.isEmpty(fxzf.getLicense())) {
WarnInfo warnInfo = new WarnInfo();
warnInfo.setDetectStation(fxzf.getDetectStation());
warnInfo.setWarnType(fxzf.getWarnType());
warnInfo = this.warnInfoService.getByTempletTypeAndStation(warnInfo);
Config config = this.configService.getByCode(SysConstants.WEB_WARN_TEMPLET);
if (null != warnInfo) {
//根据配置项设置网页告警模板内容(设置warnInfo使getWarnInfo取值TempletInfo)
warnInfo.setQbbTempletId(null);
warnInfo.setQbbmbxx(null);
warnInfo.setTempletInfo(null != config ? config.getName() : "");
WarnHistory warnHistory = new WarnHistory();
Date date = new Date();
warnHistory.setFxzfId(fxzf.getId());
warnHistory.setDeleted(0);
warnHistory.setLicense(fxzf.getLicense());
warnHistory.setPlateColor(fxzf.getLicenseColor());
//设置为WEB报警
warnHistory.setWarnType(2);
warnHistory.setWarnTime(date);
warnHistory.setWarnInfo(this.getWarnInfo(fxzf, warnInfo));//模糊匹配WEB告警信息
warnHistory.setId(IDGenerator.idGenerator());
this.warnHistoryDao.insert(warnHistory);
JgZcd jgZcd = this.jgZcdService.getByZczId(fxzf.getDetectStation());
//判断过车信息中的车辆是否为黑名单
String key = "B_" + fxzf.getLicense() + "_" + fxzf.getLicenseColor();
boolean flagKey = chargeRedisService.chargeKey(key);
if (flagKey) {
this.msgService.insertWarnInfo(warnHistory.getId(), "0", warnHistory.getWarnTime(), "黑名单告警:" + warnHistory.getWarnInfo(), String.valueOf(jgZcd.getJgid()));
} else {
this.msgService.insertWarnInfo(warnHistory.getId(), "0", warnHistory.getWarnTime(), warnHistory.getWarnInfo(), String.valueOf(jgZcd.getJgid()));
}
}
}
return AjaxMessage.success("WEB自动告警成功");
} catch (Exception e) {
return AjaxMessage.error(e.toString());
}
}
/**
* 通过正则将表达式中字段匹配成对象属性
*
* @param fxzf
* @param warnInfo
* @return
*/
@Override
public String getWarnInfo(Fxzf fxzf, WarnInfo warnInfo) {
String result = "";
if (null != fxzf && null != warnInfo) {
String para = "";
if (StringUtil.isEmpty(warnInfo.getQbbTempletId()) || null == warnInfo.getQbbmbxx()) {
para = warnInfo.getTempletInfo().replace("+", "");
} else {
para = warnInfo.getQbbmbxx().getXxnr().replace("+", "");
}
if (!StringUtil.isEmpty(para)) {
String regEx = "@([\\s\\S]*?)@";
Pattern pat = Pattern.compile(regEx);
Matcher mat = pat.matcher(para);
while (mat.find()) {
System.out.println(mat.group());
Map<String, Object> map = this.getMap(fxzf);
para = para.replaceAll(mat.group(), String.valueOf(map.get(mat.group())));
}
result = para;
}
}
return result;
}
/**
* 将fxzf转换成map
*
* @param fxzf
* @return
*/
public Map<String, Object> getMap(Fxzf fxzf) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("@车牌号@", null != fxzf.getLicense() ? fxzf.getLicense() : "");
map.put("@治超站@", null != fxzf.getDetectStation() ? this.dataDictionaryService.getByDataCode(DETECT_CODE, fxzf.getDetectStation()).getName() : "");
map.put("@过车时间@", null != fxzf.getCaptureTime() ? DateUtil.formatDate(fxzf.getCaptureTime(), DateUtil.DATE_FORMAT_TIME_T) : "");
map.put("@总重@", null != fxzf.getWeight() ? fxzf.getWeight() : "");
map.put("@轴数@", null != fxzf.getAxisCount() ? fxzf.getAxisCount() : "");
map.put("@超限率@", null != fxzf.getOverLoadPercent() ? fxzf.getOverLoadPercent() : "");
map.put("@违法等级@", null != fxzf.getOverLoadStatus() ? this.dataDictionaryService.getByDataCode(OVERLOADSTATUS_CODE, String.valueOf(fxzf.getOverLoadStatus())).getName() : "");
return map;
}
@Override
public List<WarnHistory> AnalysisDayWarnByCondition(WarnHistory condition) {
return this.warnHistoryDao.AnalysisDayWarnByCondition(condition);
}
@Override
public Pageable<WarnHistory> findByPagerExport(Pageable<WarnHistory> pager, WarnHistory condition) {
return this.warnHistoryDao.findByPagerExport(pager, condition);
}
@Override
public List<WarnHistory> getWarnByFxzfId(String fxzfid) {
return this.warnHistoryDao.getWarnByFxzfId(fxzfid);
}
@Override
public WarnHistory getWarnHistoryQbb(Fxzf warn) {
return this.warnHistoryDao.getWarnHistoryQbb(warn);
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class BOJ_2517_달리기 {
private static Pair[] person;
private static int S;
private static int[] tree;
private static int[] ans;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
person = new Pair[N];
for (int i = 0; i < N; i++) {
person[i] = new Pair(i,Integer.parseInt(br.readLine()));
}
Arrays.sort(person);
S =1;
while(S<N)
S<<=1;
tree = new int[2*S];
ans = new int[N];
for (int i = 0; i < N; i++) {
update(person[i].idx);
sum(0,person[i].idx);
}
for (int i = 0; i < N; i++) {
bw.append(ans[i] + "\n");
}
bw.flush();
bw.close();
}
// 부분합을 구한다
private static void sum(int s, int e) {
int start = s + S;
int end = e + S;
int sum =0;
while(start<=end) {
// 홀수면 따로 있는 경우다
if(start%2 == 1) {
sum+=tree[start];
start++;
}
if(end%2== 0) {
sum+=tree[end];
end--;
}
start/=2;
end/=2;
}
ans[e] = sum;
}
// bottom-up 하면서 업데이트
private static void update(int idx) {
int stand = idx + S;
tree[stand] = 1;
stand/=2;
while(stand>0) {
tree[stand] = tree[stand*2] + tree[stand*2 +1];
stand/=2;
}
}
public static class Pair implements Comparable<Pair>{
int idx, fast;
public Pair(int idx, int fast) {
super();
this.idx = idx;
this.fast = fast;
}
@Override
public String toString() {
return "Pair [idx=" + idx + ", fast=" + fast + "]";
}
@Override
public int compareTo(Pair o) {
Integer f1 = this.fast;
Integer f2 = o.fast;
return f2.compareTo(f1);
}
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class FindMContactInviteUI$2 implements OnClickListener {
final /* synthetic */ FindMContactInviteUI eLY;
FindMContactInviteUI$2(FindMContactInviteUI findMContactInviteUI) {
this.eLY = findMContactInviteUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
}
}
|
package capstone.abang.com.Models;
/**
* Created by Rylai on 2/20/2018.
*/
public class Location {
private String code;
private String lat;
private String lng;
private Location() {
}
public Location(String code, String lat, String lng) {
this.code = code;
this.lat = lat;
this.lng = lng;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
}
|
package app.com.blogapi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import app.com.blogapi.entidades.Entradas;
import app.com.blogapi.servicio.BlogApiServices;
import app.com.blogapi.servicio.PostService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FormPost extends AppCompatActivity {
private EditText tituloPublicacion, contenidoPublicacion, tagsPublicacion;
private Button cancelar, guardar;
private String authToken, userName,userEmail;
private int userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_post);
final PostService postService = BlogApiServices
.getInstance().getPostService();
tituloPublicacion = findViewById(R.id.ptTitle);
contenidoPublicacion = findViewById(R.id.etBody);
contenidoPublicacion.setMaxLines(10);
tagsPublicacion = findViewById(R.id.etTags);
cancelar= findViewById(R.id.fpCancel);
guardar = findViewById(R.id.fpSave);
/* Obteniendo las variables almacenadas en el shared preferences */
SharedPreferences pref = getApplicationContext().getSharedPreferences("BlogApiPref", MODE_PRIVATE);
authToken = pref.getString("token",null);
userName = pref.getString("name",null);
userEmail = pref.getString("email",null);
userId = pref.getInt("id",0);
cancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelarPost();
}
});
guardar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String body = contenidoPublicacion.getText().toString();
String [] tagsList = strToArrayList(tagsPublicacion.getText().toString());
String title = tituloPublicacion.getText().toString();
Entradas entradas = new Entradas(userId,body,tagsList,title,userEmail,userName);
Call<Entradas> call = postService.entradaNueva("Bearer "+authToken, entradas);
call.enqueue(new Callback<Entradas>() {
@Override
public void onResponse(Call<Entradas> call, Response<Entradas> response) {
if (response.isSuccessful()) {
Toast.makeText(FormPost.this, "El Post fue creado con exito!!!"+response.code(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(FormPost.this, "Error: "+response.code(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Entradas> call, Throwable t) {
Toast.makeText(FormPost.this, "Error: "+t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
public void cancelarPost(){
/* Limpiar los campos */
tituloPublicacion.setText("");
contenidoPublicacion.setText("");
tagsPublicacion.setText("");
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
/*
* Convertir los tags recibidos en arreglo
* */
public static String[] strToArrayList(String strValues){
String str[] = strValues.split(",");
return str;
}
}
|
package 多线程.三个线程保证顺序执行;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class 使用Condition {
private static Lock lock=new ReentrantLock();
private static Condition condition1=lock.newCondition();
private static Condition condition2=lock.newCondition();
private static boolean t1Run=false;
private static boolean t2Run=false;
public static void main(String[] args) {
final Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
System.out.println("1");
t1Run=true;
condition1.signal();
lock.unlock();
}
});
final Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
if(!t1Run){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("2");
condition2.signal();
lock.unlock();
}
});
// final Thread thread3=new Thread(new Runnable() {
// @Override
// public void run() {
//
// }
// })
}
}
|
package ua.goit.timonov.enterprise.service;
import org.springframework.transaction.annotation.Transactional;
import ua.goit.timonov.enterprise.dao.EmployeeDAO;
import ua.goit.timonov.enterprise.model.Employee;
import ua.goit.timonov.enterprise.model.Waiter;
import java.util.List;
/**
* Web service for EmployeeDAO
*/
public class EmployeeService {
private EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
@Transactional
public List<Employee> getAllEmployees() {
return employeeDAO.getAll();
}
@Transactional
public Employee getEmployeeByName(String... name) {
return employeeDAO.search(name);
}
@Transactional
public List<Waiter> getWaiters() {
List<Waiter> waiters = employeeDAO.getWaiters();
return waiters;
}
@Transactional
public void add(Employee employee) {
employeeDAO.add(employee);
}
@Transactional
public Employee getEmployeeById(Integer id) {
return employeeDAO.search(id);
}
@Transactional
public void update(Employee employee) {
employeeDAO.update(employee);
}
}
|
package project.timesheetWebapp.service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import project.applyLeaveWebapp.dto.ResponseDTO;
import project.timesheetWebapp.constants.Constants;
import project.timesheetWebapp.dao.TimesheetDAO;
import project.timesheetWebapp.dto.TimesheetDetailsDTO;
import project.timesheetWebapp.dto.TimesheetTaskDTO;
@Service
public class TimesheetServiceImpl implements TimesheetService {
@Autowired
private TimesheetDAO dao ;
public ResponseDTO saveTimesheet(List<TimesheetDetailsDTO> dto) {
ResponseDTO response = new ResponseDTO() ;
if(dto == null || dto.size() == 0) {
response.setStatus(Constants.statusZero);
response.setResponse(Constants.responseFailed);
return response ;
}
int result = dao.saveTimesheet(dto) ;
if(result <= 0 ) {
response.setStatus(Constants.statusZero);
response.setResponse(Constants.responseFailed);
return response ;
}else {
response.setStatus(Constants.statusOne);
response.setResponse(Constants.responseSuccess);
return response ;
}
}
public ResponseDTO getTimesheet(String employeeId,String date) {
ResponseDTO response = new ResponseDTO() ;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dateStr = null;
try {
dateStr = formatter.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<TimesheetTaskDTO> list = dao.getTimesheet(employeeId, dateStr) ;
if(list.size() > 0) {
TimesheetDetailsDTO day = new TimesheetDetailsDTO() ;
day.setDate(date);
day.setTasks(list);
response.setStatus(Constants.statusOne);
response.setResponse(day);
}else {
response.setStatus(Constants.statusZero);
response.setResponse("Failed to get tasks for selected day");
}
return response ;
}
}
|
package services;
import model.domain.Persoana;
import model.domain.Proiect;
import model.domain.UserOnProject;
import model.forms.PersonOnProjectFormModel;
import model.forms.ProiectFormModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import services.repository.ProiectRepository;
import services.repository.StatusProiectRepository;
import services.repository.UserOnProjectRepository;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class ProjectServiceImpl implements ProjectsService {
private static final Logger LOGGER = LoggerFactory.getLogger(ProjectServiceImpl.class);
private static final int DELETED = 1;
private static final int NOT_DELETED = 0;
@Autowired
private ProiectRepository proiectRepository;
@Autowired
private StatusProiectRepository statusProiectRepository;
@Autowired
private ClientServiceImpl clientService;
@Autowired
private ProjectCategoryService projectCategoryService;
@Autowired
private UserOnProjectRepository userOnProjectRepository;
@Autowired
private ResurseUmaneService resurseUmaneService;
@Override
public List<Proiect> findAll() {
try {
return proiectRepository.findAllByDeletedEquals(NOT_DELETED);
} catch (DataAccessException e) {
LOGGER.error("PROJECTS.NO_PROJECTS", e);
return Collections.emptyList();
}
}
@Override
public Proiect findOne(long id) {
Proiect proiect;
try {
proiect = proiectRepository.findOne(id);
return proiect;
} catch (DataAccessException e) {
String msg = "PROJECTS.NO_PROJECT_FOUND";
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
}
@Override
@Transactional
public Proiect saveProject(ProiectFormModel entity) {
Pattern pattern = Pattern.compile("^([a-zA-Z0-9]{4}).*$");
Matcher matcher = pattern.matcher(entity.getNumeProiect());
Proiect proiect = new Proiect();
proiect.setNumeProiect(entity.getNumeProiect());
while (matcher.find()) {
proiect.setCodroiect(matcher.group(1).toUpperCase());
}
proiect.setDescriere(entity.getDescriere());
proiect.setIdStatusProiect(statusProiectRepository.findOne(entity.getIdStatusProiect()));
proiect.setIdClient(clientService.findOne(entity.getIdClient()));
proiect.setIdCategorieProiect(projectCategoryService.findOne(entity.getIdCategorieProiect()));
proiect.setDataStart(entity.getDataStart());
proiect.setDataEndEstimativa(entity.getDataEndEstimativa());
return proiectRepository.save(proiect);
}
@Override
public void delete(long id) {
Proiect proiect;
try {
proiect = proiectRepository.findOne(id);
proiect.setDeleted(DELETED);
proiectRepository.save(proiect);
} catch (DataAccessException e) {
String msg = "ERROR While deleting project";
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
}
@Override
public long emptyTrash() {
List<Proiect> toDelete;
try {
toDelete = proiectRepository.findByDeletedEquals(DELETED);
proiectRepository.delete(toDelete);
return toDelete.size();
} catch (DataAccessException e) {
String msg = "ERROR While emptying project trash ";
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
}
@Override
public List<Persoana> getUsersOnProject(long idProiect) {
List<Persoana> usersOnProject;
Proiect proiect = proiectRepository.findOne(idProiect);
try {
usersOnProject = userOnProjectRepository.findAllByProiectEquals(proiect);
} catch (DataAccessException e) {
LOGGER.info(String.format("No users assigned to project %s", proiect.getNumeProiect()));
usersOnProject = Collections.emptyList();
}
return usersOnProject;
}
@Override
public UserOnProject removePersoanaFromProiect(Persoana persoana, Proiect proiect) {
UserOnProject toDelete = userOnProjectRepository.findByPersoanaAndProiectEquals(persoana, proiect);
return removePersoanaFromProiect(toDelete.getIdUserOnProject());
}
@Override
public UserOnProject removePersoanaFromProiect(long idUserOnProject) {
UserOnProject toDelete = userOnProjectRepository.findOne(idUserOnProject);
userOnProjectRepository.delete(toDelete);
return toDelete;
}
@Override
@Transactional
public UserOnProject assignPersoanaToProiect(PersonOnProjectFormModel personOnProject) {
Persoana persoana = resurseUmaneService.findByFullNameEquals(personOnProject.getFullName());
Proiect proiect = proiectRepository.findOne(personOnProject.getIdProiect());
UserOnProject mapping = userOnProjectRepository.findByPersoanaAndProiectEquals(persoana, proiect);
if (mapping == null) {
mapping = new UserOnProject();
mapping.setPersoana(persoana);
mapping.setProiect(proiect);
userOnProjectRepository.save(mapping);
}
return mapping;
}
}
|
package Repository;
import Model.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface PatientRepository extends JpaRepository<Patient, Long> {
List<Patient> findByName(String name);
List<Patient> findByNameAndLastUpdateTimeOrderByLastUpdateTime(String name, String lastUpdateTime);
Patient findById(long id);
List<Patient> findByNameAndDate(String name, String date);
@Query(value = "SELECT ANY_VALUE(id) as id, ANY_VALUE(date) as date, max(lastUpdateTime) as lastUpdateTime, ANY_VALUE(location) as location, ANY_VALUE(name) as name, ANY_VALUE(time) as time FROM `patient1` GROUP BY name ORDER BY lastUpdateTime" , nativeQuery = true)
List<Patient> findByNative();
}
|
package org.fuserleer.serialization.mapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.Function;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
/**
* Deserializer for translation from CBOR binary data
* to DSON data for an object which can be represented by a string.
*/
public class JacksonCborObjectBytesDeserializer<T> extends StdDeserializer<T> {
/**
*
*/
private static final long serialVersionUID = -5294764659152624229L;
private final byte prefix;
private final Function<byte[], T> bytesMapper;
JacksonCborObjectBytesDeserializer(Class<T> t, byte prefix, Function<byte[], T> bytesMapper)
{
super(t);
this.prefix = prefix;
this.bytesMapper = bytesMapper;
}
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
byte[] bytes = p.getBinaryValue();
if (bytes == null || bytes.length == 0 || bytes[0] != this.prefix)
throw new InvalidFormatException(p, "Expecting " + this.prefix, bytes, this.handledType());
return this.bytesMapper.apply(Arrays.copyOfRange(bytes, 1, bytes.length));
}
}
|
/*
* This file is part of SMG, a symbolic memory graph Java library
* Originally developed as part of CPAChecker, the configurable software verification platform
*
* Copyright (C) 2011-2015 Petr Muller
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* 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 cz.afri.smg.graphs;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import cz.afri.smg.graphs.SMGValues.SMGExplicitValue;
import cz.afri.smg.graphs.SMGValues.SMGKnownSymValue;
import cz.afri.smg.objects.SMGObject;
import cz.afri.smg.objects.SMGObjectVisitor;
import cz.afri.smg.objects.SMGRegion;
import cz.afri.smg.objects.sll.SMGSingleLinkedList;
import cz.afri.smg.objects.tree.SimpleBinaryTree;
final class SMGObjectNode {
private final String name;
private final String definition;
private static int counter = 0;
public SMGObjectNode(final String pType, final String pDefinition) {
name = "node_" + pType + "_" + counter++;
definition = pDefinition;
}
public SMGObjectNode(final String pName) {
name = pName;
definition = null;
}
public String getName() {
return name;
}
public String getDefinition() {
return name + "[" + definition + "];";
}
}
class SMGNodeDotVisitor extends SMGObjectVisitor {
private final ReadableSMG smg;
private SMGObjectNode node = null;
public SMGNodeDotVisitor(final ReadableSMG pSmg) {
smg = pSmg;
}
private String defaultDefinition(final String pColor, final String pShape, final String pStyle,
final SMGObject pObject) {
return "color=" + pColor + ", shape=" + pShape + ", style=" + pStyle + ", label =\"" + pObject.toString() + "\"";
}
@Override
public void visit(final SMGRegion pRegion) {
String shape = "rectangle";
String color;
String style;
if (smg.isObjectValid(pRegion)) {
color = "black"; style = "solid";
} else {
color = "red"; style = "dotted";
}
node = new SMGObjectNode("region", defaultDefinition(color, shape, style, pRegion));
}
@Override
public void visit(final SMGSingleLinkedList pSll) {
String shape = "rectangle";
String color = "blue";
String style = "dashed";
node = new SMGObjectNode("sll", defaultDefinition(color, shape, style, pSll));
}
@Override
public void visit(final SimpleBinaryTree pTree) {
String shape = "rectangle";
String color = "green";
String style = "dashed";
node = new SMGObjectNode("tree", defaultDefinition(color, shape, style, pTree));
}
@Override
public void visit(final SMGObject pObject) {
if (pObject.notNull()) {
pObject.accept(this);
} else {
node = new SMGObjectNode("NULL");
}
}
public SMGObjectNode getNode() {
return node;
}
}
public final class SMGPlotter {
public static void debuggingPlot(final ReadableSMG pSmg, final String pId) throws IOException {
SMGPlotter plotter = new SMGPlotter();
PrintWriter writer = new PrintWriter(pId + ".dot", "UTF-8");
writer.write(plotter.smgAsDot(pSmg, pId, pId));
writer.close();
}
private final HashMap <SMGObject, SMGObjectNode> objectIndex = new HashMap<>();
private static int nulls = 0;
private int offset = 0;
public SMGPlotter() { } /* utility class */
public static String convertToValidDot(final String original) {
return original.replaceAll("[:]", "_");
}
public String smgAsDot(final ReadableSMG smg, final String name, final String location) {
StringBuilder sb = new StringBuilder();
sb.append("digraph gr_" + name.replace('-', '_') + "{\n");
offset += 2;
sb.append(newLineWithOffset("label = \"Location: " + location.replace("\"", "\\\"") + "\";"));
addStackSubgraph(smg, sb);
SMGNodeDotVisitor visitor = new SMGNodeDotVisitor(smg);
for (SMGObject heapObject : smg.getHeapObjects()) {
if (!objectIndex.containsKey(heapObject)) {
visitor.visit(heapObject);
objectIndex.put(heapObject, visitor.getNode());
}
if (heapObject.notNull()) {
sb.append(newLineWithOffset(objectIndex.get(heapObject).getDefinition()));
}
}
addGlobalObjectSubgraph(smg, sb);
for (Integer value : smg.getValues()) {
if (value != smg.getNullValue()) {
SMGExplicitValue explicitValue = smg.getExplicit(SMGKnownSymValue.valueOf(value));
String explicitValueString;
if (explicitValue.isUnknown()) {
explicitValueString = "";
} else {
explicitValueString = " : " + String.valueOf(explicitValue.getAsLong());
}
sb.append(newLineWithOffset(smgValueAsDot(value, explicitValueString)));
}
}
for (SMGEdgeHasValue edge: smg.getHVEdges()) {
sb.append(newLineWithOffset(smgHVEdgeAsDot(edge)));
}
for (SMGEdgePointsTo edge: smg.getPTEdges()) {
if (edge.getValue() != smg.getNullValue()) {
sb.append(newLineWithOffset(smgPTEdgeAsDot(edge)));
}
}
sb.append("}");
return sb.toString();
}
private void addStackSubgraph(final ReadableSMG pSmg, final StringBuilder pSb) {
pSb.append(newLineWithOffset("subgraph cluster_stack {"));
offset += 2;
pSb.append(newLineWithOffset("label=\"Stack\";"));
int i = pSmg.getStackFrames().size();
for (CLangStackFrame stackItem : pSmg.getStackFrames()) {
addStackItemSubgraph(stackItem, pSb, i);
i--;
}
offset -= 2;
pSb.append(newLineWithOffset("}"));
}
private void addStackItemSubgraph(final CLangStackFrame pStackFrame, final StringBuilder pSb, final int pIndex) {
pSb.append(newLineWithOffset("subgraph cluster_stack_" + pStackFrame.getFunctionDeclaration().getName() + "{"));
offset += 2;
pSb.append(newLineWithOffset("fontcolor=blue;"));
pSb.append(newLineWithOffset("label=\"#" + pIndex + ": " + pStackFrame.getFunctionDeclaration().toString() +
"\";"));
HashMap<String, SMGRegion> toPrint = new HashMap<>();
toPrint.putAll(pStackFrame.getVariables());
SMGRegion returnObject = pStackFrame.getReturnObject();
if (returnObject != null) {
toPrint.put(CLangStackFrame.RETVAL_LABEL, returnObject);
}
pSb.append(newLineWithOffset(smgScopeFrameAsDot(toPrint, String.valueOf(pIndex))));
offset -= 2;
pSb.append(newLineWithOffset("}"));
}
private String smgScopeFrameAsDot(final Map<String, SMGRegion> pNamespace, final String pStructId) {
StringBuilder sb = new StringBuilder();
sb.append("struct" + pStructId + "[shape=record,label=\" ");
// I sooo wish for Python list comprehension here...
ArrayList<String> nodes = new ArrayList<>();
for (Entry<String, SMGRegion> entry : pNamespace.entrySet()) {
String key = entry.getKey();
SMGObject obj = entry.getValue();
if (key.equals("node")) {
// escape Node1
key = "node1";
}
nodes.add("<item_" + key + "> " + obj.toString());
objectIndex.put(obj, new SMGObjectNode("struct" + pStructId + ":item_" + key));
}
sb.append(Joiner.on(" | ").join(nodes));
sb.append("\"];\n");
return sb.toString();
}
private void addGlobalObjectSubgraph(final ReadableSMG pSmg, final StringBuilder pSb) {
if (pSmg.getGlobalObjects().size() > 0) {
pSb.append(newLineWithOffset("subgraph cluster_global{"));
offset += 2;
pSb.append(newLineWithOffset("label=\"Global objects\";"));
pSb.append(newLineWithOffset(smgScopeFrameAsDot(pSmg.getGlobalObjects(), "global")));
offset -= 2;
pSb.append(newLineWithOffset("}"));
}
}
private static String newNullLabel() {
SMGPlotter.nulls += 1;
return "value_null_" + SMGPlotter.nulls;
}
private String smgHVEdgeAsDot(final SMGEdgeHasValue pEdge) {
if (pEdge.getValue() == 0) {
String newNull = newNullLabel();
return newNull + "[shape=plaintext, label=\"NULL\"];" + objectIndex.get(pEdge.getObject()).getName() + " -> " +
newNull + "[label=\"[" + pEdge.getOffset() + "]\"];";
} else {
return objectIndex.get(pEdge.getObject()).getName() + " -> value_" + pEdge.getValue() + "[label=\"[" +
pEdge.getOffset() + "]\"];";
}
}
private String smgPTEdgeAsDot(final SMGEdgePointsTo pEdge) {
return "value_" + pEdge.getValue() + " -> " + objectIndex.get(pEdge.getObject()).getName() + "[label=\"+" +
pEdge.getOffset() + "b\"];";
}
private static String smgValueAsDot(final int pValue, final String pExplicit) {
return "value_" + pValue + "[label=\"#" + pValue + pExplicit + "\"];";
}
@SuppressWarnings("unused")
private static String neqRelationAsDot(final Integer v1, final Integer v2) {
String targetNode;
String returnString = "";
if (v2.equals(0)) {
targetNode = newNullLabel();
returnString = targetNode + "[shape=plaintext, label=\"NULL\", fontcolor=\"red\"];\n";
} else {
targetNode = "value_" + v2;
}
return returnString + "value_" + v1 + " -> " + targetNode + "[color=\"red\", fontcolor=\"red\", label=\"neq\"]";
}
private String newLineWithOffset(final String pLine) {
return Strings.repeat(" ", offset) + pLine + "\n";
}
}
|
package be.continuum.slice.event;
import be.continuum.slice.value.PhoneNumber;
import lombok.Builder;
import lombok.Data;
/**
* AddPhoneNumber
*
* @author bartgerard
* @version v0.0.1
*/
@Data
@Builder
public class PhoneNumberRemovedEvent {
private final PhoneNumber phoneNumber;
}
|
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Company company = new Company();
ArrayList<Employee> arrayListManager = new ArrayList<>();
ArrayList<Employee> arrayListTopManager = new ArrayList<>();
ArrayList<Employee> arrayListOperator = new ArrayList<>();
for (int i = 0; i<180;i++){
arrayListOperator.add(new Operator());
}
for (int i = 0; i<80;i++){
arrayListManager.add(new Manager(company));
}
for (int i = 0; i<10;i++){
arrayListTopManager.add(new TopManager(company));
}
company.hireAll(arrayListTopManager);
company.hireAll(arrayListManager);
company.hireAll(arrayListOperator);
company.getTopSalaryStaff(15);
System.out.println("================");
company.getLowestSalaryStaff(30);
System.out.println("================");
System.out.println("Количество работников в компании - " + company.getEmployeesCount());
int dismissalList = company.getEmployeesCount() / 2;
for (int i = 0; i < dismissalList; i++) {
company.fire(i);
}
System.out.println("================");
company.getTopSalaryStaff(15);
System.out.println("================");
company.getLowestSalaryStaff(30);
System.out.println("Количество работников в компании - " + company.getEmployeesCount());
}
}
|
package net.minecraft.block;
public class BlockHalfStoneSlab extends BlockStoneSlab {
public boolean isDouble() {
return false;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\BlockHalfStoneSlab.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.clerezza.sparql.query.impl;
import org.apache.clerezza.BlankNodeOrIRI;
import org.apache.clerezza.RDFTerm;
import org.apache.clerezza.sparql.query.*;
/**
*
* @author hasan
*/
public class SimplePropertyPathPattern implements PropertyPathPattern {
private ResourceOrVariable subject;
private PropertyPathExpressionOrVariable propertyPathExpression;
private ResourceOrVariable object;
public SimplePropertyPathPattern(ResourceOrVariable subject,
PropertyPathExpressionOrVariable propertyPathExpression,
ResourceOrVariable object) {
if (subject == null) {
throw new IllegalArgumentException("Invalid subject: null");
}
if (propertyPathExpression == null) {
throw new IllegalArgumentException("Invalid property path expression: null");
}
if (object == null) {
throw new IllegalArgumentException("Invalid object: null");
}
this.subject = subject;
this.propertyPathExpression = propertyPathExpression;
this.object = object;
}
public SimplePropertyPathPattern(Variable subject, Variable propertyPathExpression, Variable object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(BlankNodeOrIRI subject, Variable propertyPathExpression, Variable object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(Variable subject, Variable propertyPathExpression, RDFTerm object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(BlankNodeOrIRI subject, Variable propertyPathExpression, RDFTerm object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(Variable subject, PropertyPathExpression propertyPathExpression, Variable object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(BlankNodeOrIRI subject, PropertyPathExpression propertyPathExpression, Variable object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(Variable subject, PropertyPathExpression propertyPathExpression, RDFTerm object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
public SimplePropertyPathPattern(BlankNodeOrIRI subject, PropertyPathExpression propertyPathExpression, RDFTerm object) {
this(new ResourceOrVariable(subject), new PropertyPathExpressionOrVariable(propertyPathExpression),
new ResourceOrVariable(object));
}
@Override
public ResourceOrVariable getSubject() {
return subject;
}
@Override
public PropertyPathExpressionOrVariable getPropertyPathExpression() {
return propertyPathExpression;
}
@Override
public ResourceOrVariable getObject() {
return object;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PropertyPathPattern)) {
return false;
}
final PropertyPathPattern other = (PropertyPathPattern) obj;
if (!this.subject.equals(other.getSubject())) {
return false;
}
if (!this.propertyPathExpression.equals(other.getPropertyPathExpression())) {
return false;
}
if (!this.object.equals(other.getObject())) {
return false;
}
return true;
}
@Override
public int hashCode() {
return (subject.hashCode() >> 1) ^ propertyPathExpression.hashCode() ^ (object.hashCode() << 1);
}
}
|
package controllers;
import java.util.*;
import notifiers.*;
import play.Logger;
import play.data.validation.*;
import play.mvc.*;
import models.*;
import utils.*;
public class Invites extends Application {
public static void invite() {
render();
}
}
|
package polyhedra;
import java.util.Comparator;
class ByArea implements Comparator<Prism> {
public int compare(Prism p1, Prism p2) {
return (int)(p1.area() - p2.area());
}
}
|
package br.com.smarthouse.modelgenerics;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Entity que modela o Sub Ambiente
*
* @author Rafael Casabona
*
*/
@Entity
@Table(name = "SUB_AMBIENTE")
public class SubAmbiente implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7952621692447590860L;
@Id
@Column(name = "ID_SUBAMBIENTE")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "TIPO_AMBIENTE")
private TipoAmbiente tipoAmbiente;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_LUZES")
private List<Luz> luzes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTipoAmbiente() {
return tipoAmbiente.getNome();
}
public void setTipoAmbiente(TipoAmbiente tipoAmbiente) {
this.tipoAmbiente = tipoAmbiente;
}
public List<Luz> getLuzes() {
return luzes;
}
public void setLuzes(List<Luz> luzes) {
this.luzes = luzes;
}
}
|
import java.io.File;
import java.io.FileOutputStream;
import org.jdom2.*;
import org.jdom2.output.*;
/**
* GenerateurXML écrit dans un fichier, à charque fin de lot, toutes
* les données lues en indiquant le lot dans le fichier XML.
*
* @author Xavier Crégut <Prenom.Nom@enseeiht.fr>
*/
public class GenerateurXML extends Traitement {
String filename;
public GenerateurXML(String arg) {
this.filename = arg;
}
@Override
public final void gererFinLotLocal(String nomLot) {
try {
Element root = new Element("root");
Document doc = new Document(root);
XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
xmlOutput.output(doc, new FileOutputStream(new File(this.filename)));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
protected String toStringComplement() {
return String.format("\"%s\"", this.filename);
}
}
|
import java.util.*;
class LookAndSay {
public String[] lookAndSay(int n) {
if (n == 1) {
return new String[]{"1"};
}
String[] result = new String[n];
result[0] = "1";
for (int i = 1; i < n; i++) {
int len = result[i - 1].length();
int count = 1;
String str = "";
for (int j = 1; j < len; j++) {
if (result[i - 1].charAt(j) != result[i - 1].charAt(j - 1)) {
str += count;
str += result[i - 1].charAt(j - 1);
count = 1;
} else {
count++;
}
}
str += count;
str += result[i - 1].charAt(len - 1);
result[i] = str;
}
return result;
}
public static void main(String[] args) {
LookAndSay test = new LookAndSay();
int n = Integer.parseInt(args[0]);
String[] result = test.lookAndSay(n);
System.out.println(Arrays.toString(result));
}
}
|
/**
* 155. Min Stack
* 双栈法不一定getMin()最快,但是所有操作平均速度应该是很快的
*/
public class Solution {
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.printStack();
minStack.push(0);
minStack.printStack();
minStack.push(-3);
minStack.printStack();
System.out.println("min:" + minStack.getMin()); // return -3
minStack.pop();
minStack.printStack();
System.out.println("top:" + minStack.top()); // return 0
System.out.println("min:" + minStack.getMin());// return -2
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.