text
stringlengths
10
2.72M
package ch.ethz.geco.t4j.internal.json; import reactor.util.annotation.NonNull; import reactor.util.annotation.Nullable; import java.util.List; /** * Represents an error object, you'll encounter in API responses. */ public class ErrorObject { public List<SingleErrorObject> errors; public static class SingleErrorObject { @NonNull public String message = ""; @NonNull public String scope = ""; @Nullable public String property_path; @Nullable public String invalid_value; @Nullable public String type; } }
package com.phila.samergigabyte.philabooksx; /** * Created by SamerGigaByte on 27/11/2015. */ public class OnlineBook extends Book { String bookUrl; }
package old.DefaultPackage; public class Code04 { public static String convert(String s, int numRows) { char[] str = s.toCharArray(); StringBuffer[] sb = new StringBuffer[numRows]; for(int i = 0; i < sb.length; ++i) { sb[i] = new StringBuffer(); } int i = 0; while(i < str.length) { for(int j = 0; j < numRows && i < str.length; ++j) sb[j].append(str[i++]); for(int j = numRows - 2; j >= 1 && i < str.length; --j) sb[j].append(str[i++]); } StringBuffer result = new StringBuffer(); for(int j = 0; j < numRows; ++j) { result.append(sb[j]); } return result.toString(); } public static void main(String[] args) { System.out.println(convert("PAYPALISHIRING",3)); } }
package mbd.student.gurukustudent.model.student; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by Naufal on 08/03/2018. */ public class UpdateProfileResponse { @SerializedName("status") @Expose private Integer status; @SerializedName("message") @Expose private String message; @SerializedName("data") @Expose private Student student; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
package org.vaadin.peter.contextmenu; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.EventListener; import java.util.EventObject; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import org.vaadin.peter.contextmenu.client.ContextMenuClientRpc; import org.vaadin.peter.contextmenu.client.ContextMenuServerRpc; import org.vaadin.peter.contextmenu.client.ContextMenuState; import org.vaadin.peter.contextmenu.client.ContextMenuState.ContextMenuItemState; import com.vaadin.event.ItemClickEvent; import com.vaadin.event.ItemClickEvent.ItemClickListener; import com.vaadin.server.AbstractClientConnector; import com.vaadin.server.AbstractExtension; import com.vaadin.server.Resource; import com.vaadin.shared.MouseEventDetails.MouseButton; import com.vaadin.ui.Component; import com.vaadin.ui.Table; import com.vaadin.ui.Table.FooterClickEvent; import com.vaadin.ui.Table.FooterClickListener; import com.vaadin.ui.Table.HeaderClickEvent; import com.vaadin.ui.Table.HeaderClickListener; import com.vaadin.ui.Tree; import com.vaadin.ui.UI; import com.vaadin.util.ReflectTools; /** * ContextMenu is an extension which can be attached to any Vaadin component to * display a popup context menu. Most useful the menu is when attached for * example to Tree or Table which support item and property based context menu * detection. * * @author Peter / Vaadin */ public class ContextMenu extends AbstractExtension { private static final long serialVersionUID = 4275181115413786498L; private final Map<String, ContextMenuItem> items; private final ContextMenuServerRpc serverRPC = new ContextMenuServerRpc() { private static final long serialVersionUID = 5622864428554337992L; @Override public void itemClicked(String itemId, boolean menuClosed) { ContextMenuItem item = items.get(itemId); if (item == null) { return; } item.notifyClickListeners(); fireEvent(new ContextMenuItemClickEvent(item)); } @Override public void onContextMenuOpenRequested(int x, int y, String connectorId) { fireEvent(new ContextMenuOpenedOnComponentEvent(ContextMenu.this, x, y, (Component) UI.getCurrent().getConnectorTracker() .getConnector(connectorId))); } @Override public void contextMenuClosed() { fireEvent(new ContextMenuClosedEvent(ContextMenu.this)); } }; public ContextMenu() { registerRpc(serverRPC); items = new HashMap<String, ContextMenu.ContextMenuItem>(); setOpenAutomatically(true); setHideAutomatically(true); } protected String getNextId() { return UUID.randomUUID().toString(); } /** * Enables or disables open automatically feature. If open automatically is * on, it means that context menu will always be opened when it's host * component is right clicked. This will happen on client side without * server round trip. If automatic opening is turned off, context menu will * only open when server side open(x, y) is called. If automatic opening is * disabled you will need a listener implementation for context menu that is * called upon client side click event. Another option is to extend context * menu and handle the right clicking internally with case specific listener * implementation and inside it call open(x, y) method. * * @param openAutomatically */ public void setOpenAutomatically(boolean openAutomatically) { getState().setOpenAutomatically(openAutomatically); } /** * @return true if open automatically is on. If open automatically is on, it * means that context menu will always be opened when it's host * component is right clicked. If automatic opening is turned off, * context menu will only open when server side open(x, y) is * called. Automatic opening avoid having to make server roundtrip * whereas "manual" opening allows to have logic in menu before * opening it. */ public boolean isOpenAutomatically() { return getState().isOpenAutomatically(); } /** * Sets menu to hide automatically after mouse cliks on menu items or area * off the menu. If automatic hiding is disabled menu will stay open as long * as hide is called from the server side. * * @param hideAutomatically */ public void setHideAutomatically(boolean hideAutomatically) { getState().setHideAutomatically(hideAutomatically); } /** * @return true if context menu is hiding automatically after clicks, false * otherwise. */ public boolean isHideAutomatically() { return getState().isHideAutomatically(); } /** * Adds new item to context menu root with given caption. * * @param caption * @return reference to newly added item */ public ContextMenuItem addItem(String caption) { ContextMenuItemState itemState = getState().addChild(caption, getNextId()); ContextMenuItem item = new ContextMenuItem(null, itemState); items.put(itemState.id, item); return item; } /** * Adds new item to context menu root with given icon without caption. * * @param icon * @return reference to newly added item */ public ContextMenuItem addItem(Resource icon) { ContextMenuItem item = addItem(""); item.setIcon(icon); return item; } /** * Adds new item to context menu root with given caption and icon. * * @param caption * @param icon * @return reference to newly added item */ public ContextMenuItem addItem(String caption, Resource icon) { ContextMenuItem item = addItem(caption); item.setIcon(icon); return item; } /** * Removes given context menu item from the context menu. The given item can * be a root item or leaf item or anything in between. If given given is not * found from the context menu structure, this method has no effect. * * @param contextMenuItem */ public void removeItem(ContextMenuItem contextMenuItem) { if (!hasMenuItem(contextMenuItem)) { return; } if (contextMenuItem.isRootItem()) { getState().getRootItems().remove(contextMenuItem.state); } else { ContextMenuItem parent = contextMenuItem.getParent(); parent.state.getChildren().remove(contextMenuItem.state); } Set<ContextMenuItem> children = contextMenuItem.getAllChildren(); items.remove(contextMenuItem.state.id); for (ContextMenuItem child : children) { items.remove(child.state.id); } markAsDirty(); } private boolean hasMenuItem(ContextMenuItem contextMenuItem) { return items.containsKey(contextMenuItem.state.id); } /** * Removes all items from the context menu. */ public void removeAllItems() { items.clear(); getState().getRootItems().clear(); } /** * Assigns this as the context menu of given table. * * @param table */ public void setAsTableContextMenu(final Table table) { extend(table); setOpenAutomatically(false); table.addItemClickListener(new ItemClickEvent.ItemClickListener() { private static final long serialVersionUID = -348059189217149508L; @Override public void itemClick(ItemClickEvent event) { if (event.getButton() == MouseButton.RIGHT) { fireEvent(new ContextMenuOpenedOnTableRowEvent( ContextMenu.this, table, event.getItemId(), event .getPropertyId())); open(event.getClientX(), event.getClientY()); } } }); table.addHeaderClickListener(new HeaderClickListener() { private static final long serialVersionUID = -5880755689414670581L; @Override public void headerClick(HeaderClickEvent event) { if (event.getButton() == MouseButton.RIGHT) { fireEvent(new ContextMenuOpenedOnTableHeaderEvent( ContextMenu.this, table, event.getPropertyId())); open(event.getClientX(), event.getClientY()); } } }); table.addFooterClickListener(new FooterClickListener() { private static final long serialVersionUID = 2884227013964132482L; @Override public void footerClick(FooterClickEvent event) { if (event.getButton() == MouseButton.RIGHT) { fireEvent(new ContextMenuOpenedOnTableHeaderEvent( ContextMenu.this, table, event.getPropertyId())); open(event.getClientX(), event.getClientY()); } } }); } /** * Assigns this as context menu of given tree. * * @param tree */ public void setAsTreeContextMenu(final Tree tree) { extend(tree); setOpenAutomatically(false); tree.addItemClickListener(new ItemClickListener() { private static final long serialVersionUID = 338499886052623304L; @Override public void itemClick(ItemClickEvent event) { if (event.getButton() == MouseButton.RIGHT) { fireEvent(new ContextMenuOpenedOnTreeItemEvent( ContextMenu.this, tree, event.getItemId())); open(event.getClientX(), event.getClientY()); } } }); } /** * Assigns this as context menu of given component which will react to right * mouse button click. * * @param component */ public void setAsContextMenuOf(AbstractClientConnector component) { if (component instanceof Table) { setAsTableContextMenu((Table) component); } else if (component instanceof Tree) { setAsTreeContextMenu((Tree) component); } else { super.extend(component); } } /** * Opens the context menu to given coordinates. ContextMenu must extend * component before calling this method. This method is only intended for * opening the context menu from server side when using * {@link #ContextMenuOpenedListener.ComponentListener} * * @param x * @param y */ public void open(int x, int y) { getRpcProxy(ContextMenuClientRpc.class).showContextMenu(x, y); } /** * * @param component */ public void open(Component component) { getRpcProxy(ContextMenuClientRpc.class).showContextMenuRelativeTo( component.getConnectorId()); } /** * Closes the context menu from server side */ public void hide() { getRpcProxy(ContextMenuClientRpc.class).hide(); } @Override protected ContextMenuState getState() { return (ContextMenuState) super.getState(); } /** * Adds click listener to context menu. This listener will be invoked when * any of the menu items in this menu are clicked. * * @param clickListener */ public void addItemClickListener( ContextMenu.ContextMenuItemClickListener clickListener) { addListener(ContextMenuItemClickEvent.class, clickListener, ContextMenuItemClickListener.ITEM_CLICK_METHOD); } /** * Adds listener that will be invoked when context menu is opened from * com.vaadin.ui.Table component. * * @param contextMenuTableListener */ public void addContextMenuTableListener( ContextMenu.ContextMenuOpenedListener.TableListener contextMenuTableListener) { addListener( ContextMenuOpenedOnTableRowEvent.class, contextMenuTableListener, ContextMenuOpenedListener.TableListener.MENU_OPENED_FROM_TABLE_ROW_METHOD); addListener( ContextMenuOpenedOnTableHeaderEvent.class, contextMenuTableListener, ContextMenuOpenedListener.TableListener.MENU_OPENED_FROM_TABLE_HEADER_METHOD); addListener( ContextMenuOpenedOnTableFooterEvent.class, contextMenuTableListener, ContextMenuOpenedListener.TableListener.MENU_OPENED_FROM_TABLE_FOOTER_METHOD); } /** * Adds listener that will be invoked when context menu is openef from * com.vaadin.ui.Tree component. * * @param contextMenuTreeListener */ public void addContextMenuTreeListener( ContextMenu.ContextMenuOpenedListener.TreeListener contextMenuTreeListener) { addListener( ContextMenuOpenedOnTreeItemEvent.class, contextMenuTreeListener, ContextMenuOpenedListener.TreeListener.MENU_OPENED_FROM_TREE_ITEM_METHOD); } /** * Adds listener that will be invoked when context menu is closed. * * @param contextMenuClosedListener */ public void addContextMenuCloseListener( ContextMenuClosedListener contextMenuClosedListener) { addListener(ContextMenuClosedEvent.class, contextMenuClosedListener, ContextMenuClosedListener.MENU_CLOSED); } /** * Adds listener that will be invoked when context menu is opened from the * component to which it's assigned to. * * @param contextMenuComponentListener */ public void addContextMenuComponentListener( ContextMenu.ContextMenuOpenedListener.ComponentListener contextMenuComponentListener) { addListener( ContextMenuOpenedOnComponentEvent.class, contextMenuComponentListener, ContextMenuOpenedListener.ComponentListener.MENU_OPENED_FROM_COMPONENT); } /** * ContextMenuItem represents one clickable item in the context menu. Item * may have sub items. * * @author Peter Lehto / Vaadin Ltd * */ public class ContextMenuItem implements Serializable { private static final long serialVersionUID = -6514832427611690050L; private ContextMenuItem parent; private final ContextMenuItemState state; private final List<ContextMenu.ContextMenuItemClickListener> clickListeners; private Object data; protected ContextMenuItem(ContextMenuItem parent, ContextMenuItemState itemState) { this.parent = parent; if (itemState == null) { throw new NullPointerException( "Context menu item state must not be null"); } clickListeners = new ArrayList<ContextMenu.ContextMenuItemClickListener>(); this.state = itemState; } protected Set<ContextMenuItem> getAllChildren() { Set<ContextMenuItem> children = new HashSet<ContextMenu.ContextMenuItem>(); for (ContextMenuItemState childState : state.getChildren()) { ContextMenuItem child = items.get(childState.id); children.add(child); children.addAll(child.getAllChildren()); } return children; } /** * @return parent item of this menu item. Null if this item is a root * item. */ protected ContextMenuItem getParent() { return parent; } protected void notifyClickListeners() { for (ContextMenu.ContextMenuItemClickListener clickListener : clickListeners) { clickListener .contextMenuItemClicked(new ContextMenuItemClickEvent( this)); } } /** * Associates given object with this menu item. Given object can be * whatever application specific if necessary. * * @param data */ public void setData(Object data) { this.data = data; } /** * @return Object associated with ContextMenuItem. */ public Object getData() { return data; } /** * Adds new item as this item's sub item with given caption * * @param caption * @return reference to newly created item. */ public ContextMenuItem addItem(String caption) { ContextMenuItemState childItemState = state.addChild(caption, getNextId()); ContextMenuItem item = new ContextMenuItem(this, childItemState); items.put(childItemState.id, item); markAsDirty(); return item; } /** * Adds new item as this item's sub item with given icon * * @param icon * @return reference to newly added item */ public ContextMenuItem addItem(Resource icon) { ContextMenuItem item = this.addItem(""); item.setIcon(icon); return item; } /** * Adds new item as this item's sub item with given caption and icon * * @param caption * @param icon * @return reference to newly added item */ public ContextMenuItem addItem(String caption, Resource icon) { ContextMenuItem item = this.addItem(caption); item.setIcon(icon); return item; } /** * Sets given resource as icon of this menu item. * * @param icon */ public void setIcon(Resource icon) { setResource(state.id, icon); } /** * @return current icon */ public Resource getIcon() { return getResource(state.id); } /** * Sets or disables separator line under this item * * @param visible */ public void setSeparatorVisible(boolean separatorVisible) { state.separator = separatorVisible; markAsDirty(); } /** * @return true if separator line is visible after this item, false * otherwise */ public boolean hasSeparator() { return state.separator; } /** * Enables or disables this menu item * * @param enabled */ public void setEnabled(boolean enabled) { state.enabled = enabled; markAsDirty(); } /** * @return true if menu item is enabled, false otherwise */ public boolean isEnabled() { return state.enabled; } /** * @return true if this menu item has a sub menu */ public boolean hasSubMenu() { return state.getChildren().size() > 0; } /** * @return true if this item is root item, false otherwise. */ public boolean isRootItem() { return parent == null; } /** * Adds context menu item click listener only to this item. This * listener will be invoked only when this item is clicked. * * @param clickListener */ public void addItemClickListener( ContextMenu.ContextMenuItemClickListener clickListener) { this.clickListeners.add(clickListener); } /** * Removes given click listener from this item. Removing listener * affects only this context menu item. * * @param clickListener */ public void removeItemClickListener( ContextMenu.ContextMenuItemClickListener clickListener) { this.clickListeners.remove(clickListener); } /** * Add a new style to the menu item. This method is following the same * semantics as {@link Component#addStyleName(String)}. * * @param style * the new style to be added to the component */ public void addStyleName(String style) { if (style == null || style.isEmpty()) { return; } if (style.contains(" ")) { // Split space separated style names and add them one by one. StringTokenizer tokenizer = new StringTokenizer(style, " "); while (tokenizer.hasMoreTokens()) { addStyleName(tokenizer.nextToken()); } return; } state.getStyles().add(style); markAsDirty(); } /** * Remove a style name from this menu item. This method is following the * same semantics as {@link Component#removeStyleName(String)} . * * @param style * the style name or style names to be removed */ public void removeStyleName(String style) { if (state.getStyles().isEmpty()) { return; } StringTokenizer tokenizer = new StringTokenizer(style, " "); while (tokenizer.hasMoreTokens()) { state.getStyles().remove(tokenizer.nextToken()); } } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof ContextMenuItem) { return state.id.equals(((ContextMenuItem) other).state.id); } return false; } @Override public int hashCode() { return state.id.hashCode(); } /** * Changes the caption of the menu item * * @param newCaption */ public void setCaption(String newCaption) { state.caption = newCaption; markAsDirty(); } } /** * ContextMenuItemClickListener is listener for context menu items wanting * to notify listeners about item click */ public interface ContextMenuItemClickListener extends EventListener { public static final Method ITEM_CLICK_METHOD = ReflectTools.findMethod( ContextMenuItemClickListener.class, "contextMenuItemClicked", ContextMenuItemClickEvent.class); /** * Called by the context menu item when it's clicked * * @param event * containing the information of which item was clicked */ public void contextMenuItemClicked(ContextMenuItemClickEvent event); } /** * ContextMenuItemClickEvent is an event produced by the context menu item * when it is clicked. Event contains method for retrieving the clicked item * and menu from which the click event originated. */ public static class ContextMenuItemClickEvent extends EventObject { private static final long serialVersionUID = -3301204853129409248L; public ContextMenuItemClickEvent(Object component) { super(component); } } /** * ContextMenuClosedListener is used to listen for the event that the * context menu is closed, either when a item is clicked or when the popup * is canceled. */ public interface ContextMenuClosedListener extends EventListener { public static final Method MENU_CLOSED = ReflectTools.findMethod( ContextMenuClosedListener.class, "onContextMenuClosed", ContextMenuClosedEvent.class); /** * Called when the context menu is closed * * @param event */ public void onContextMenuClosed(ContextMenuClosedEvent event); } /** * ContextMenuClosedEvent is an event fired by the context menu when it's * closed. */ public static class ContextMenuClosedEvent extends EventObject { private static final long serialVersionUID = -5705205542849351984L; private final ContextMenu contextMenu; public ContextMenuClosedEvent(ContextMenu contextMenu) { super(contextMenu); this.contextMenu = contextMenu; } public ContextMenu getContextMenu() { return contextMenu; } } /** * ContextMenuOpenedListener is used to modify the content of context menu * based on what was clicked. For example TableListener can be used to * modify context menu based on certain table component clicks. * * @author Peter Lehto / Vaadin Ltd * */ public interface ContextMenuOpenedListener extends EventListener { /** * ComponentListener is used when context menu is extending a component * and works in mode where auto opening is disabled. For example if * ContextMenu is assigned to a Layout and layout is right clicked when * auto open feature is disabled, the open listener would be called * instead of menu opening automatically. Example usage is for example * as follows: * * event.getContextMenu().open(event.getRequestSourceComponent()); * * @author Peter Lehto / Vaadin */ public interface ComponentListener extends ContextMenuOpenedListener { public static final Method MENU_OPENED_FROM_COMPONENT = ReflectTools .findMethod( ContextMenuOpenedListener.ComponentListener.class, "onContextMenuOpenFromComponent", ContextMenuOpenedOnComponentEvent.class); /** * Called by the context menu when it's opened by clicking on * component. * * @param event */ public void onContextMenuOpenFromComponent( ContextMenuOpenedOnComponentEvent event); } /** * ContextMenuOpenedListener.TableListener sub interface for table * related context menus * * @author Peter Lehto / Vaadin Ltd */ public interface TableListener extends ContextMenuOpenedListener { public static final Method MENU_OPENED_FROM_TABLE_ROW_METHOD = ReflectTools .findMethod(ContextMenuOpenedListener.TableListener.class, "onContextMenuOpenFromRow", ContextMenuOpenedOnTableRowEvent.class); public static final Method MENU_OPENED_FROM_TABLE_HEADER_METHOD = ReflectTools .findMethod(ContextMenuOpenedListener.TableListener.class, "onContextMenuOpenFromHeader", ContextMenuOpenedOnTableHeaderEvent.class); public static final Method MENU_OPENED_FROM_TABLE_FOOTER_METHOD = ReflectTools .findMethod(ContextMenuOpenedListener.TableListener.class, "onContextMenuOpenFromFooter", ContextMenuOpenedOnTableFooterEvent.class); /** * Called by the context menu when it's opened by clicking table * component's row * * @param event */ public void onContextMenuOpenFromRow( ContextMenuOpenedOnTableRowEvent event); /** * Called by the context menu when it's opened by clicking table * component's header * * @param event */ public void onContextMenuOpenFromHeader( ContextMenuOpenedOnTableHeaderEvent event); /** * Called by the context menu when it's opened by clicking table * component's footer * * @param event */ public void onContextMenuOpenFromFooter( ContextMenuOpenedOnTableFooterEvent event); } public interface TreeListener extends ContextMenuOpenedListener { public static final Method MENU_OPENED_FROM_TREE_ITEM_METHOD = ReflectTools .findMethod(ContextMenuOpenedListener.TreeListener.class, "onContextMenuOpenFromTreeItem", ContextMenuOpenedOnTreeItemEvent.class); /** * Called by the context menu when it's opened by clicking item on a * tree. * * @param event */ public void onContextMenuOpenFromTreeItem( ContextMenuOpenedOnTreeItemEvent event); } } /** * ContextMenuOpenedOnTreeItemEvent is an event fired by the context menu * when it's opened by clicking on tree item. */ public static class ContextMenuOpenedOnTreeItemEvent extends EventObject { private static final long serialVersionUID = -7705205542849351984L; private final Object itemId; private final ContextMenu contextMenu; public ContextMenuOpenedOnTreeItemEvent(ContextMenu contextMenu, Tree tree, Object itemId) { super(tree); this.contextMenu = contextMenu; this.itemId = itemId; } public ContextMenu getContextMenu() { return contextMenu; } public Object getItemId() { return itemId; } } /** * ContextMenuOpenedOnTableHeaderEvent is an event fired by the context menu * when it's opened by clicking on table header row. */ public static class ContextMenuOpenedOnTableHeaderEvent extends EventObject { private static final long serialVersionUID = -1220618848356241248L; private final Object propertyId; private final ContextMenu contextMenu; public ContextMenuOpenedOnTableHeaderEvent(ContextMenu contextMenu, Table source, Object propertyId) { super(source); this.contextMenu = contextMenu; this.propertyId = propertyId; } public ContextMenu getContextMenu() { return contextMenu; } public Object getPropertyId() { return propertyId; } } /** * ContextMenuOpenedOnTableFooterEvent is an event that is fired by the * context menu when it's opened by clicking on table footer */ public static class ContextMenuOpenedOnTableFooterEvent extends EventObject { private static final long serialVersionUID = 1999781663913723438L; private final Object propertyId; private final ContextMenu contextMenu; public ContextMenuOpenedOnTableFooterEvent(ContextMenu contextMenu, Table source, Object propertyId) { super(source); this.contextMenu = contextMenu; this.propertyId = propertyId; } public ContextMenu getContextMenu() { return contextMenu; } public Object getPropertyId() { return propertyId; } } /** * ContextMenuOpenedOnTableRowEvent is an event that is fired when context * menu is opened by clicking on table row. */ public static class ContextMenuOpenedOnTableRowEvent extends EventObject { private static final long serialVersionUID = -470218301318358912L; private final ContextMenu contextMenu; private final Object propertyId; private final Object itemId; public ContextMenuOpenedOnTableRowEvent(ContextMenu contextMenu, Table table, Object itemId, Object propertyId) { super(table); this.contextMenu = contextMenu; this.itemId = itemId; this.propertyId = propertyId; } public ContextMenu getContextMenu() { return contextMenu; } public Object getItemId() { return itemId; } public Object getPropertyId() { return propertyId; } } /** * ContextMenuOpenedOnComponentEvent is an event fired by the context menu * when it's opened from a component * */ public static class ContextMenuOpenedOnComponentEvent extends EventObject { private static final long serialVersionUID = 947108059398706966L; private final ContextMenu contextMenu; private final int x; private final int y; public ContextMenuOpenedOnComponentEvent(ContextMenu contextMenu, int x, int y, Component component) { super(component); this.contextMenu = contextMenu; this.x = x; this.y = y; } /** * @return ContextMenu that was opened. */ public ContextMenu getContextMenu() { return contextMenu; } /** * @return Component which initiated the context menu open request. */ public Component getRequestSourceComponent() { return (Component) getSource(); } /** * @return x-coordinate of open position. */ public int getX() { return x; } /** * @return y-coordinate of open position. */ public int getY() { return y; } } }
package net.sf.throughglass.templates; import android.graphics.Bitmap; /** * Created by yowenlove on 14-8-20. */ public interface IFragmentInfo { String onGetTitle(); String onGetSubTitle(); Bitmap onGetIcon(); }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Wireformats; import edu.colostate.cs.cs414.soggyZebras.rollerball.Game.Location; import edu.colostate.cs.cs414.soggyZebras.rollerball.Game.Piece; import java.io.*; import java.util.Base64; import java.util.Map; public class ServerRespondsGameState implements Event { //Information to be serialized or deserialized private int message_type; private int gameID; private Map<Location,Piece> board; /** * * @param m */ public ServerRespondsGameState(Map<Location,Piece> m, int id) { this.message_type = eServer_Responds_Game_State; this.gameID = id; this.board = m ; } /** * * @throws IOException * @throws ClassNotFoundException */ public ServerRespondsGameState(String input) throws IOException, ClassNotFoundException { byte[] data = Base64.getDecoder().decode(input); ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(data)); // deserialize the objects into their proper local variables this.message_type = oin.readInt(); this.gameID = oin.readInt(); this.board = (Map<Location,Piece>) oin.readObject(); // Close streams oin.close(); } @Override public String getFile() throws IOException { // Create a new String, file output stream, object output stream ByteArrayOutputStream ostream = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(ostream); oout.writeInt(this.message_type); oout.writeInt(this.gameID); oout.writeObject(this.board); //flush the objects to the stream and close the streams oout.flush(); oout.close(); return Base64.getEncoder().encodeToString(ostream.toByteArray()); } @Override public int getType() { return this.message_type; } /** * * @return Map<Location,Piece> */ public Map<Location,Piece>getMap(){ return this.board; } public int getGameID(){ return this.gameID; } }
package lxy.liying.circletodo.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobUser; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.LogInListener; import cn.bmob.v3.listener.QueryListener; import lxy.liying.circletodo.R; import lxy.liying.circletodo.app.App; import lxy.liying.circletodo.domain.CircleUser; import lxy.liying.circletodo.utils.Constants; import lxy.liying.circletodo.utils.ErrorCodes; import lxy.liying.circletodo.utils.StringUtils; /** * ======================================================= * 版权:©Copyright LiYing 2015-2016. All rights reserved. * 作者:liying * 日期:2016/8/1 12:41 * 版本:1.0 * 描述:使用邮箱+密码登录方式 * 备注: * ======================================================= */ public class LoginByEmailActivity extends BaseActivity implements View.OnClickListener { private EditText etLoginEmail, etLoginPassword; private TextView tvToLoginByUsername; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_by_email); actionBarNavigator(); etLoginEmail = (EditText) findViewById(R.id.etLoginEmail); etLoginPassword = (EditText) findViewById(R.id.etLoginPassword); tvToLoginByUsername = (TextView) findViewById(R.id.tvToLoginByUsername); Button btnLogin = (Button) findViewById(R.id.btnLogin); btnLogin.setOnClickListener(this); } /** * 使用邮箱+密码的方式进行登录 * * @param v */ @Override public void onClick(View v) { final String email = etLoginEmail.getText().toString(); String password = etLoginPassword.getText().toString(); password = StringUtils.encryptToSHA1(password); // 查看是否已经验证邮箱 BmobQuery<CircleUser> query = new BmobQuery<CircleUser>(); final String finalPassword = password; query.getObject(App.currentUser.getObjectId(), new QueryListener<CircleUser>() { @Override public void done(CircleUser object, BmobException e) { if (e == null) { boolean verified = object.getEmailVerified(); if (verified) { // 邮箱已验证 loginViaEmail(email, finalPassword); } else { App.getInstance().showToast("邮箱未验证,无法通过邮箱登录。"); } } else { // Log.i("bmob","失败:"+e.getMessage()+","+e.getErrorCode()); App.getInstance().showToast(ErrorCodes.errorMsg.get(e.getErrorCode())); } } }); } private void loginViaEmail(String email, String password) { BmobUser.loginByAccount(email, password, new LogInListener<CircleUser>() { @Override public void done(CircleUser user, BmobException e) { if (user != null) { App.getInstance().showToast("登录成功"); // 设置登录成功用户为当前用户 App.currentUser = BmobUser.getCurrentUser(CircleUser.class); // 设置当前用户ID App.CURRENT_UID = App.currentUser.getUid(); // 通知CalendarActivity更新用户信息 setResult(Constants.REFRESH_USER_INFO_CODE); LoginByEmailActivity.this.finish(); // 关闭本页面 LoginByEmailActivity.this.overridePendingTransition(R.anim.push_right_in_ac, R.anim.push_right_out_ac); } else { // 提示错误信息 showErrorDialog(LoginByEmailActivity.this, "失败:" + ErrorCodes.errorMsg.get(e.getErrorCode()), false); } } }); } /** * 返回用户名+密码的登录方式 * * @param view */ public void toLoginByUsername(View view) { finish(); overridePendingTransition(R.anim.push_right_in_ac, R.anim.push_right_out_ac); } }
package com.hcg.web.Vo; public class PageResp { public Integer ErrorCode; //-1 代表系统错误 0代表请求成功 1 代表请求成功返回错误异常 public String msg; public Object object; public Integer getErrorCode() { return ErrorCode; } public void setErrorCode(Integer errorCode) { ErrorCode = errorCode; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public PageResp(Integer errorCode, String msg, Object object) { ErrorCode = errorCode; this.msg = msg; this.object = object; } public PageResp() { } }
package adcar.com.adcar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import adcar.com.utility.Strings; import adcar.com.utility.Utility; /** * Created by aditya on 07/03/16. */ public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent startVheeler = new Intent(context, MainActivity.class); startVheeler.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startVheeler); Utility.sendMessageToHandler(MainActivity.getHandler(), Strings.TOAST, "on boot we tried this"); Log.i("BOOT", "Boot Tried"); } }
package pro.likada.util.converter; import pro.likada.model.Trailer; import pro.likada.service.TrailerService; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; /** * Created by abuca on 10.03.17. */ @FacesConverter("trailerConverter") public class TrailerConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) { if (value != null && value.trim().length() > 0) { FacesContext context = FacesContext.getCurrentInstance(); TrailerService trailerService = context.getApplication().evaluateExpressionGet(context, "#{trailerService}", TrailerService.class); Trailer trailer = trailerService.findById(Long.parseLong(value)); return trailer; } return null; } @Override public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object object) { if(object!=null){ Trailer trailer = (Trailer) object; return trailer.getId()!=null ? trailer.getId().toString(): ""; } return ""; } }
package it.unibs.pajc; import java.io.*; import java.net.*; import java.util.Vector; public class ServerBS //extends Thread { ServerSocket server; private Vector <Socket> players = new Vector<Socket>(); public static void main(String[] args) { new ServerBS(); } public ServerBS() //costruttore { int port = 1234; System.out.println("Starting server on port: " + port + "\n"); try { server = new ServerSocket(port); int numPlayer = 0; //continua ad accettare connessioni e crea una partita ogni 2 while(true) { // chiamata bloccante, in attesa di una nuova connessione Socket client = server.accept(); numPlayer++; System.out.println("PLAYER " + numPlayer + " connected: "); System.out.println("Address: " + client.getInetAddress()); System.out.println("Port: " + client.getPort() + "\n"); //aggiunge la socket al vettore dei giocatori players.add(client); if(players.size() % 2 == 0) //se clients pari faccio partire una partita { //se ho 2 giocatori: pos 0 e pos 1, se ho 4 giocatori: pos 2 e pos 3, ... Partita partita = new Partita(players.size()/2, players.get(players.size() - 2), players.get(players.size() - 1)); //faccio partire la partita startando il thread Thread t = new Thread(partita); t.start(); } } } catch(IOException e) { System.out.println("\nErrore2: " + e.getMessage()); } } }
/* * Copyright 2002-2020 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.transaction.manager; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionManager; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.testfixture.CallCountingTransactionManager; import static org.assertj.core.api.Assertions.assertThat; /** * Integration test that verifies the behavior for transaction manager lookups * when one transaction manager is {@link Primary @Primary} and an additional * transaction manager is configured via the * {@link TransactionManagementConfigurer} API. * * @author Sam Brannen * @since 5.2.6 */ @SpringJUnitConfig @Transactional class LookUpTxMgrViaTransactionManagementConfigurerWithPrimaryTxMgrTests { @Autowired CallCountingTransactionManager primary; @Autowired @Qualifier("annotationDrivenTransactionManager") CallCountingTransactionManager annotationDriven; @Test void transactionalTest() { assertThat(primary.begun).isEqualTo(0); assertThat(primary.inflight).isEqualTo(0); assertThat(primary.commits).isEqualTo(0); assertThat(primary.rollbacks).isEqualTo(0); assertThat(annotationDriven.begun).isEqualTo(1); assertThat(annotationDriven.inflight).isEqualTo(1); assertThat(annotationDriven.commits).isEqualTo(0); assertThat(annotationDriven.rollbacks).isEqualTo(0); } @AfterTransaction void afterTransaction() { assertThat(primary.begun).isEqualTo(0); assertThat(primary.inflight).isEqualTo(0); assertThat(primary.commits).isEqualTo(0); assertThat(primary.rollbacks).isEqualTo(0); assertThat(annotationDriven.begun).isEqualTo(1); assertThat(annotationDriven.inflight).isEqualTo(0); assertThat(annotationDriven.commits).isEqualTo(0); assertThat(annotationDriven.rollbacks).isEqualTo(1); } @Configuration static class Config implements TransactionManagementConfigurer { @Bean @Primary PlatformTransactionManager primary() { return new CallCountingTransactionManager(); } @Bean @Override public TransactionManager annotationDrivenTransactionManager() { return new CallCountingTransactionManager(); } } }
package com.zc.pivas.checktype.dao; import com.zc.base.orm.mybatis.annotation.MyBatisRepository; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.pivas.checktype.bean.CheckTypeBean; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 核对类型DAO * * @author kunkka * @version 1.0 */ @MyBatisRepository("checkTypeDAO") public interface CheckTypeDAO { /*** * 分页查询核对类型 * @param bean 对象 * @param jqueryStylePaging 分页参数 * @return 分页数据 * @exception Exception e */ List<CheckTypeBean> getCheckTypeList(@Param("checkType") CheckTypeBean bean, @Param("paging") JqueryStylePaging jqueryStylePaging); /** * 分页查询总数 * 查询总数 * * @param bean 查询参数 * @return 页码 */ int getCheckTypeTotal(@Param("checkType") CheckTypeBean bean); /** * 添加核对类型表数据 * <p> * 新增核对类型 * * @param bean 核对类型 */ void addCheckType(CheckTypeBean bean); /** * 修改核对类型表数据 * <p> * 修改核对类型 * * @param bean 核对类型 */ void updateCheckType(CheckTypeBean bean); /** * 查询类型数据 * * @param bean 名称 * @return 审核错误类型 */ CheckTypeBean getCheckType(@Param("checkType") CheckTypeBean bean); /*** * 删除核对类型 * @param gid 主键id */ void delCheckType(String gid); /** * 查询审核类型:用于修改判断checkName * * @param bean 名称 * @return 审核错误类型 */ CheckTypeBean checkOrderIDIsExist(@Param("checkType") CheckTypeBean bean); /** * 查询审核类型数据:用于修改时判断orderid * 查询审核类型:用于修改时判断orderid * * @param bean 名称 * @return 审核错误类型 */ CheckTypeBean checkNameIsExist(@Param("checkType") CheckTypeBean bean); /** * 查询所有生效的核对列表 * * @return */ List<CheckTypeBean> queryCheckTypeAllList(@Param("checkType") String checkType); /** * 修改类型的时候判断和对类型是否存在 * * @param bean 查询条件 * @return 是否存在 */ CheckTypeBean checkTypeIsExitst(@Param("checkType") CheckTypeBean bean); }
package interfaceExample; public abstract class Animal extends Being { public abstract String communicate(); private Human pOwner; public Animal(int mspeed,String name, int i, int j, boolean b) { super(mspeed,name,i,j,b); } public Animal(int maxSeed, String name, int i, int j,Boolean b, Human pOwner2) { super(maxSeed,name,i,j,b); this.pOwner = getpOwner(); } public Human getpOwner() { return pOwner; } public void setpOwner(Human pOwner) { this.pOwner = pOwner; } }
package com.application.sqlite; import android.content.ContentResolver; import android.net.Uri; import android.provider.BaseColumns; /** * <b>Description:</b></br>DBConstants : Table Names, Column Names, Index Names & Content Provider URI</br> * @author Vikalp Patel(VikalpPatelCE) */ public class DBConstant { public static final String DB_NAME = "ApplicationDB"; public static final String TABLE_MOBCAST = "mobcast"; public static final String TABLE_CHAT = "chat"; public static final String TABLE_TRAINING = "training"; public static final String TABLE_EVENT = "event"; public static final String TABLE_AWARD = "award"; public static final String TABLE_BIRTHDAY = "birthday"; public static final String TABLE_MOBCAST_FILE = "mobcastFileInfo"; public static final String TABLE_TRAINING_FILE = "trainingFileInfo"; public static final String TABLE_MOBCAST_FEEDBACK = "mobcastFeedback"; public static final String TABLE_TRAINING_QUIZ = "trainingQuiz"; public static final String TABLE_PARICHAY_REFERRAL = "parichayReferral"; public static final String INDEX_MOBCAST_ID = "_id_unique_mobcast"; public static final String INDEX_CHAT_ID = "_id_unique_chat"; public static final String INDEX_TRAINING_ID = "_id_unique_training"; public static final String INDEX_EVENT_ID = "_id_unique_event"; public static final String INDEX_AWARD_ID = "_id_unique_award"; public static final String INDEX_BIRTHDAY_ID = "_id_unique_birthday"; public static final String INDEX_MOBCAST_FILE = "_id_unique_mobcast_file"; public static final String INDEX_TRAINING_FILE = "_id_unique_training_file"; public static final String INDEX_MOBCAST_FEEDBACK = "_id_unique_mobcast_feedback"; public static final String INDEX_TRAINING_QUIZ = "_id_unique_training_quiz"; public static final String INDEX_PARICHAY_REFERRAL = "_id_unique_parichay_referral"; public static final String INDEX_ID_ORDER = " ASC"; public static class Mobcast_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/mobcast"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/mobcast"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_MOBCAST_ID = "_mobcast_id"; public static final String COLUMN_MOBCAST_TITLE = "_mobcast_title"; public static final String COLUMN_MOBCAST_DESC = "_mobcast_desc"; public static final String COLUMN_MOBCAST_BY = "_mobcast_by"; public static final String COLUMN_MOBCAST_VIEWCOUNT = "_mobcast_view_count"; public static final String COLUMN_MOBCAST_DATE = "_mobcast_date"; public static final String COLUMN_MOBCAST_TIME = "_mobcast_time"; public static final String COLUMN_MOBCAST_TYPE = "_mobcast_type"; public static final String COLUMN_MOBCAST_DATE_FORMATTED = "_mobcast_date_formatted"; public static final String COLUMN_MOBCAST_TIME_FORMATTED = "_mobcast_time_formatted"; public static final String COLUMN_MOBCAST_IS_READ = "_mobcast_is_read"; public static final String COLUMN_MOBCAST_IS_SHARE = "_mobcast_is_share"; public static final String COLUMN_MOBCAST_IS_LIKE = "_mobcast_is_like"; public static final String COLUMN_MOBCAST_IS_SHARING = "_mobcast_is_sharing"; public static final String COLUMN_MOBCAST_IS_DOWNLOADABLE = "_mobcast_is_downloadable"; public static final String COLUMN_MOBCAST_LIKE_NO = "_mobcast_seen_no"; public static final String COLUMN_MOBCAST_READ_NO = "_mobcast_read_no"; public static final String COLUMN_MOBCAST_SHARE_NO = "_mobcast_share_no"; public static final String COLUMN_MOBCAST_LINK = "_mobcast_link"; public static final String COLUMN_MOBCAST_EXPIRY_DATE = "_mobcast_expiry_date"; public static final String COLUMN_MOBCAST_EXPIRY_TIME = "_mobcast_expiry_time"; public static final String COLUMN_MOBCAST_FILE_ID = "_mobcast_file_id"; } public static class Training_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/training"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/training"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TRAINING_ID = "_training_id"; public static final String COLUMN_TRAINING_TITLE = "_training_title"; public static final String COLUMN_TRAINING_DESC = "_training_desc"; public static final String COLUMN_TRAINING_BY = "_training_by"; public static final String COLUMN_TRAINING_VIEWCOUNT = "_training_view_count"; public static final String COLUMN_TRAINING_DATE = "_training_date"; public static final String COLUMN_TRAINING_TIME = "_training_time"; public static final String COLUMN_TRAINING_TYPE = "_training_type"; public static final String COLUMN_TRAINING_DATE_FORMATTED = "_training_date_formatted"; public static final String COLUMN_TRAINING_TIME_FORMATTED = "_training_time_formatted"; public static final String COLUMN_TRAINING_IS_READ = "_training_is_read"; public static final String COLUMN_TRAINING_IS_SHARE = "_training_is_share"; public static final String COLUMN_TRAINING_IS_LIKE = "_training_is_like"; public static final String COLUMN_TRAINING_IS_SHARING = "_training_is_sharing"; public static final String COLUMN_TRAINING_IS_DOWNLOADABLE = "_training_is_downloadable"; public static final String COLUMN_TRAINING_LIKE_NO = "_training_seen_no"; public static final String COLUMN_TRAINING_READ_NO = "_training_read_no"; public static final String COLUMN_TRAINING_SHARE_NO = "_training_share_no"; public static final String COLUMN_TRAINING_LINK = "_training_link"; public static final String COLUMN_TRAINING_EXPIRY_DATE = "_training_expiry_date"; public static final String COLUMN_TRAINING_EXPIRY_TIME = "_training_expiry_time"; public static final String COLUMN_TRAINING_FILE_ID = "_training_file_id"; } public static class Chat_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/chat"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/chat"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_USER_ID = "_user_id"; public static final String COLUMN_GROUP_ID = "_group_id"; public static final String COLUMN_GROUP_ID_MYSQL = "_group_id_mysql"; public static final String COLUMN_CITY_ID = "_city_id"; public static final String COLUMN_USER_JABBER_ID = "_user_jabber_id"; public static final String COLUMN_USER_ID_MYSQL = "_user_id_mysql"; public static final String COLUMN_USER_SENT_MESSAGE = "_is_user_sent"; public static final String COLUMN_MESSAGE = "_message"; public static final String COLUMN_MESSAGE_ID = "_message_id"; public static final String COLUMN_PATH = "_path"; public static final String COLUMN_FILE_LINK = "_file_link"; public static final String COLUMN_TYPE = "_type"; public static final String COLUMN_ISSENT = "_is_sent"; public static final String COLUMN_ISREAD = "_is_read"; public static final String COLUMN_ISDELIEVERED = "_is_delieverd"; public static final String COLUMN_ISNOTIFIED = "_is_notified"; public static final String COLUMN_TIMESTAMP = "_timestamp"; public static final String COLUMN_MESSAGE_TIME = "_message_time"; public static final String COLUMN_MESSAGE_DATE = "_message_date"; public static final String COLUMN_TAGGED = "_tagged"; public static final String COLUMN_ISLEFT = "_is_left"; } public static class Event_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/event"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/event"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_EVENT_ID = "_event_id"; public static final String COLUMN_EVENT_TITLE = "_event_title"; public static final String COLUMN_EVENT_BY = "_event_by"; public static final String COLUMN_EVENT_DESC = "_event_desc"; public static final String COLUMN_EVENT_VENUE = "_event_venue"; public static final String COLUMN_EVENT_START_TIME = "_event_start_time"; public static final String COLUMN_EVENT_END_TIME = "_event_end_time"; public static final String COLUMN_EVENT_START_DATE = "_event_start_date"; public static final String COLUMN_EVENT_END_DATE = "_event_end_date"; public static final String COLUMN_EVENT_DURATION = "_event_duration"; public static final String COLUMN_EVENT_LANDMARK = "_event_land_mark"; public static final String COLUMN_EVENT_FILE_LINK = "_event_file_link"; public static final String COLUMN_EVENT_FILE_PATH = "_event_file_path"; public static final String COLUMN_EVENT_FILE_APPEND = "_event_file_append"; public static final String COLUMN_EVENT_FILE_SIZE = "_event_file_size"; public static final String COLUMN_EVENT_IS_JOIN = "_event_is_join"; public static final String COLUMN_EVENT_IS_CALENDAR = "_event_is_calendar"; public static final String COLUMN_EVENT_IS_SHARING = "_event_sharing"; public static final String COLUMN_EVENT_IS_READ = "_event_is_read"; public static final String COLUMN_EVENT_IS_LIKE = "_event_is_like"; public static final String COLUMN_EVENT_MAP = "_event_map"; public static final String COLUMN_EVENT_INVITED_NO = "_event_invited_no"; public static final String COLUMN_EVENT_GOING_NO = "_event_going_no"; public static final String COLUMN_EVENT_DECLINE_NO = "_event_decline_no"; public static final String COLUMN_EVENT_MAYBE_NO = "_event_maybe_no"; public static final String COLUMN_EVENT_LIKE_NO = "_event_like_no"; public static final String COLUMN_EVENT_READ_NO = "_event_read_no"; public static final String COLUMN_EVENT_START_DATE_FORMATTED = "_event_start_date_formatted"; public static final String COLUMN_EVENT_END_DATE_FORMATTED = "_event_end_date_formatted"; public static final String COLUMN_EVENT_RECEIVED_DATE = "_event_received_date"; public static final String COLUMN_EVENT_RECEIVED_TIME = "_event_received_time"; public static final String COLUMN_EVENT_RECEIVED_DATE_FORMATTED = "_event_received_date_formatted"; public static final String COLUMN_EVENT_EXPIRY_DATE = "_event_expiry_date"; public static final String COLUMN_EVENT_EXPIRY_TIME = "_event_expiry_time"; public static final String COLUMN_EVENT_EXPIRY_DATE_FORMATTED = "_event_expiry_date_formatted"; } public static class Award_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/award"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/award"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_AWARD_ID = "_award_id"; public static final String COLUMN_AWARD_NAME = "_award_name"; public static final String COLUMN_AWARD_RECOGNITION = "_award_recognition"; public static final String COLUMN_AWARD_CONGRATULATE_NO = "_award_congratulate_no"; public static final String COLUMN_AWARD_CITY = "_award_city"; public static final String COLUMN_AWARD_DEPARTMENT = "_award_department"; public static final String COLUMN_AWARD_FILE_LINK = "_award_file_link"; public static final String COLUMN_AWARD_FILE_PATH = "_award_file_path"; public static final String COLUMN_AWARD_FILE_SIZE = "_award_file_size"; public static final String COLUMN_AWARD_THUMBNAIL_PATH = "_award_thumbnail_path"; public static final String COLUMN_AWARD_THUMBNAIL_LINK = "_award_thumbnail_link"; public static final String COLUMN_AWARD_DESCRIPTION = "_award_description"; public static final String COLUMN_AWARD_RECEIVER_EMAIL = "_award_receiver_email"; public static final String COLUMN_AWARD_READ_NO = "_award_read_no"; public static final String COLUMN_AWARD_LIKE_NO = "_award_like_no"; public static final String COLUMN_AWARD_RECEIVED_DATE = "_award_received_date"; public static final String COLUMN_AWARD_EXPIRY_DATE_FORMATTED = "_award_expiry_date_formatted"; public static final String COLUMN_AWARD_FILE_APPEND = "_award_file_append"; public static final String COLUMN_AWARD_IS_SHARE = "_award_is_share"; public static final String COLUMN_AWARD_IS_CONGRATULATE = "_award_is_congratulate"; public static final String COLUMN_AWARD_IS_READ = "_award_is_read"; public static final String COLUMN_AWARD_IS_SHARING = "_award_sharing"; public static final String COLUMN_AWARD_IS_LIKE = "_award_is_like"; public static final String COLUMN_AWARD_IS_MESSAGE = "_award_is_message"; public static final String COLUMN_AWARD_DATE = "_award_date"; public static final String COLUMN_AWARD_TIME = "_award_time"; public static final String COLUMN_AWARD_DATE_FORMATTED = "_award_date_formatted"; public static final String COLUMN_AWARD_RECEIVED_DATE_FORMATTED = "_award_received_date_formatted"; public static final String COLUMN_AWARD_RECEIVER_TIME_FORMATTED = "_award_receiver_time_formatted"; public static final String COLUMN_AWARD_RECEIVER_MOBILE = "_award_receiver_mobile"; public static final String COLUMN_AWARD_EXPIRY_DATE = "_award_expiry_date"; public static final String COLUMN_AWARD_EXPIRY_TIME = "_award_expiry_time"; } public static class Birthday_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/birthday"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/birthday"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_BIRTHDAY_ID = "_birthday_id"; public static final String COLUMN_BIRTHDAY_NAME = "_birthday_name"; public static final String COLUMN_BIRTHDAY_DEPARTMENT = "_birthday_department"; public static final String COLUMN_BIRTHDAY_IS_SHARE = "_birthday_is_share"; public static final String COLUMN_BIRTHDAY_IS_WISHED = "_birthday_is_congratulate"; public static final String COLUMN_BIRTHDAY_IS_READ = "_birthday_is_read"; public static final String COLUMN_BIRTHDAY_IS_SHARING = "_birthday_sharing"; public static final String COLUMN_BIRTHDAY_IS_LIKE = "_birthday_is_like"; public static final String COLUMN_BIRTHDAY_IS_MESSAGE = "_birthday_is_message"; public static final String COLUMN_BIRTHDAY_AGE = "_birthday_recognition"; public static final String COLUMN_BIRTHDAY_SUN_SIGN = "_birthday_congratulate_no"; public static final String COLUMN_BIRTHDAY_CITY = "_birthday_city"; public static final String COLUMN_BIRTHDAY_FILE_LINK = "_birthday_file_link"; public static final String COLUMN_BIRTHDAY_FILE_PATH = "_birthday_file_path"; public static final String COLUMN_BIRTHDAY_FILE_APPEND = "_birthday_file_append"; public static final String COLUMN_BIRTHDAY_DOB = "_birthday_dob"; public static final String COLUMN_BIRTHDAY_DATE = "_birthday_date"; public static final String COLUMN_BIRTHDAY_DAY = "_birthday_day"; public static final String COLUMN_BIRTHDAY_DATE_FORMATTED = "_birthday_date_formatted"; public static final String COLUMN_BIRTHDAY_RECEIVED_DATE_FORMATTED = "_birthday_received_date_formatted"; public static final String COLUMN_BIRTHDAY_RECEIVER_TIME_FORMATTED = "_birthday_receiver_time_formatted"; public static final String COLUMN_BIRTHDAY_IS_MALE = "_birthday_receiver_is_male"; public static final String COLUMN_BIRTHDAY_RECEIVER_MOBILE = "_birthday_receiver_mobile"; public static final String COLUMN_BIRTHDAY_RECEIVER_EMAIL = "_birthday_receiver_email"; public static final String COLUMN_BIRTHDAY_EXPIRY_DATE = "_birthday_expiry_date"; public static final String COLUMN_BIRTHDAY_EXPIRY_TIME = "_birthday_expiry_time"; } public static class Mobcast_File_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/mobcastFileInfo"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/mobcastFileInfo"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_MOBCAST_ID = "_mobcast_id"; public static final String COLUMN_MOBCAST_FILE_ID = "_mobcast_file_id"; public static final String COLUMN_MOBCAST_FILE_LINK = "_mobcast_file_link"; public static final String COLUMN_MOBCAST_FILE_LANG = "_mobcast_file_lang"; public static final String COLUMN_MOBCAST_FILE_SIZE = "_mobcast_file_size"; public static final String COLUMN_MOBCAST_FILE_PATH = "_mobcast_file_path"; public static final String COLUMN_MOBCAST_FILE_DURATION = "_mobcast_file_duration"; public static final String COLUMN_MOBCAST_FILE_PAGES = "_mobcast_file_pages"; public static final String COLUMN_MOBCAST_FILE_READ_DURATION = "_mobcast_file_read_duration"; public static final String COLUMN_MOBCAST_FILE_NAME = "_mobcast_file_name"; public static final String COLUMN_MOBCAST_FILE_THUMBNAIL_LINK = "_mobcast_file_thumbnail_link"; public static final String COLUMN_MOBCAST_FILE_THUMBNAIL_PATH = "_mobcast_file_thumbnail_path"; public static final String COLUMN_MOBCAST_FILE_IS_DEFAULT = "_mobcast_file_is_default"; public static final String COLUMN_MOBCAST_LIVE_STREAM = "_mobcast_live_stream"; public static final String COLUMN_MOBCAST_LIVE_STREAM_YOUTUBE = "_mobcast_live_stream_youtube"; public static final String COLUMN_MOBCAST_FILE_APPEND = "_mobcast_file_append"; } public static class Training_File_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/trainingFileInfo"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/trainingFileInfo"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TRAINING_ID = "_training_id"; public static final String COLUMN_TRAINING_FILE_ID = "_training_file_id"; public static final String COLUMN_TRAINING_FILE_LINK = "_training_file_link"; public static final String COLUMN_TRAINING_FILE_LANG = "_training_file_lang"; public static final String COLUMN_TRAINING_FILE_SIZE = "_training_file_size"; public static final String COLUMN_TRAINING_FILE_PATH = "_training_file_path"; public static final String COLUMN_TRAINING_FILE_DURATION = "_training_file_duration"; public static final String COLUMN_TRAINING_FILE_PAGES = "_training_file_pages"; public static final String COLUMN_TRAINING_FILE_NAME = "_training_file_name"; public static final String COLUMN_TRAINING_FILE_THUMBNAIL_LINK = "_training_file_thumbnail_link"; public static final String COLUMN_TRAINING_FILE_THUMBNAIL_PATH = "_training_file_thumbnail_path"; public static final String COLUMN_TRAINING_FILE_READ_DURATION = "_training_file_read_duration"; public static final String COLUMN_TRAINING_FILE_IS_DEFAULT = "_training_file_is_default"; public static final String COLUMN_TRAINING_LIVE_STREAM = "_training_live_stream"; public static final String COLUMN_TRAINING_LIVE_STREAM_YOUTUBE = "_training_live_stream_youtube"; public static final String COLUMN_TRAINING_FILE_APPEND = "_training_file_append"; } public static class Mobcast_Feedback_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/mobcastFeedback"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/mobcastFeedback"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_MOBCAST_FEEDBACK_ID = "_mobcast_feedback_id"; public static final String COLUMN_MOBCAST_FEEDBACK_QID = "_mobcast_feedback_queid"; public static final String COLUMN_MOBCAST_FEEDBACK_QUESTION = "_mobcast_feedback_question"; public static final String COLUMN_MOBCAST_FEEDBACK_TYPE = "_mobcast_feedback_type"; public static final String COLUMN_MOBCAST_FEEDBACK_ATTEMPT = "_mobcast_feedback_attempt"; public static final String COLUMN_MOBCAST_FEEDBACK_ATTEMPT_COUNT = "_mobcast_feedback_attempt_count"; public static final String COLUMN_MOBCAST_FEEDBACK_ANSWER = "_mobcast_feedback_answer"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_1 = "_mobcast_feedback_option_1"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_2 = "_mobcast_feedback_option_2"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_3 = "_mobcast_feedback_option_3"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_4 = "_mobcast_feedback_option_4"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_5 = "_mobcast_feedback_option_5"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_6 = "_mobcast_feedback_option_6"; public static final String COLUMN_MOBCAST_FEEDBACK_OPTION_7 = "_mobcast_feedback_option_7"; } public static class Training_Quiz_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/trainingQuiz"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/trainingQuiz"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TRAINING_QUIZ_ID = "_training_quiz_id"; public static final String COLUMN_TRAINING_QUIZ_QID = "_training_quiz_queid"; public static final String COLUMN_TRAINING_QUIZ_QUESTION = "_training_quiz_question"; public static final String COLUMN_TRAINING_QUIZ_TYPE = "_training_quiz_type"; public static final String COLUMN_TRAINING_QUIZ_ANSWER = "_training_quiz_answer"; public static final String COLUMN_TRAINING_QUIZ_ATTEMPT = "_training_quiz_attempt"; public static final String COLUMN_TRAINING_QUIZ_ATTEMPT_COUNT = "_training_quiz_attempt_count"; public static final String COLUMN_TRAINING_QUIZ_OPTION_1 = "_training_quiz_option_1"; public static final String COLUMN_TRAINING_QUIZ_OPTION_2 = "_training_quiz_option_2"; public static final String COLUMN_TRAINING_QUIZ_OPTION_3 = "_training_quiz_option_3"; public static final String COLUMN_TRAINING_QUIZ_OPTION_4 = "_training_quiz_option_4"; public static final String COLUMN_TRAINING_QUIZ_OPTION_5 = "_training_quiz_option_5"; public static final String COLUMN_TRAINING_QUIZ_OPTION_6 = "_training_quiz_option_6"; public static final String COLUMN_TRAINING_QUIZ_OPTION_7 = "_training_quiz_option_7"; public static final String COLUMN_TRAINING_QUIZ_CORRECT_OPTION = "_training_correct_option"; public static final String COLUMN_TRAINING_QUIZ_DURATION = "_training_quiz_duration"; public static final String COLUMN_TRAINING_QUIZ_QUESTION_POINTS = "_training_quiz_question_points"; } public static class Parichay_Referral_Columns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://"+ ApplicationDB.AUTHORITY + "/parichayReferral"); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/parichayReferral"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_PARICHAY_JOB_ID = "_parichay_job_id"; public static final String COLUMN_PARICHAY_REFERRED_ID = "_parichay_referred_id"; public static final String COLUMN_PARICHAY_REFERRED_NAME = "_parichay_referred_name"; public static final String COLUMN_PARICHAY_REFERRED_FOR = "_parichay_referred_for"; public static final String COLUMN_PARICHAY_REFERRED_DATE = "_parichay_referred_date"; public static final String COLUMN_PARICHAY_REFERRED_TYPE = "_parichay_referred_type"; public static final String COLUMN_PARICHAY_IS_IRF_MFCG = "_parichay_is_irf_mfcg"; public static final String COLUMN_PARICHAY_REASON = "_parichay_reason"; public static final String COLUMN_PARICHAY_IS_TELEPHONIC = "_parichay_is_telephonic"; public static final String COLUMN_PARICHAY_IS_ONLINE = "_parichay_is_online_written"; public static final String COLUMN_PARICHAY_IS_PR1 = "_parichay_is_pr1"; public static final String COLUMN_PARICHAY_IS_PR2 = "_parichay_is_pr2"; public static final String COLUMN_PARICHAY_IS_HR = "_parichay_is_hr"; public static final String COLUMN_PARICHAY_INSTALL = "_parichay_no_install"; public static final String COLUMN_PARICHAY_IS_DUPLICATE = "_parichay_is_duplicate"; public static final String COLUMN_PARICHAY_INSTALL1 = "_parichay_install1"; public static final String COLUMN_PARICHAY_INSTALL2 = "_parichay_install2"; public static final String COLUMN_PARICHAY_INSTALL3 = "_parichay_install3"; public static final String COLUMN_PARICHAY_INSTALL1_RS = "_parichay_install1_rs"; public static final String COLUMN_PARICHAY_INSTALL2_RS = "_parichay_install2_rs"; public static final String COLUMN_PARICHAY_INSTALL3_RS = "_parichay_install3_rs"; } }
/** * */ package eu.fbk.dycapo.factories.json; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import eu.fbk.dycapo.exceptions.DycapoException; import eu.fbk.dycapo.models.Location; import eu.fbk.dycapo.models.Trip; /** * @author riccardo * */ public abstract class TripFetcher { private static final String TAG = "TripFetcher"; public static final Trip fetchTrip(JSONObject responseValue) throws DycapoException { try { SimpleDateFormat parser = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss"); Trip result = new Trip(); String message = "error TripFetcher.fetchTrip : not enough parameters are given to define a Trip: missing "; if (responseValue.has(Trip.ID)) result.setId(responseValue.getInt(Trip.ID)); if (responseValue.has(DycapoObjectsFetcher.HREF)) result.setHref(responseValue .getString(DycapoObjectsFetcher.HREF)); if (responseValue.has(Trip.ACTIVE)) result.setActive(responseValue.getBoolean(Trip.ACTIVE)); if (responseValue.has(Trip.EXPIRES)) try { result.setExpires(parser.parse(responseValue .getString(Trip.EXPIRES))); } catch (ParseException e) { Log.e(TAG, e.getMessage()); throw new DycapoException(e.getMessage()); } else throw new DycapoException(message + Trip.EXPIRES); if (responseValue.has(Trip.PUBLISHED)) try { result.setPublished(parser.parse(responseValue .getString(Trip.PUBLISHED))); } catch (ParseException e) { Log.e(TAG, e.getMessage()); throw new DycapoException(e.getMessage()); } if (responseValue.has(Trip.UPDATED)) try { result.setUpdated(parser.parse(responseValue .getString(Trip.UPDATED))); } catch (ParseException e) { Log.e(TAG, e.getMessage()); throw new DycapoException(e.getMessage()); } if (responseValue.has(Trip.AUTHOR)) result.setAuthor(PersonFetcher.fetchPerson(responseValue .getJSONObject(Trip.AUTHOR))); else throw new DycapoException(message + Trip.AUTHOR); if (responseValue.has(Trip.MODE)) { Log.d(TAG + "." + Trip.MODE, Trip.MODE + " present"); result.setMode(ModeFetcher.fetchMode(responseValue .getJSONObject(Trip.MODE))); Log.d(TAG, Trip.MODE + " fetched"); } else throw new DycapoException(message + Trip.MODE); if (responseValue.has(Trip.PREFERENCES)) { Log.d(TAG + "." + Trip.PREFERENCES, Trip.PREFERENCES + " present"); result.setPreferences(PreferencesFetcher .fetchPreferences(responseValue .getJSONObject(Trip.PREFERENCES))); Log.d(TAG + "." + Trip.PREFERENCES, Trip.PREFERENCES + " fetched"); } else throw new DycapoException(message + Trip.PREFERENCES); if (responseValue.has(Trip.LOCATIONS)) { JSONArray rawlocs = responseValue.getJSONArray(Trip.LOCATIONS); int length = rawlocs.length(); ArrayList<Location> waypoints = new ArrayList<Location>(); for (int i = 0; i < length; i++) { Log.d(TAG, "starting fetching location " + String.valueOf(i) + " of " + String.valueOf(length) + " locations"); Location res = LocationFetcher.fetchLocation(rawlocs .getJSONObject(i)); Log.d(TAG, "ending fetching location " + String.valueOf(i) + " of " + String.valueOf(length) + " locations"); if (res.getPoint() == Location.ORIG) { result.setOrigin(res); Log.d(TAG, "Origin found"); } else if (res.getPoint() == Location.DEST) { result.setDestination(res); Log.d(TAG, "Destionation found"); } else waypoints.add(res); } if (!waypoints.isEmpty()) result.setWaypoints(waypoints); if (!(result.getOrigin() instanceof Location)) throw new DycapoException(message + Location.POINT_TYPE[0]); if (!(result.getDestination() instanceof Location)) throw new DycapoException(message + Location.POINT_TYPE[1]); } return result; } catch (JSONException e) { e.printStackTrace(); } return null; } public static final List<Trip> extractTrips(JSONArray value) throws DycapoException { List<Trip> trips = new ArrayList<Trip>(); try { for (int i = 0; i < value.length(); i++) { trips.add(fetchTrip(value.getJSONObject(i))); } return trips; } catch (JSONException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } return null; } }
package com.dabis.trimsalon; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dabis.trimsalon.ui.TrimsalonKlantFrame; public class DeTrimsalon { /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI(ApplicationContext context) { //Create and set up the window. TrimsalonKlantFrame lbw = new TrimsalonKlantFrame(context); lbw.setLocationRelativeTo(null); lbw.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml"); createAndShowGUI(factory); } }); } }
package Pattren; import java.util.Scanner; public class AlphaPatt { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); int k=1; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++,k++){ System.out.print((char)(k+64)+" "); } System.out.println(); } } }
package com.yoke.poseidon.web.itemShow.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yoke.poseidon.web.itemShow.cache.RedisCache; import com.yoke.poseidon.web.itemShow.entity.PanelContent; import org.apache.ibatis.annotations.CacheNamespace; import org.apache.ibatis.annotations.Param; import org.springframework.lang.NonNull; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author ehereal * @since 2018-09-20 */ //@CacheNamespace(implementation = RedisCache.class, eviction = RedisCache.class) public interface PanelContentMapper extends BaseMapper<PanelContent> { /** * 根据版块id查询版块的内容信息 * @param panelId 版块的id * @param sort 按照什么排序排序 * @param limit 限制查询的条数 * @return 查询得到的版块内容 */ List<PanelContent> selectByPanelId(@NonNull @Param("panelId") String panelId, @Param("sort") String sort, @Param("limit") Integer limit); /** * 根据版块id查询商品的id * @param panelId 版块的id * @param itemLimit 限制查询的条数 * @return 查询得到的商品ids */ List<String> selectItemIdsByPanelId(@Param("panelId") Integer panelId, @Param("limit") Integer itemLimit); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Threads; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author rm */ public class WaitAndModify { public static void main(String[] args) { final WaitAndModify obje = new WaitAndModify(); Thread player_1 = new Thread(new Runnable() { @Override public void run() { try { obje.player1(); } catch (InterruptedException ex) { } } }); Thread player_2 = new Thread(new Runnable() { @Override public void run() { try { obje.player2(); } catch (InterruptedException ex) { Logger.getLogger(WaitAndModify.class.getName()).log(Level.SEVERE, null, ex); } } }); player_1.start(); player_2.start(); } Object obj = new Object(); public void player1() throws InterruptedException { synchronized (obj/*this*/) { System.out.println("player1 shotting football now"); obj.wait(); //xxxxxxxxxxxx //go to synchronized(obj){ .............. System.out.println("than u for play back again "); } } public void player2() throws InterruptedException { synchronized (obj /*this*/) { Thread.sleep(1000); Scanner sc = new Scanner(System.in); System.out.println("press enter the shot "); sc.nextLine(); obj.notifyAll();//{تشغل كل الثريدات اللي بتريفرانس نفس الاوبجكت} // obj.notify(); {تشغل اخر واوبجكت نداها وهو اللي فيxxxxxxxxxxxxه } Thread.sleep(1000); } } }
package C9; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class E32 { public static HashMap<Edge, Boolean> visitedEdgeMap = new HashMap<>(); public static Graph initGraph() { String[] edges = { "1 3 1", "1 4 1", "2 3 1", "2 8 1", "3 4 1", "3 6 1", "3 7 1", "3 9 1", "4 5 1", "4 7 1", "4 10 1", "4 11 1", "5 10 1", "6 9 1", "7 9 1", "7 10 1", "8 9 1", "9 10 1", "9 12 1", "10 11 1", "10 12 1", }; // use ABC because of char for(int i = 0; i < edges.length; i++) { Scanner scan = new Scanner(edges[i]); int start = scan.nextInt(); int end = scan.nextInt(); int cost = scan.nextInt(); scan.close(); edges[i] = getABC(start) + " " + getABC(end) + " " + cost; } Graph g = new Graph(edges, false); return g; } public static char getABC(int num) { char tmp = 'A'; tmp += --num; return tmp; } public static int getNum(char abc) { char tmp = 'A'; int res = abc - tmp; return ++res; } public static void findEulerResult(Graph graph) { LinkedList<Node> oddNodes = new LinkedList<>(); for(Node node : graph.nodes) { boolean isOdd = node.edges.size()%2 != 0; if (isOdd) oddNodes.add(node); for(Edge edge : node.edges) { visitedEdgeMap.put(edge, false); } } if(oddNodes.size() == 0) { System.out.println("The graph has an Euler circuit"); findEulerPath(graph.nodes.getFirst(), null); } else if (oddNodes.size() == 2) { System.out.println("The graph has an Euler tour"); findEulerPath(oddNodes.remove(), oddNodes.remove()); } } public static void findEulerPath(Node start, Node end) { LinkedList<Node> res = new LinkedList<>(); LinkedList<Node> nodePath = new LinkedList<>(); // find initial path getDfsPath(start, end == null ? start : end, true, nodePath); res.addAll(0, nodePath); printPath(nodePath); while(true) { Node newStart = getUnvisitedEdge(res); if(newStart == null) break; nodePath.clear(); getDfsPath(newStart, newStart, true, nodePath); printPath(nodePath); int insertIdx = 0; for(Node tmp : res) { insertIdx++; if(tmp.name == newStart.name) { break; } } nodePath.removeFirst(); res.addAll(insertIdx, nodePath); } printPath(res); } public static void printPath(LinkedList<Node> path) { System.out.printf("Len %d: ", path.size() - 1); for(Node tmp : path) { System.out.printf("%s ", getNum(tmp.name)); } System.out.println(); } public static Node getUnvisitedEdge(LinkedList<Node> path) { for(Node node : path) { if (node.edgeCount != node.edges.size()) { return node; } } return null; } public static boolean getDfsPath(Node node, Node startNode, boolean isStart, LinkedList<Node> nodePath) { nodePath.add(node); if (!isStart && node.name == startNode.name) { return true; } for(Edge edge : node.edges) { if(!visitedEdgeMap.get(edge)) { visitedEdgeMap.put(edge, true); node.edgeCount++; visitedEdgeMap.put(edge.tailNode.edgeMap.get(node), true); edge.tailNode.edgeCount++; boolean finded = getDfsPath(edge.tailNode, startNode, false, nodePath); if (finded) { return true; } } } nodePath.removeLast(); return false; } public static void main(String[] args) throws Exception { findEulerResult(initGraph()); } }
package com.romens.yjkgrab.utils; import android.util.Log; import com.avos.avoscloud.AVObject; import com.romens.yjkgrab.model.Customer; import com.romens.yjkgrab.model.Order; import com.romens.yjkgrab.model.Product; import com.romens.yjkgrab.model.Shop; public class AnalysisHelper { public static class OrderHelper { public static Order analysis(AVObject avObject) { Order order = new Order(); order.setCreatedAt(avObject.getCreatedAt()); order.setCustomerId(avObject.getAVObject("customer").getObjectId()); order.setShopId(avObject.getAVObject("shop").getObjectId()); order.setProductId(avObject.getAVObject("product").getObjectId()); order.setObjectId(avObject.getObjectId()); order.setStatus(avObject.getString("status")); order.setProductNum(avObject.getString("productNum")); order.setRemarks(avObject.getString("remarks")); order.setPickupDate(avObject.getDate("pickupDate")); order.setServiceDate(avObject.getDate("serviceDate")); order.setGrabDate(avObject.getDate("grabDate")); order.setExpectDate(avObject.getDate("expectDate")); order.setDistance(Float.valueOf(avObject.getString("distance"))); order.setOrderId(avObject.getString("orderId")); order.setInstallationId(avObject.getString("installationId")); return order; } } public static class ShopHelper { public static Shop analysis(AVObject avObject) { Shop shop = new Shop(); shop.setAddress(avObject.getString("address")); shop.setName(avObject.getString("name")); shop.setObjectId(avObject.getObjectId()); shop.setPhone(avObject.getString("phone")); shop.setPicture(avObject.getString("picture")); shop.setAvGeoPoint(avObject.getAVGeoPoint("location")); return shop; } } public static class ProductHelper { public static Product analysis(AVObject avObject) { Product product = new Product(); product.setObjectId(avObject.getObjectId()); product.setName(avObject.getString("name")); product.setCompany(avObject.getString("company")); product.setPacking(avObject.getString("packing")); product.setSpecifications(avObject.getString("specifications")); return product; } } public static class CustomHelper { public static Customer analysis(AVObject avObject) { Customer customer = new Customer(); customer.setObjectId(avObject.getObjectId()); customer.setName(avObject.getString("name")); customer.setPhone(avObject.getString("phone")); customer.setAddress(avObject.getString("adress")); customer.setAvGeoPoint(avObject.getAVGeoPoint("location")); return customer; } } }
/* * Created on 20/08/2008 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.citibank.ods.modules.product.prodassettype.functionality.valueobject; import com.citibank.ods.entity.pl.TplProdAssetTypeEntity; /** * @author rcoelho * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class ProdAssetTypeDetailFncVO extends BaseProdAssetTypeDetailFncVO { public ProdAssetTypeDetailFncVO() { m_baseTplProdAssetTypeEntity = new TplProdAssetTypeEntity(); } }
package model; import contract.IDoor; import view.Lorann; /** * * @author Guillaume Woreth, Luca Borruto, Ahmed Ben Mbarek * */ public class Door implements IDoor { /** * Instanciate door to open and finish level */ private int _DoorY; private int _DoorX; public boolean KeyState = true; public Door(){ } public void verifDoor() { if(!KeyState) { System.out.println("WINNER WINNER CHICKEN DINNER"); } else if (KeyState) { System.out.println("NOOB EZ GAME"); } } public int get_DoorY() { return _DoorY; } public void set_DoorY(int _DoorY) { this._DoorY = _DoorY; } public int get_DoorX() { return _DoorX; } public void set_DoorX(int _DoorX) { this._DoorX = _DoorX; } public boolean isKeyState() { return KeyState; } public void setKeyState(boolean keyState) { KeyState = keyState; } }
package readwrite.read; import models.Performance; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PerformanceReader extends Reader<Performance> { private static List<Performance> performanceList = new ArrayList<>(); public static void readData() { PerformanceReader performanceReader = new PerformanceReader(); performanceList = performanceReader.readAndCreateObjects( "F:\\FMI\\Anul_II\\Sem_2\\PAO\\Proiect-PAO-master\\src\\readwrite\\resources\\Performances.csv"); for (Performance performance : performanceList) { System.out.println(performance); } } public static List<Performance> getPerformanceList() { return Collections.unmodifiableList(performanceList); } @Override Performance createObject(String[] objectDetails) { return new Performance(objectDetails[0], objectDetails[1], objectDetails[2], Integer.parseInt(objectDetails[3])); } }
package exception; import java.sql.SQLException; /** * 数据库操作异常类 * @author cdh 2017-08-01 * */ public class DataHandleException extends SQLException{ private static final long serialVersionUID = 1L; public DataHandleException(String e){ super(e); } }
/* * Created on 2005-8-22 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.aof.webapp.action.prm.report; import java.io.FileInputStream; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.hibernate.Query; import net.sf.hibernate.Transaction; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.Region; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.aof.component.domain.party.Party; import com.aof.component.domain.party.PartyHelper; import com.aof.component.domain.party.UserLogin; import com.aof.component.prm.TimeSheet.TimeSheetDetail; import com.aof.component.prm.TimeSheet.TimeSheetMaster; import com.aof.component.prm.project.ExpenseType; import com.aof.component.prm.project.ProjectEvent; import com.aof.component.prm.project.ProjectMaster; import com.aof.component.prm.project.ServiceType; import com.aof.core.persistence.Persistencer; import com.aof.core.persistence.hibernate.Hibernate2Session; import com.aof.core.persistence.jdbc.SQLExecutor; import com.aof.core.persistence.jdbc.SQLResults; import com.aof.core.persistence.util.EntityUtil; import com.aof.util.Constants; import com.aof.util.GeneralException; import com.aof.util.UtilDateTime; import com.aof.util.UtilFormat; import com.aof.webapp.action.ActionErrorLog; import com.lowagie.text.Cell; /** * @author CN01446 * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class CAFPrintExcelFormAction extends ReportBaseAction { protected ActionErrors errors = new ActionErrors(); protected ActionErrorLog actionDebug = new ActionErrorLog(); public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){ return ExportToExcel(mapping, form, request, response); } private ActionForward ExportToExcel (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ try { ActionErrors errors = this.getActionErrors(request.getSession()); //Fetch related Data net.sf.hibernate.Session hs = Hibernate2Session.currentSession(); PartyHelper ph = new PartyHelper(); UserLogin ul = (UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY); String UserId = request.getParameter("UserId"); String DataPeriod = request.getParameter("DataId"); if (UserId == null) UserId = ""; if (DataPeriod == null) DataPeriod = ""; List result = new ArrayList(); TimeSheetMaster tsm = null; Query q = hs.createQuery( "select tsm from TimeSheetMaster as tsm inner join tsm.TsmUser as tUser where tsm.Period = :DataPeriod and tUser.userLoginId = :DataUser"); q.setParameter("DataPeriod", DataPeriod); q.setParameter("DataUser", UserId); result = q.list(); List result2 = result; Iterator itMstr = result.iterator(); String projId[] = request.getParameterValues("projId"); String PSTId[] = request.getParameterValues("PSTId"); String chk[] = request.getParameterValues("chk"); String PEventId[] = request.getParameterValues("PEventId"); int ChkSize = 0; if (chk == null) { chk = new String[1]; chk[0] = "-1"; return null; } else { ChkSize = java.lang.reflect.Array.getLength(chk); } //Get Excel Template Path String TemplatePath = GetTemplateFolder(); if (TemplatePath == null) return null; //Start to output the excel file response.reset(); response.setHeader("Content-Disposition", "attachment;filename=\""+ SaveToFileName + "\""); response.setContentType("application/octet-stream"); //Use POI to read the selected Excel Spreadsheet HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(TemplatePath+"\\"+ExcelTemplate)); if (itMstr.hasNext()) { // set query result to request request.setAttribute("QryMaster", result); tsm = (TimeSheetMaster) itMstr.next(); }else tsm = new TimeSheetMaster(); if (!errors.empty()) { saveErrors(request, errors); return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); NumberFormat numFormater = NumberFormat.getInstance(); numFormater.setMaximumFractionDigits(2); numFormater.setMinimumFractionDigits(2); if (projId != null) { int RowSize = java.lang.reflect.Array.getLength(projId); try { TimeSheetDetail ts = null; ProjectMaster oldPM = null; ServiceType oldST = null; Object[] details = null; int ckrow = 1; int ci = 0; for (int i = 1; i <= RowSize; i++) { int ColSize = 0; if (ci < ChkSize && i == new Integer(chk[ci]).intValue()) { String tsId[] = request.getParameterValues("tsId" + i); String RecordVal[] =request.getParameterValues("RecordVal" + i); ProjectMaster projectMaster =(ProjectMaster) hs.load(ProjectMaster.class,projId[i - 1].toString()); ProjectEvent projectEvent =(ProjectEvent) hs.load(ProjectEvent.class,new Integer(PEventId[i - 1])); ServiceType st = (ServiceType) hs.load(ServiceType.class, new Long(PSTId[i - 1])); if(projectMaster.equals(oldPM) && st.equals(oldST)){ //update last record if (tsId != null) ColSize= java.lang.reflect.Array.getLength(tsId); for (int j = 0; j < ColSize; j++) { if (!tsId[j].trim().equals("")) { ts =(TimeSheetDetail) hs.load(TimeSheetDetail.class,new Integer(tsId[j])); int diff = new Long( UtilDateTime.getDayDistance( ts.getTsDate(),(UtilDateTime.toDate2(tsm.getPeriod() + " 00:00:00.000")))) .intValue(); if(details[diff] == null){ details[diff] = ts; } //If TimeSheetDetail in Monday & user hours equals zero, we don't add it. else if(diff != 0 || ts.getTsHoursUser().floatValue() != 0){ if(details[diff] instanceof TimeSheetDetail){ ArrayList al = new ArrayList(); al.add(details[diff]); al.add(ts); details[diff] = al; }else if(details[diff] instanceof ArrayList){ ((ArrayList)details[diff]).add(ts); } } } } }else{ //create new record details = new Object[7]; if (tsId != null) ColSize= java.lang.reflect.Array.getLength(tsId); for (int j = 0; j < ColSize; j++) { if (!tsId[j].trim().equals("")) { ts =(TimeSheetDetail) hs.load(TimeSheetDetail.class,new Integer(tsId[j])); int diff = new Long( UtilDateTime.getDayDistance( ts.getTsDate(),(UtilDateTime.toDate2(tsm.getPeriod() + " 00:00:00.000")))) .intValue(); details[diff] = ts; } } } if(ci == ChkSize-1){ String cafNo = this.generateCAFFormNumber(); setCAFNumber(details,cafNo); printCAF(wb, request, response, tsm,details, cafNo,true); }else if(ci < ChkSize-1){ //System.out.println(new Integer(chk[ci]).intValue()); ProjectMaster nextPM = (ProjectMaster) hs.load(ProjectMaster.class,projId[new Integer(chk[ci+1]).intValue()-1].toString()); ServiceType nextST = (ServiceType) hs.load(ServiceType.class, new Long(PSTId[new Integer(chk[ci+1]).intValue()-1])); //System.out.println(projectMaster.equals(nextPM)); //System.out.println(st.equals(nextST)); if(!projectMaster.equals(nextPM) || !st.equals(nextST)){ String cafNo = this.generateCAFFormNumber(); setCAFNumber(details,cafNo); printCAF(wb, request, response, tsm,details, cafNo,false); } } oldPM = projectMaster; oldST = st; ci++; } } }catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } return null; } private void setCAFNumber(Object[] details, String cafNo) { try { net.sf.hibernate.Session hs = Hibernate2Session.currentSession(); for(int i = 0; i < 7; i++){ if(details[i] instanceof TimeSheetDetail){ //TimeSheetDetail tsd = (TimeSheetDetail)hs.load(TimeSheetDetail.class, ((TimeSheetDetail)details[i]).getTsId()); TimeSheetDetail tsd = (TimeSheetDetail)details[i]; (tsd).setCAFPrintDate(cafNo); hs.update(tsd); }else if(details[i] instanceof ArrayList){ for(int j = 0; j < ((ArrayList)details[i]).size(); j++){ TimeSheetDetail tsd1 = (TimeSheetDetail)((ArrayList)details[i]).get(j); tsd1.setCAFPrintDate(cafNo); hs.update(tsd1); } } } hs.flush(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void printCAF(HSSFWorkbook wb, HttpServletRequest request, HttpServletResponse response, TimeSheetMaster tsm, Object[] details, String cafNo, boolean closed) { try{ TimeSheetDetail tsd = null; for(int i=0; i<7; i++){ if(details[i] != null){ if(details[0] instanceof ArrayList){ tsd = (TimeSheetDetail)((ArrayList)details[i]).get(0); }else tsd = (TimeSheetDetail)details[i]; break; } } //Select the first worksheet HSSFSheet sheet = null; sheet = wb.cloneSheet(0); // System.out.println(wb.getNumberOfSheets()-1); wb.setSheetName(wb.getNumberOfSheets()-1, "Sheet"+(sheetIndex)); sheetIndex+=1; if(sheet.getProtect()==true) sheet.setProtect(false); HSSFCellStyle boldTextStyle = sheet.getRow(ListStartRow).getCell((short)0).getCellStyle(); HSSFCellStyle normalStyle = sheet.getRow(ListStartRow).getCell((short)1).getCellStyle(); HSSFCellStyle dateStyle = sheet.getRow(ListStartRow).getCell((short)2).getCellStyle(); HSSFCell cell = null; cell = sheet.getRow(1).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(cafNo); cell = sheet.getRow(3).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getCustomer().getDescription()); cell = sheet.getRow(4).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getCustomer().getAddress()); cell = sheet.getRow(5).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getContact()); cell = sheet.getRow(3).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getTimeSheetMaster().getTsmUser().getName()); cell = sheet.getRow(4).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getProjectManager().getName()); cell = sheet.getRow(5).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 if(tsd.getProject().getProjAssistant()!=null) cell.setCellValue(tsd.getProject().getProjAssistant().getName()); cell = sheet.getRow(8).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getContractNo()); cell = sheet.getRow(9).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getContractType()); cell = sheet.getRow(10).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getProjName()); cell = sheet.getRow(11).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getTSServiceType().getDescription()); cell = sheet.getRow(12).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getCustPM()); java.util.Set expenseSet = tsd.getProject().getExpenseTypes(); Iterator itES = expenseSet.iterator(); ArrayList expenseList = new ArrayList(); while(itES.hasNext()){ expenseList.add(((ExpenseType)itES.next()).getExpDesc()); } cell = sheet.getRow(8).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(expenseList.contains("Hotel") ? "Y" : "N"); cell = sheet.getRow(9).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(expenseList.contains("Meal") ? "Y" : "N"); cell = sheet.getRow(10).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(expenseList.contains("Transport(Travel)") ? "Y" : "N"); cell = sheet.getRow(11).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(expenseList.contains("Telephones") ? "Y" : "N"); cell = sheet.getRow(12).getCell((short)8); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(expenseList.contains("Misc") ? "Y" : "N"); cell = sheet.getRow(13).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(tsd.getProject().getExpenseNote()); int dynRow = this.detailStartRow; float totalNormalHours = 0; float totalOneAndHalfHours = 0; float totalRateTwoHours = 0; for(int index = 0; index < 7; index++){ if(details[index] != null){ if(details[index] instanceof TimeSheetDetail){ String date = UtilFormat.format(((TimeSheetDetail)details[index]).getTsDate()); float hours = ((TimeSheetDetail)details[index]).getTsHoursUser().floatValue(); if(hours != 0){ cell = sheet.getRow(dynRow).getCell((short)1); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(date); if(index < 5){ /* Modification : hours are printed no matter <=8 or >8 , by Bill Yu if(hours <= 8){ cell = sheet.getRow(dynRow).getCell((short)2); cell.setCellValue(hours); totalNormalHours += hours; }else{ cell = sheet.getRow(dynRow).getCell((short)2); cell.setCellValue(8.0); cell = sheet.getRow(dynRow).getCell((short)3); cell.setCellValue(hours - 8); totalNormalHours += 8.0; totalOneAndHalfHours += (hours-8.0); } */ // following 3 rows replace the code above cell = sheet.getRow(dynRow).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalNormalHours += hours; }else if(index == 5){ //Modification : hours on Saturday placed at rate 1.5 column , by Bill Yu cell = sheet.getRow(dynRow).getCell((short)3); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalOneAndHalfHours += hours; }else if(index == 6){ //Modification : hours on Sunday placed at rate 2 column , by Bill Yu cell = sheet.getRow(dynRow).getCell((short)4); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalRateTwoHours += hours; } cell = sheet.getRow(dynRow).getCell((short)5); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(((TimeSheetDetail)details[index]).getProjectEvent().getPeventName()); } } else if(details[index] instanceof ArrayList){ for(int index1 = 0; index1 < ((ArrayList)details[index]).size(); index1++){ TimeSheetDetail ts = (TimeSheetDetail)((ArrayList)details[index]).get(index1); if(index1 > 0){ sheet.shiftRows(dynRow+1,sheet.getPhysicalNumberOfRows(), 1); dynRow++; sheet.createRow(dynRow); this.cloneRow(sheet, dynRow-1,dynRow); } String date = UtilFormat.format(ts.getTsDate()); float hours = ts.getTsHoursUser().floatValue(); if(hours != 0){ cell = sheet.getRow(dynRow).getCell((short)1); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(date); if(index < 5){ /* if(hours <= 8){ cell = sheet.getRow(dynRow).getCell((short)2); cell.setCellValue(hours); totalNormalHours += hours; }else{ cell = sheet.getRow(dynRow).getCell((short)2); cell.setCellValue(8.0); cell = sheet.getRow(dynRow).getCell((short)3); cell.setCellValue(hours - 8); totalNormalHours += 8.0; totalOneAndHalfHours += (hours-8.0); } }else{ cell = sheet.getRow(dynRow).getCell((short)4); cell.setCellValue(hours); totalRateTwoHours += hours; }*/ cell = sheet.getRow(dynRow).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalNormalHours += hours; }else if(index == 5){ //Modification : hours on Saturday placed at rate 1.5 column , by Bill Yu cell = sheet.getRow(dynRow).getCell((short)3); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalOneAndHalfHours += hours; }else if(index == 6){ //Modification : hours on Sunday placed at rate 2 column , by Bill Yu cell = sheet.getRow(dynRow).getCell((short)4); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(hours); totalRateTwoHours += hours; } cell= sheet.getRow(dynRow).getCell((short)5); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(ts.getProjectEvent().getPeventName()); } } } } dynRow++; } sheet.setProtect(true); /* cell = sheet.getRow(dynRow).getCell((short)2); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(totalNormalHours); cell = sheet.getRow(dynRow).getCell((short)3); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(totalOneAndHalfHours); cell = sheet.getRow(dynRow).getCell((shor)4); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellValue(totalRateTwoHours); */ if(closed){ sheetIndex = 1; wb.removeSheetAt(0); //写入Excel工作表 wb.write(response.getOutputStream()); //关闭Excel工作薄对象 response.getOutputStream().close(); response.setStatus( HttpServletResponse.SC_OK ); response.flushBuffer(); } }catch(Exception e){ e.printStackTrace(); } } private void cloneRow(HSSFSheet sheet, int prev, int cur) { // TODO Auto-generated method stub HSSFRow prevRow = sheet.getRow(prev); HSSFRow curRow = sheet.getRow(cur); if(prevRow != null && curRow != null){ int size = prevRow.getPhysicalNumberOfCells(); for(int i = 0; i < size; i++){ HSSFCell cell = curRow.createCell((short)i); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellStyle(prevRow.getCell((short)i).getCellStyle()); } sheet.addMergedRegion(new Region(cur, (short)5, cur, (short)8)); } } private HSSFCell getCell(HSSFSheet sheet, int dynRow, short s) { HSSFCell cell = sheet.getRow(dynRow).getCell(s); if(cell == null){ cell = sheet.getRow(dynRow).createCell(s); cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断 cell.setCellStyle(sheet.getRow(dynRow-1).getCell(s).getCellStyle()); } return cell; } public String generateCAFFormNumber() { Calendar calendar = Calendar.getInstance(); StringBuffer sb = new StringBuffer(); sb.append("CAF"); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1; int day = calendar.get(Calendar.DATE); sb.append(year); sb.append(this.fillPreZero(month,2)); sb.append(this.fillPreZero(day,2)); String codePrefix = sb.toString(); SQLExecutor sqlExec = new SQLExecutor( Persistencer.getSQLExecutorConnection(EntityUtil.getConnectionByName("jdbc/aofdb"))); try { String statement = "select max(t.caf_printdate) from proj_ts_det as t where t.caf_printdate like '"+codePrefix+"%'"; SQLResults result = sqlExec.runQueryCloseCon(statement); int count = 0; String GetResult = (String)result.getString(0,0); if (GetResult != null) count = (new Integer(GetResult.substring(codePrefix.length()))).intValue(); sb = new StringBuffer(); sb.append(codePrefix); sb.append(fillPreZero(count+1,3)); return sb.toString(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); if(sqlExec.getConnection() != null) sqlExec.closeConnection(); return null; } } private String fillPreZero(int no,int len) { String s=String.valueOf(no); StringBuffer sb=new StringBuffer(); for(int i=0;i<len-s.length();i++) { sb.append('0'); } sb.append(s); return sb.toString(); } private final static String ExcelTemplate="CAFPrintForm.xls"; private int sheetIndex = 1; private final static String SaveToFileName="CAF Excel Form.xls"; private static int ListStartRow = 5; private static int detailStartRow = 19; }
import java.util.Scanner; /** * Created by 17032361 on 2017/8/21. * 求考试成绩最高分 */ public class chapter5_7_1 { public static void main(String[] args){ Scanner in = new Scanner(System.in); int[] arr = new int[5]; for (int i=0;i<arr.length;i++){ System.out.println("请输入第"+(i+1)+"的学生的成绩"); arr[i] = in.nextInt(); } int max=arr[0]; for(int i=0;i<arr.length;i++){ if(max<arr[i]){ max = arr[i]; } } System.out.println("学生的的成绩最大是"+max); } }
package pojo.businessObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pojo.DAO.*; import pojo.valueObject.assist.MessageReceiverVO; import pojo.valueObject.domain.*; import tool.BeanFactory; import tool.Time; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by geyao on 2017/3/3. */ @Transactional @Service public class MessageBO { @Autowired private TeamDAO teamDAO; @Resource private ProjectDAO projectDAO; @Resource private TeacherDAO teacherDAO; @Resource private StudentVO studentVO; @Resource private MessageDAO messageDAO; @Autowired private UserDAO userDAO; /** * 读取信息,在DAO里同时处理了三种表的action * @param userVO * @return * @throws Exception */ public ArrayList<MessageVO> readMessage(UserVO userVO) throws Exception{ MessageDAO messageDAO = BeanFactory.getBean("messageDAO", MessageDAO.class); return messageDAO.getUnreadMessageVO(userVO); } /** * 修改项目,发送消息 * @param projectVO */ public void updateProjectVO(ProjectVO projectVO, UserVO sender) throws Exception{ if (projectVO == null){ return; } if (sender == null) return; List<TeamVO> teamVOList = teamDAO.getTeamVOByProjectVO(projectVO); List<UserVO> receiver = new ArrayList<>(); for (TeamVO teamVO : teamVOList){ receiver.addAll(teamDAO.getStudentVOSByTeamId(teamVO.getId())); } receiver.add(teacherDAO.getTeacherVOByProjectVO(projectVO)); MessageVO messageVO = BeanFactory.getBean("messageVO", MessageVO.class); messageVO.setTitle(projectVO.getName() + "项目信息改动"); messageVO.setContent(projectVO.getName() + "项目信息发生了变动,请及时查看"); messageVO.setContent(Time.getCurrentTime()); messageVO.setSenderUserVO(sender); sendMessage(messageVO, receiver); } /** * 发送消息 * 转成set,设置messageVO的readFlag,设置关系表 * @param messageVO * @param receiverVOList */ public void sendMessage(MessageVO messageVO, List<UserVO> receiverVOList) throws Exception{ if (messageVO == null || receiverVOList == null) return; HashSet<UserVO>receiverSet = new HashSet<>(); receiverSet.addAll(receiverVOList); messageVO.setReadFlag(receiverSet.size()); messageDAO.save(messageVO); for (UserVO userVO : receiverSet){ MessageReceiverVO messageReceiverVO = BeanFactory .getBean("messageReceiverVO", MessageReceiverVO.class); messageReceiverVO.setMessageVO(messageVO); messageReceiverVO.setReadFlag(false); messageReceiverVO.setReceiverUserVO(userVO); userVO.setNewsFlag( (userVO.getNewsFlag() + 1) ); //设置完了关系和修改UserVO的newsFlag userDAO.update(userVO); messageDAO.save(messageReceiverVO); } } /** * 辞退某个团队,给团队成员发送消息 * @param teamId * @param projectId * @param sender * @throws Exception */ public void fireTeam(Integer teamId, Integer projectId, UserVO sender) throws Exception{ TeamVO teamVO = teamDAO.getTeamVOByTeamId(teamId); ProjectVO projectVO = projectDAO.getProjectVO(projectId); MessageVO messageVO = BeanFactory.getBean("messageVO", MessageVO.class); messageVO.setSenderUserVO(sender); messageVO.setTitle(teamVO.getTeamName() + " 团队已退出 " + projectVO.getName()); messageVO.setContent(""); messageVO.setCreateTime(Time.getCurrentTime()); List<UserVO> receiver = new ArrayList<>(); receiver.addAll( teamDAO.getStudentVOSByTeamId(teamVO.getId()) ); receiver.add(sender); sendMessage(messageVO, receiver); } /** * 删除项目,复制了修改项目的代码 * @param projectId * @param sender * @throws Exception */ public void deleteProject(Integer projectId, UserVO sender) throws Exception{ ProjectVO projectVO = projectDAO.getProjectVO(projectId); if (projectVO == null){ return; } if (sender == null) return; List<TeamVO> teamVOList = teamDAO.getTeamVOByProjectVO(projectVO); List<UserVO> receiver = new ArrayList<>(); for (TeamVO teamVO : teamVOList){ receiver.addAll(teamDAO.getStudentVOSByTeamId(teamVO.getId())); } receiver.add(teacherDAO.getTeacherVOByProjectVO(projectVO)); MessageVO messageVO = BeanFactory.getBean("messageVO", MessageVO.class); messageVO.setTitle(projectVO.getName() + "项目已被删除"); messageVO.setContent(projectVO.getName() + "项目已被删除"); messageVO.setContent(Time.getCurrentTime()); messageVO.setSenderUserVO(sender); sendMessage(messageVO, receiver); } /** * 删除团队 * @param teamId * @param sender * @throws Exception */ public void deleteTeam(Integer teamId, UserVO sender) throws Exception{ TeamVO teamVO = teamDAO.getTeamVOByTeamId(teamId); if (teamVO == null) return; List<UserVO> receiver = new ArrayList<>(); receiver.addAll(teamDAO.getStudentVOSByTeamId(teamVO.getId())); receiver.add(sender); MessageVO messageVO = BeanFactory.getBean("messageVO", MessageVO.class); messageVO.setTitle(teamVO.getTeamName() + "团队已被删除"); messageVO.setContent(teamVO.getTeamName() + "团队已被删除"); messageVO.setContent(Time.getCurrentTime()); messageVO.setSenderUserVO(sender); sendMessage(messageVO, receiver); } }
/** * */ package com.fixit.core.data.sql; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * @author Kostyantin * @createdAt 2017/04/27 21:31:28 GMT+3 */ @Entity @Table(name = "ServerLog") public class ServerLog implements SqlModelObject<Long> { public static ServerLog createLog(String tag, String level, String message, String stackTrace) { return new ServerLog( tag, level, message, stackTrace, new Date() ); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String tag; private String level; private String message; private String stackTrace; @Temporal(TemporalType.TIMESTAMP) private Date createdAt; public ServerLog() { } private ServerLog(String tag, String level, String message, String stackTrace, Date createdAt) { this.tag = tag; this.level = level; this.message = message; this.stackTrace = stackTrace; this.createdAt = createdAt; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getStackTrace() { return stackTrace; } public void setStackTrace(String stackTrace) { this.stackTrace = stackTrace; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Override public String toString() { return "ServerLog [id=" + id + ", tag=" + tag + ", level=" + level + ", message=" + message + ", stackTrace=" + stackTrace + ", createdAt=" + createdAt + "]"; } }
package com.dian.diabetes.activity.user; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.dian.diabetes.R; import com.dian.diabetes.activity.BasicActivity; import com.dian.diabetes.activity.DialogLoading; import com.dian.diabetes.activity.indicator.IndicatorActivity; import com.dian.diabetes.db.AlarmBo; import com.dian.diabetes.db.UserBo; import com.dian.diabetes.db.UserInfoBo; import com.dian.diabetes.db.dao.User; import com.dian.diabetes.db.dao.UserInfo; import com.dian.diabetes.request.HttpContants; import com.dian.diabetes.request.LoginRegisterAPI; import com.dian.diabetes.service.IndicateService; import com.dian.diabetes.service.LoadingService; import com.dian.diabetes.service.UpdateService; import com.dian.diabetes.service.UserService; import com.dian.diabetes.tool.Config; import com.dian.diabetes.tool.Preference; import com.dian.diabetes.tool.ToastTool; import com.dian.diabetes.utils.CheckUtil; import com.dian.diabetes.utils.ContantsUtil; import com.dian.diabetes.utils.HttpServiceUtil; import com.dian.diabetes.utils.StringUtil; import com.dian.diabetes.utils.HttpServiceUtil.CallBack; import com.dian.diabetes.widget.anotation.ViewInject; /** * 类/接口注释 * * @author Chanjc@ifenguo.com * @createDate 2014年7月4日 * */ public class LoginActivity extends BasicActivity implements OnClickListener, OnFocusChangeListener { @ViewInject(id = R.id.forget_psw) private TextView forgetPswText; @ViewInject(id = R.id.login_uname) private EditText nameEditText; @ViewInject(id = R.id.login_psw) private EditText pswEditText; @ViewInject(id = R.id.login_btn) private Button loginBtn; @ViewInject(id = R.id.goregister_btn) private Button goregisterBtn; @ViewInject(id = R.id.back_btn) private Button backBtn; @ViewInject(id = R.id.name_right_img) private ImageView nameRightImg; @ViewInject(id = R.id.psw_right_img) private ImageView pswRightImg; private LoginActivity activity; private DialogLoading loading; // 存放获取输入的电话 private String num = ""; // 存放获取输入的密码 private String psw = ""; private Preference preference; private CallBack loginCallback; private UserBo userBo; private UserInfoBo userInfoBo; private String scanCode; private Bundle bundle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_login_layout); activity = (LoginActivity) context; loading = new DialogLoading(activity); userBo = new UserBo(activity); userInfoBo = new UserInfoBo(activity); preference = Preference.instance(activity); initCallBack(); init(); } private void init() { bundle = getIntent().getExtras(); if (bundle != null) { scanCode = bundle.getString("code"); } forgetPswText.setOnClickListener(this); loginBtn.setOnClickListener(this); goregisterBtn.setOnClickListener(this); backBtn.setOnClickListener(this); nameEditText.setOnFocusChangeListener(this); pswEditText.setOnFocusChangeListener(this); // 每次oncreateView的时候设置为空 nameEditText.setText(preference.getString(Preference.CACHE_USER)); nameEditText.requestFocus(); } /** * 检查用户输入的手机号 * * @return 是否通过检查 */ private boolean checkNum() { // 判断号码是否存在 num = nameEditText.getText().toString(); // 电话的长度为11,开头为1,layout里面已经设置只能输入数字 if (CheckUtil.checkLengthEq(num, 11) && num.charAt(0) == '1') { return true; } else { return false; } } /** * 检查用户输入的密码 * * @return 是否通过检查 */ private boolean checkPsw() { psw = pswEditText.getText().toString(); // 判断长度checkLength if (CheckUtil.checkLength(psw, 4)) { return true; } else { return false; } } @Override public void onStop() { nameEditText.setText(""); pswEditText.setText(""); super.onStop(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.back_btn: activity.onBackPressed(); break; case R.id.forget_psw: startActivity(null, ForgetPswActivity.class); break; case R.id.login_btn: if (checkNum() && checkPsw()) { // 提交到服务器 goLogin(); } else { ToastTool.showUserStatus(HttpContants.WRONG_FORMAT, activity); } break; case R.id.goregister_btn: startActivity(bundle, RegisterActivity.class); break; } } private void goLogin() { // 提交到服务器 String phone = nameEditText.getText().toString(); String password = pswEditText.getText().toString(); preference.putString(Preference.CACHE_USER, phone); Map<String, Object> map = new HashMap<String, Object>(); map.put("phone", phone); map.put("password", password); loading.show(); LoginRegisterAPI.login(map, loginCallback); } private void initCallBack() { loginCallback = new CallBack() { @Override public void callback(String json) { loading.hide(); // 解析json try { JSONObject jsonObject = new JSONObject(json); int jStatus = jsonObject.getInt("status"); switch (jStatus) { case HttpContants.REQUEST_SUCCESS: JSONObject data = jsonObject.getJSONObject("data"); String jSessionId = data.getString("sessionId"); JSONObject user = data.getJSONObject("user"); Long mid = user.getLong("mid"); // 更新到user表中,存在修改,不存在插入 UserService uService = new UserService(); User userModel = uService.convertJsonTo(user); ContantsUtil.curUser = userBo.saveUserServer(userModel); ContantsUtil.MAIN_UPDATE = false; // mid preference.putLong(Preference.USER_ID, mid); ContantsUtil.DEFAULT_TEMP_UID = mid + ""; // uid // activity.getPrefernce().putLong(ContantsUtil.USER_ID, // uid); // sessionId preference.putString(ContantsUtil.USER_SESSIONID, jSessionId); HttpServiceUtil.sessionId = jSessionId; Config.startUpdate(); // 显示登录状态 MyThread myThread = new MyThread(); new Thread(myThread).start(); loading.show(); break; default: ToastTool.showToast(jStatus, activity); break; } } catch (JSONException e) { e.printStackTrace(); } } }; } @Override public void onFocusChange(View v, boolean hasFocus) { switch (v.getId()) { case R.id.login_uname: nameEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { // check username if (checkNum()) { nameRightImg .setImageResource(R.drawable.input_correct); } else { nameRightImg .setImageResource(R.drawable.input_wrong); } } else { nameRightImg.setImageBitmap(null); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); break; case R.id.login_psw: pswEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { // check psw if (checkPsw()) { pswRightImg .setImageResource(R.drawable.input_correct); } else { pswRightImg .setImageResource(R.drawable.input_wrong); } } else { pswRightImg.setImageBitmap(null); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } } private void setDialogLabel(String label) { if (loading == null) { loading = new DialogLoading(context); } loading.setDialogLabel(label); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: setDialogLabel("正在合并用户设置数据"); break; case 2: setDialogLabel("正在合并血糖数据"); break; case 3: setDialogLabel("数据同步完成"); // 启动当前用户闹钟系统 new AlarmBo(activity).setNextAlarm( ContantsUtil.DEFAULT_TEMP_UID, ContantsUtil.curUser.getService_uid()); loading.dismiss(); if (CheckUtil.isNull(ContantsUtil.curInfo.getSex()) || ContantsUtil.curInfo.getSex() == -1) { Bundle bundle = new Bundle(); bundle.putLong("mid", StringUtil.toLong(ContantsUtil.DEFAULT_TEMP_UID)); bundle.putBoolean("isedit", true); startActivity(bundle, ManageUsersActivity.class); Toast.makeText(context, "请先完善您的个人信息,再进行下面的操作!", Toast.LENGTH_SHORT).show(); } else { ToastTool.showUserStatus(HttpContants.LONGIN_SUCCESS, activity); // activity.startActivity(null, MainActivity.class); if (scanCode != null) { startActivity(bundle, IndicatorActivity.class); } } finishSimple(); break; case 4: setDialogLabel("正在同步本地用户设置数据"); break; case 5: setDialogLabel("正在同步本地血糖数据"); break; case 6: setDialogLabel("正在同步本地监测计划数据"); break; case 7: setDialogLabel("正在上传系统数据"); break; case 8: setDialogLabel("正在上传饮食数据"); break; case 9: setDialogLabel("正在上传运动数据"); break; case 10: setDialogLabel("正在上传用药数据"); break; case 11: setDialogLabel("正在同步本地饮食数据"); break; case 12: setDialogLabel("正在同步本地运动数据"); break; case 13: setDialogLabel("正在同步本地用药数据"); break; case 14: setDialogLabel("正在同步自测指标数据"); break; case 15: setDialogLabel("正在上传自测指标数据"); break; case 16: setDialogLabel("同步用户信息成功"); break; case 17: loading.dismiss(); Toast.makeText(context, "同步用户信息失败,请稍后再试", Toast.LENGTH_SHORT) .show(); break; } } }; /** * 同步服务端数据 */ class MyThread implements Runnable { public void run() { IndicateService.initIndicate(getApplicationContext(), ContantsUtil.DEFAULT_TEMP_UID); // 同步用户个人信息 // 从服务器获取数据更新 Map<String, Object> map = new HashMap<String, Object>(); map.put("mid", ContantsUtil.DEFAULT_TEMP_UID); String result = HttpServiceUtil.post(ContantsUtil.HOST + HttpContants.URL_MEMBER_GETONE, map); if (!CheckUtil.isNull(result)) { boolean state = loadUserInfo(result); if (!state) { handler.sendEmptyMessage(17); return; } else { handler.sendEmptyMessage(16); } } // 如果登陆之前未联网先同步系统参数 if (!ContantsUtil.isSycnSystem) { handler.sendEmptyMessage(7); Map<String, Object> params = new HashMap<String, Object>(); params.put("timestamp", preference.getLong(Preference.SYS_UPDATE_TIME)); result = HttpServiceUtil.post(ContantsUtil.PRED_UPDATE, params); LoadingService.sycnData(preference, context, result); ContantsUtil.isSycnSystem = true; } // 判断是否有未同步数据 UpdateService uService = new UpdateService(context, userBo); if (preference.getBoolean(Preference.HAS_UPDATE)) { handler.sendEmptyMessage(4); uService.updateUserProperty(); handler.sendEmptyMessage(5); uService.updateDiabetes(); handler.sendEmptyMessage(6); uService.updateAlarm(); handler.sendEmptyMessage(11); uService.updateEat(); handler.sendEmptyMessage(12); uService.updateSport(); handler.sendEmptyMessage(13); uService.updateMedicine(); handler.sendEmptyMessage(15); uService.updateIndicates(); Config.stopUpdate(); preference.putBoolean(Preference.HAS_UPDATE, false); } LoadingService service = new LoadingService(context, userBo); // load用户自定义设置 handler.sendEmptyMessage(1); service.loadingUserSet(); handler.sendEmptyMessage(2); service.loadingDbtData(); handler.sendEmptyMessage(3); service.loadingEatData(); handler.sendEmptyMessage(8); service.loadingSportData(); handler.sendEmptyMessage(9); service.loadingMedicineData(); handler.sendEmptyMessage(10); service.loadingIndicateData(); handler.sendEmptyMessage(14); // 刷新配置 Config.loadUserSet(activity); } }; private boolean loadUserInfo(String json) { JSONObject data; try { data = new JSONObject(json); int status = data.getInt("status"); if (CheckUtil.checkStatusOk(status)) { UserInfo userInfo = new UserInfo(); UserInfo.transformToUserInfo(userInfo, data.getString("data")); // 数据库里面有没有当前用户,没有就保存在数据库,有就更新信息 UserInfo temp = userInfoBo.getUinfoByMid(userInfo.getMid()); if (temp == null) { userInfoBo.saveUserInfo(userInfo); } else { userInfo.setId(temp.getId()); userInfo.setUid(temp.getUid()); userInfoBo.updateUserInfo(userInfo); } ContantsUtil.curInfo = userInfo; return true; } else { return false; } } catch (JSONException e) { e.printStackTrace(); } return false; } }
package com.rndapp.t.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import com.rndapp.t.R; /** * Created by ell on 1/18/15. */ public class LineFragment extends Fragment { protected RecyclerView.Adapter adapter; public void setAdapter(RecyclerView.Adapter adapter) { this.adapter = adapter; } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_line, container, false); RecyclerView recyclerView = (RecyclerView)rootView.findViewById(R.id.line_list); recyclerView.setHasFixedSize(true); if (adapter != null) recyclerView.setAdapter(adapter); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); return rootView; } }
package com.ggwork.net.socket; import com.qfc.yft.CimConsts; import com.qfc.yft.utils.APIDesUtils; import com.qfc.yft.utils.JackUtils; import com.qfc.yft.vo.SystemParams; /** * socket消息协议 * * @author zw.bai * @date 2013-5-10下午3:40:15 */ public class SocketProtocol { public final String SOCKET_LOGIN = ""; public final String SOCKET_SATUATED = ""; public static String scoketLogInXML(String sessionId) { StringBuffer sb = new StringBuffer(); sb.append("<cim client='cs' type='login'><user sessionId='"); sb.append(sessionId); sb.append("' status='" + SystemParams.getInstance().getStatus() + "'/></cim>"); return sb.toString(); } public static String socketSaturatedXml(String sessionId) { StringBuffer sb = new StringBuffer(); sb.append("<cim client='cs' type='check' resp='1'><user sessionId='"); sb.append(sessionId); sb.append("' status='10'/></cim>"); return sb.toString(); } public static String socketSelfStatusXml() { StringBuffer sb = new StringBuffer(); sb.append("<cim client=\"cs\" type=\"setStatus\"><user status=\""); sb.append(SystemParams.getInstance().getStatus()); sb.append("\"/></cim>"); return sb.toString(); } public static void socketSendMessXml(long id, int type, String mess) { StringBuffer sb = new StringBuffer(); String remark = "<userInfo sendUserType=\"3\" userName=\"" + SystemParams.getInstance().getUserName() + "\"/>"; if (type == CimConsts.ConnectUserType.FRIEND) { sb.append("<cim client=\"cs\" type=\"sendMessage\"><userList><user id='"); sb.append(id) .append("'/></userList>") .append("<message type=\"" + CimConsts.MessageType.MT_CHAT + "\" groupId=\"0\" userStauts=\"10\" remark=\"" + APIDesUtils.base64Encode(remark.getBytes()) + "\">"); sb.append(APIDesUtils.base64Encode(mess.getBytes())); sb.append("</message></cim>"); } else if (type == CimConsts.ConnectUserType.GROUP) { sb.append("<cim client=\"cs\" type=\"sendMessage\"> "); sb.append("<message type=\"" + CimConsts.MessageType.MT_BIG_GROUP + "\" groupId=\"" + id + "\" userStauts=\"10\" remark=\"" + APIDesUtils.base64Encode(remark.getBytes()) + "\">"); sb.append(APIDesUtils.base64Encode(mess.getBytes())); sb.append("</message></cim>"); } else if (type == CimConsts.ConnectUserType.GUEST) { sb.append("<cim client=\"cs\" type=\"sendMessage\"><userList><user id='"); sb.append(id) .append("'/></userList>") .append("<message type=\"" + CimConsts.MessageType.MT_CHAT + "\" groupId=\"0\" userStauts=\"10\">") .append(APIDesUtils.base64Encode(mess.getBytes())) .append("</message></cim>"); } else if (type == CimConsts.MessageType.MT_WEB_CUSTOM_FACE_SENT) { sb.append("<cim client=\"cs\" type=\"sendMessage\"><userList><user id='"); sb.append(id) .append("'/></userList>") .append("<message type=\"" + type + "\" groupId=\"0\" userStauts=\"10\" remark=\"" + APIDesUtils.base64Encode(remark.getBytes()) + "\">"); sb.append(APIDesUtils.base64Encode(mess.getBytes())).append("</message></cim>"); } else if (type == CimConsts.MessageType.MT_WEB_CUSTOM_FACE_SENT) { } CimSocket.getInstance().sendMsg(sb.toString()); } public static void socketAddTempGroupXml(long id, int type, String mess) { StringBuffer sb = new StringBuffer(); sb.append("<cim client=\"cs\" type=\"sendMessage\">"); sb.append("<message type=\"" + CimConsts.MessageType.MI_TEMP_ADD_GROUP + "\" groupId=\"" + id + "\" userStauts=\"10\">"); sb.append(APIDesUtils.base64Encode(mess.getBytes())); sb.append("</message></cim>"); CimSocket.getInstance().sendMsg(sb.toString()); } public static void socketOutTempGroupXml(long id, int type, String mess) { StringBuffer sb = new StringBuffer(); sb.append("<cim client=\"cs\" type=\"sendMessage\">"); sb.append("<message type=\"" + CimConsts.MessageType.MI_TEMP_OUT_GROUP + "\" groupId=\"" + id + "\" userStauts=\"10\">"); sb.append(APIDesUtils.base64Encode(mess.getBytes())); sb.append("</message></cim>"); CimSocket.getInstance().sendMsg(sb.toString()); } public static void socketAddFriend() { StringBuffer sb = new StringBuffer(); sb.append("<cim client=\"cs\" type=\"recvMessage\">"); sb.append("<user id=\"1322657711058\" status=\"10\"/>"); sb.append("<message type=\"4\" groupId=\"0\" remark=\"\" time=\"20130614112220\">QA==</message></cim>"); } }
class Quadratic { public void quadraticRoots(int a,int b,int c) { double a1=a; double b1=b; double c1=c; double d=(b1*b1)-(4*a1*c1); if(d<0) { System.out.print("Imaginary"); } else { double r1=(-b1-Math.pow(d,0.5))/(2.0*a1); double r2=(-b1+Math.pow(d,0.5))/(2.0*a1); System.out.print((int)Math.floor(r2)+" "); System.out.print((int)Math.floor(r1)); //System.out.println(); } } }
package com.ilecreurer.drools.samples.sample2.conf; import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieContainer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest public class CollisionConfigurationTest { @Autowired private AreaProperties areaProperties; @Autowired private KieContainer kieContainer; @Test void checkKBase() { KieBase kieBase = kieContainer.getKieBase("kbaseceprules"); assertThat(kieBase).isNotNull(); } @Test void checkAreaProperties() { assertThat(areaProperties).isNotNull(); assertThat(areaProperties.getMaxLatitude()).isEqualTo(80.0d); } }
package ru.chertenok.weather.niceweather; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.TaskStackBuilder; import android.view.Gravity; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import ru.chertenok.weather.niceweather.model.Config; import ru.chertenok.weather.niceweather.model.OnLoad; import ru.chertenok.weather.niceweather.model.OpenWeatherMapDataLoader; import ru.chertenok.weather.niceweather.model.TodayWeather; import ru.chertenok.weather.niceweather.model.WeatherUndergroundDataLoader; public class MainActivity extends AppCompatActivity implements OnLoad,NavigationView.OnNavigationItemSelectedListener { private TextView tv_temp; private TextView tv_desc; private TextView tv_city; private TextView tv_date; private ImageView iv_icon; private MenuItem mi_wopenmap; private MenuItem mi_wundegraund; private NavigationView navigationView; private ImageButton ib_menu; private DrawerLayout drawer; private Handler handler = new Handler(); private TodayWeather todayWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Wheather updating....", Snackbar.LENGTH_SHORT) .setAction("Action", null).show(); updateData(); } }); ib_menu = findViewById(R.id.ib_menu); ib_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawer.openDrawer(Gravity.LEFT); } }); drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, null, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); tv_temp = findViewById(R.id.tv_temp); tv_desc = findViewById(R.id.tv_WeatherDescription); tv_city = findViewById(R.id.tv_city); tv_date = findViewById(R.id.tv_date); iv_icon = findViewById(R.id.iv_Weather); mi_wopenmap = findViewById(R.id.nav_openMap); mi_wundegraund = findViewById(R.id.nav_underground); todayWeather = new TodayWeather("Moscow","ru"); Config.load(getApplicationContext()); updateData(); } private void updateData(){ if (Config.getWeatherSource() == Config.WeatherSource.openMap) OpenWeatherMapDataLoader.loadDate(getApplicationContext(),todayWeather, this); else WeatherUndergroundDataLoader.loadDate(getApplicationContext(),todayWeather,this); } private void updateUI(TodayWeather todayWeather) { tv_temp.setText(todayWeather.getValueByName("temp")); tv_desc.setText(todayWeather.getValueByName("description")); tv_city.setText(todayWeather.getCity()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Config.getTimeFormat()); tv_date.setText("last update - "+simpleDateFormat.format(todayWeather.getLastDateUpdate())); iv_icon.setImageBitmap(todayWeather.getIcon()); if (Config.getWeatherSource() == Config.WeatherSource.openMap) navigationView.setCheckedItem(R.id.nav_openMap); if (Config.getWeatherSource() == Config.WeatherSource.Underground) navigationView.setCheckedItem(R.id.nav_underground); } @Override public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { super.onPrepareSupportNavigateUpTaskStack(builder); mi_wundegraund.setChecked(Config.getWeatherSource() == Config.WeatherSource.Underground); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_openMap) { Config.setWeatherSource(Config.WeatherSource.openMap); updateData(); } else if (id == R.id.nav_underground) { Config.setWeatherSource(Config.WeatherSource.Underground); updateData(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override protected void onPause() { super.onPause(); Config.save(getApplicationContext()); } @Override public void onLoad(boolean isOk, final TodayWeather todayWeather) { handler.post(new Runnable() { @Override public void run() { updateUI(todayWeather); } }); } }
// Fig. 5.11: PruebaBreak.java // Terminación de un ciclo con break. import javax.swing.JOptionPane; public class PruebaBreak { public static void main( String args[] ) { String salida = ""; int cuenta; for ( cuenta = 1; cuenta <= 10; cuenta++ ) { // iterar 10 veces if ( cuenta == 5 ) { // si cuenta vale 5 break; // terminar el ciclo } salida += cuenta + " "; } // fin de instrucción for salida += "\nSe salió del ciclo en cuenta = " + cuenta; JOptionPane.showMessageDialog( null, salida ); System.exit( 0 ); // terminar la aplicación } // fin del método main } // fin de la clase PruebaBreak
package net.minecraft.world.level.chunk; public class DataLayer { public final byte[] data; private final int depthBits; private final int depthBitsPlusFour; public DataLayer(final int length, final int depthBits) { data = new byte[length >> 1]; this.depthBits = depthBits; depthBitsPlusFour = depthBits + 4; } public DataLayer(final byte[] data, final int depthBits) { this.data = data; this.depthBits = depthBits; depthBitsPlusFour = depthBits + 4; } public int get(final int x, final int y, final int z) { final int pos = y << depthBitsPlusFour | z << depthBits | x; final int slot = pos >> 1; final int part = pos & 1; if (part == 0) { return data[slot] & 0xf; } else { return data[slot] >> 4 & 0xf; } } public void set(final int x, final int y, final int z, final int val) { final int pos = y << depthBitsPlusFour | z << depthBits | x; final int slot = pos >> 1; final int part = pos & 1; if (part == 0) { data[slot] = (byte) (data[slot] & 0xf0 | val & 0xf); } else { data[slot] = (byte) (data[slot] & 0x0f | (val & 0xf) << 4); } } public boolean isValid() { return data != null; } public void setAll(final int br) { final byte val = (byte) ((br | br << 4) & 0xff); for (int i = 0; i < data.length; i++) { data[i] = val; } } }
package dk.jrpe.monitor.source.httpaccess.simulate; import java.util.ArrayList; public class SimulationConstants { public static final ArrayList<String> HTTP_STATUS_LIST; static { HTTP_STATUS_LIST = new ArrayList<>(); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("200"); HTTP_STATUS_LIST.add("404"); HTTP_STATUS_LIST.add("404"); HTTP_STATUS_LIST.add("403"); HTTP_STATUS_LIST.add("403"); HTTP_STATUS_LIST.add("302"); } public static final ArrayList<String> IP_ADDRESS_LIST; static { IP_ADDRESS_LIST = new ArrayList<>(); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("10.45.234.56"); IP_ADDRESS_LIST.add("120.45.24.5"); IP_ADDRESS_LIST.add("120.45.24.5"); IP_ADDRESS_LIST.add("120.45.24.5"); IP_ADDRESS_LIST.add("120.45.24.5"); IP_ADDRESS_LIST.add("142.65.234.56"); IP_ADDRESS_LIST.add("142.65.234.56"); IP_ADDRESS_LIST.add("142.65.234.56"); IP_ADDRESS_LIST.add("142.65.234.56"); IP_ADDRESS_LIST.add("140.65.234.56"); IP_ADDRESS_LIST.add("140.65.234.56"); IP_ADDRESS_LIST.add("106.45.23.5"); IP_ADDRESS_LIST.add("106.45.23.5"); IP_ADDRESS_LIST.add("106.45.23.5"); IP_ADDRESS_LIST.add("106.45.23.5"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("223.45.21.56"); IP_ADDRESS_LIST.add("220.45.21.56"); IP_ADDRESS_LIST.add("220.45.21.56"); IP_ADDRESS_LIST.add("220.45.21.56"); IP_ADDRESS_LIST.add("220.45.21.56"); IP_ADDRESS_LIST.add("123.43.234.56"); IP_ADDRESS_LIST.add("123.43.234.56"); IP_ADDRESS_LIST.add("123.43.234.56"); IP_ADDRESS_LIST.add("123.43.234.56"); IP_ADDRESS_LIST.add("123.43.234.56"); IP_ADDRESS_LIST.add("90.15.14.12"); IP_ADDRESS_LIST.add("90.15.14.12"); IP_ADDRESS_LIST.add("90.15.14.12"); IP_ADDRESS_LIST.add("111.75.24.22"); IP_ADDRESS_LIST.add("111.75.24.22"); IP_ADDRESS_LIST.add("111.75.24.22"); IP_ADDRESS_LIST.add("111.75.24.22"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); IP_ADDRESS_LIST.add("211.45.234.156"); } public static final ArrayList<String> ACTION_LIST; static { ACTION_LIST = new ArrayList<>(); ACTION_LIST.add("POST"); ACTION_LIST.add("GET"); } public static final ArrayList<String> URL_LIST; static { URL_LIST = new ArrayList<>(); URL_LIST.add("/test"); URL_LIST.add("/test?p=34"); URL_LIST.add("/test/all?f=456"); URL_LIST.add("/test/cart?id=4234"); URL_LIST.add("/test/cart?id=122"); URL_LIST.add("/test/cart?id=122"); URL_LIST.add("/test/cart?id=22"); URL_LIST.add("/test/cart?id=13"); URL_LIST.add("/test/cart?id=23"); URL_LIST.add("/test/cart?id=56"); URL_LIST.add("/test/cart?id=123"); } }
package br.edu.ufcspa.isolationapp.control; import android.app.Fragment; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import br.edu.ufcspa.isolationapp.Model.Links; import br.edu.ufcspa.isolationapp.R; import br.edu.ufcspa.isolationapp.adapter.EpiAdapter; import br.edu.ufcspa.isolationapp.database.DataBaseAdapter; import static android.R.id.message; /** * Created by icaromsc on 14/06/2017. */ public class LinksFragment extends Fragment { View myView; LinearLayout layout; TextView tx1; TextView tx2; TextView tx3; TextView tx4; public LinksFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_links, container, false); return myView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); /* tx1=(TextView) myView.findViewById(R.id.txtLink1); tx2=(TextView) myView.findViewById(R.id.txtLink2); tx3=(TextView) myView.findViewById(R.id.txtLink3); tx4=(TextView) myView.findViewById(R.id.txtLink4); TextView[] textViews = {tx1,tx2,tx3,tx4};*/ layout = (LinearLayout) myView.findViewById(R.id.layoutLinks); String[] links = Links.links; for (String link: links ) { TextView msg = new TextView(getActivity().getApplicationContext()); msg.setText(Html.fromHtml(link)); msg.setMovementMethod(LinkMovementMethod.getInstance()); msg.setTextSize(20); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { msg.setHighlightColor(getResources().getColor(R.color.colorAccent, null)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { msg.setLayoutParams(new LinearLayout.LayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))); } msg.setGravity(Gravity.CENTER); setMargins(msg, 15, 15, 15, 15); layout.addView(msg); } } private void setMargins (View view, int left, int top, int right, int bottom) { if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); p.setMargins(left, top, right, bottom); view.requestLayout(); } } }
package edu.uag.iidis.scec.vista; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.ValidatorForm; /** * Form bean para el registro de una nueva persona. * * @author Victor Ramos */ public final class FormaCrearTest extends ValidatorForm { private Collection test; private int contador; private Long valor; private Long[] preguntas=new Long[9]; private Long[] respuestas=new Long[9]; private String name; private Long idTest; public void setTest(Collection test) { this.test = test; if (test != null) { this.contador = test.size(); } else this.contador = -1; } public Collection getTest() { return (this.test); } public int getContador() { return (this.contador); } public Long getValor() { return (this.valor); } public void setValor(Long valor) { this.valor = valor; } public Long[] getRespuestas(){ return this.respuestas; } public void setRespuestas(Long[] respuestas){ this.respuestas=respuestas; } public Long[] getPreguntas(){ return this.preguntas; } public void setPreguntas(Long[] preguntas){ this.preguntas=preguntas; } public String getName(){ return this.name; } public void setName(String name){ this.name=name; } public Long getidTest(){ return this.idTest; } public void setidTest(Long idTest){ this.idTest=idTest; } public void reset(ActionMapping mapping, HttpServletRequest request) { contador=0; test=null; valor=null; respuestas=new Long[9]; preguntas=new Long[9]; } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // Ejecuta las validaciones proporcionadas por Struts-Validator ActionErrors errores = super.validate(mapping, request); // Validaciones no cubiertas por Struts-Validator return errores; } }
package com.alibaba.druid.bvt.filter.wall; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallContext; import com.alibaba.druid.wall.WallFunctionStat; import com.alibaba.druid.wall.WallProvider; import com.alibaba.druid.wall.WallTableStat; import com.alibaba.druid.wall.spi.MySqlWallProvider; public class WallStatTest_function_stats extends TestCase { private String sql = "select len(fname), len(fdesc) from t"; protected void setUp() throws Exception { WallContext.clearContext(); } protected void tearDown() throws Exception { WallContext.clearContext(); } public void testMySql() throws Exception { WallProvider provider = new MySqlWallProvider(); Assert.assertTrue(provider.checkValid(sql)); { WallTableStat tableStat = provider.getTableStat("t"); Assert.assertEquals(1, tableStat.getSelectCount()); } { WallFunctionStat functionStat = provider.getFunctionStat("len"); Assert.assertEquals(2, functionStat.getInvokeCount()); } Assert.assertTrue(provider.checkValid(sql)); { WallTableStat tableStat = provider.getTableStat("t"); Assert.assertEquals(2, tableStat.getSelectCount()); } { WallFunctionStat functionStat = provider.getFunctionStat("len"); Assert.assertEquals(4, functionStat.getInvokeCount()); } } }
package jthrift; public class TConst extends TDoc { private TType type; private Id name; private TConstValue value; public TConst(TType type, Id name, TConstValue value) { this.type = type; this.name = name; this.value = value; } public Id getName() { return name; } }
package com.masuikvova.wallet.Screens.Add; public interface AddView { void showError(); void showConfirm(); }
/** * */ package org.artifact.security.service; import java.util.List; import org.artifact.security.dao.RoleDao; import org.artifact.security.domain.Role; import org.artifact.security.domain.RolePermission; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 角色业务逻辑类 * <p> * 日期:2015年8月26日 * * @version 0.1 * @author Netbug */ @Service public class RoleService { @Autowired private RoleDao roleDao; public List<Role> find() { return roleDao.find(); } public void saveOrUpdate(Role role) { this.saveOrUpdate(role, false); } /** * 新增或修改角色 * <p> * 日期:2015年8月28日 * * @param role * @param relatePermissionFlag * 是否关联资源 * @author Netbug */ public void saveOrUpdate(Role role, boolean relatePermissionFlag) { roleDao.saveOrUpdate(role); if (relatePermissionFlag) { /** * 移除旧的关联资源 */ Role oldRole = this.getRoleById(role.getId()); for (RolePermission rolePermission : oldRole .getRolePermissionList()) { this.roleDao.delete(rolePermission.getId(), RolePermission.class); } /** * 添加新的关联资源 */ for (RolePermission rolePermission : role.getRolePermissionList()) { rolePermission.setId(null); rolePermission.setRole(role); this.roleDao.saveOrUpdate(rolePermission); } } } public Role getRoleById(Integer id) { return roleDao.getEntity(id, Role.class); } public void deleteRoleById(Integer id) { roleDao.delete(id, Role.class); } }
package de.kfs.db.structure; public class InformationWrapper { /** * This class wraps specific information about a Bike such as * frame height, tire diameter, manufacturer * and has utility to return these values into different types * of Tables */ private String manufacturer; private String color; private int frameHeigth; private int tireDiameter; public InformationWrapper(String manufacturer, String color, int frameHeigth, int tireDiameter) { if(manufacturer.trim().isEmpty()) { this.manufacturer = "DEFAULT"; } else { this.manufacturer = manufacturer; } if(manufacturer.trim().isEmpty()) { this.color = "egal"; } else { this.color = color; } this.frameHeigth = frameHeigth; this.tireDiameter = tireDiameter; } public String getManufacturer() { return manufacturer; } public String getColor() { return color; } public int getFrameHeigth() { return frameHeigth; } public int getTireDiameter() { return tireDiameter; } /** * merge the param into the calling wrapper. Only non-default, not empty * values of param will be used to override callings wrapper's attributes * defaults: manufacturer "DEFAULT", color "egal", tireDiameter & frameHeight -1 * @param other Wrapper that has the information to merge into calling wrapper */ public void merge(InformationWrapper other) { if(!(other.manufacturer.isEmpty() || other.manufacturer.equals("DEFAULT"))) { this.manufacturer = other.manufacturer; } if (!(other.color.isEmpty() || other.color.equals("egal"))) { this.color = other.color; } if (other.tireDiameter != -1) { this.tireDiameter = other.tireDiameter; } if (other.frameHeigth != -1) { this.frameHeigth = other.frameHeigth; } } /** * * Usage: if needed to display information within a single String * @return a nicely formatted String to display Information */ @Override public String toString() { String res = manufacturer + "; " + color + "; " + tireDiameter + "; " + frameHeigth; return res; } }
package ua.com.rd.pizzaservice.service.customer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ua.com.rd.pizzaservice.domain.address.Address; import ua.com.rd.pizzaservice.domain.customer.Customer; import ua.com.rd.pizzaservice.service.ServiceTestUtils; import java.util.HashSet; import java.util.Set; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/inMemDbRepositoryContext.xml", "classpath:/appContext.xml", }) public class CustomerServiceImplInMemDbTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private CustomerService customerService; private ServiceTestUtils serviceTestUtils; @Before public void setUp() { serviceTestUtils = new ServiceTestUtils(jdbcTemplate); } @Test public void getCustomerByIdTest() { Address address = serviceTestUtils.createAddress(1L, "Country", "City", "Street", "Building"); Customer customer = serviceTestUtils.createCustomer(1L, "Petya", address); Customer newCustomer = customerService.getCustomerById(customer.getId()); Assert.assertEquals(customer, newCustomer); } @Test public void saveCustomerTest() { Address address = serviceTestUtils.createAddress(1L, "Country", "City", "Street", "Building"); Customer customer = new Customer(); customer.setName("Petr"); customer.setAddresses(new HashSet<Address>() {{ add(address); }}); customerService.saveCustomer(customer); Assert.assertNotNull(customer.getId()); } @Test public void updateCustomerTest() { Address address = serviceTestUtils.createAddress(1L, "Country", "City", "Street", "Building"); Customer customer = serviceTestUtils.createCustomer(1L, "Petya", address); Address newAddress = serviceTestUtils.createAddress(2L, "newCountry", "newCity", "newStreet", "newBuilding"); customer.setName("Ivan"); customer.addAddress(newAddress); customerService.updateCustomer(customer); Customer updatedCustomer = getById(customer.getId()); Assert.assertEquals(customer, updatedCustomer); } private Customer getById(Long id) { return jdbcTemplate.query("SELECT c.customer_name, a.address_id, a.country, a.city, a.street, a.building " + "FROM customers c, addresses a, customers_addresses ca " + "WHERE ca.customer_customer_id = c.customer_id AND ca.addresses_address_id = a.address_id AND " + "c.customer_id = ?;", new Object[]{id}, resultSet -> { Customer customer = new Customer(); customer.setId(id); Set<Address> addresses = new HashSet<>(); while (resultSet.next()) { customer.setName(resultSet.getString("customer_name")); Address address = new Address(); address.setId(resultSet.getLong("address_id")); address.setCountry(resultSet.getString("country")); address.setCity(resultSet.getString("city")); address.setStreet(resultSet.getString("street")); address.setBuilding(resultSet.getString("building")); addresses.add(address); } customer.setAddresses(addresses); return customer; }); } @Test public void deleteCustomerTest() { Address address = serviceTestUtils.createAddress(1L, "Country", "City", "Street", "Building"); Customer customer = serviceTestUtils.createCustomer(1L, "Petya", address); customerService.deleteCustomer(customer); int countOfRecords = getCountOfCustomersById(customer.getId()); Assert.assertEquals(0, countOfRecords); } private int getCountOfCustomersById(Long id) { final String sql = "SELECT COUNT(*) FROM customers WHERE customer_id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, Integer.class); } @Test public void findAllTest() { Address address1 = serviceTestUtils.createAddress(1L, "Country", "City", "Street", "Building"); Address address2 = serviceTestUtils.createAddress(2L, "newCountry", "newCity", "newStreet", "newBuilding"); Customer customer1 = serviceTestUtils.createCustomer(1L, "Petya", address1); Customer customer2 = serviceTestUtils.createCustomer(2L, "Ivan", address1); Customer customer3 = serviceTestUtils.createCustomer(3L, "Kolya", address2); Set<Customer> customers = customerService.findAll(); Assert.assertEquals(3, customers.size()); Set<Customer> expected = new HashSet<>(); expected.add(customer1); expected.add(customer2); expected.add(customer3); Assert.assertEquals(expected, customers); } }
package com.bruce.singleton.type1_ehanshi; public class SingletonTest01 { public static void main(String[] args) { //todo more logics Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); System.out.println(s1==s2); System.out.println(s1.hashCode()+".."+s2.hashCode()); } } class Singleton{ //¹¹ÔìÆ÷˽Óл¯ private Singleton() { } private final static Singleton instance=new Singleton(); public static Singleton getInstance() { return instance; } }
package com.cn.service.impl; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cn.dao.UserDaoInterface; import com.cn.domain.Users; import com.cn.service.UserServiceInterface; @Service(value="userService") public class UserServiceImpl implements UserServiceInterface { private UserDaoInterface userDaoInterface; @Override public void test() { // TODO Auto-generated method stub System.out.print("测试成功"); } @Override public Serializable add(Users users) { // TODO Auto-generated method stub return userDaoInterface.add(users); } public UserDaoInterface getUserDaoInterface() { return userDaoInterface; } @Autowired public void setUserDaoInterface(UserDaoInterface userDaoInterface) { this.userDaoInterface = userDaoInterface; } @Override public List<Users> showUsers() { // TODO Auto-generated method stub List<Users> users = userDaoInterface.show(); return users; } }
package by.realovka.diploma.service; import by.realovka.diploma.entity.User; import by.realovka.diploma.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; class UserServiceImplTest { @InjectMocks private UserServiceImpl userService; @Mock private UserRepository userRepositoryMock; @BeforeEach public void init() { MockitoAnnotations.initMocks(this); } @Test void getUserById_Found_User() { when(userRepositoryMock.findById(1)).thenReturn(new User (1, "User", "USER")); User userFindById = userService.getUserById(1); assertEquals(1, userFindById.getId()); assertEquals("User", userFindById.getUsername()); assertEquals("USER", userFindById.getPassword()); } }
package no.ntnu.stud.ubilearn.fragments.practise; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Locale; import no.ntnu.stud.ubilearn.R; import no.ntnu.stud.ubilearn.db.PractiseDAO; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import no.ntnu.stud.ubilearn.models.BalanceSPPB; import no.ntnu.stud.ubilearn.models.SPPB; import no.ntnu.stud.ubilearn.models.StandUpSPPB; import no.ntnu.stud.ubilearn.models.WalkingSPPB; public class SPPBResultsFragment extends Fragment { private int patientId; private PractiseDAO dao; private WalkingSPPB walking; private BalanceSPPB balance; private StandUpSPPB standUp; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_practise_sbbp_results, container, false); patientId = getArguments().getInt("id"); dao = new PractiseDAO(getActivity()); dao.open(); HashMap<String,SPPB> tests = dao.getNewestResults(patientId); dao.close(); walking = (WalkingSPPB) tests.get("Walking"); balance = (BalanceSPPB) tests.get("Balance"); standUp = (StandUpSPPB) tests.get("StandUp"); fillWalkingFields(view); fillBalanceFields(view); fillStandUpFields(view); return view; } /** * Fills inn all the fields in the Walking test part of the screen * @param view the View that this fragment uses. */ private void fillWalkingFields(View view){ TextView testName = (TextView) view.findViewById(R.id.testName1); TextView testDate = (TextView) view.findViewById(R.id.testDate1); TextView time = (TextView) view.findViewById(R.id.time1); TextView total = (TextView) view.findViewById(R.id.total1); TextView aids = (TextView) view.findViewById(R.id.aids1); if (walking != null){ testName.setText(walking.getName()); testDate.setText("Dato: " + new SimpleDateFormat( "dd.MM.yyyy", Locale.getDefault()).format(walking.getCreatedAt())); time.setText("" + walking.getTime()); aids.setText("" + walking.getAidsString()); total.setText("" + walking.getScore()); } else{ testName.setText("Gangtest"); testDate.setText("Ingen gangtester funnet"); time.setText("-"); aids.setText("-"); total.setText("0"); } } /** * Fills inn all the fields in the Balance test part of the screen * @param view the View that this fragment uses. */ private void fillBalanceFields(View view){ TextView testName = (TextView) view.findViewById(R.id.testName2); TextView testDate = (TextView) view.findViewById(R.id.testDate2); TextView score1 = (TextView) view.findViewById(R.id.score1); TextView score2 = (TextView) view.findViewById(R.id.score2); TextView score3 = (TextView) view.findViewById(R.id.score3); TextView total = (TextView) view.findViewById(R.id.total2); if (balance != null){ testName.setText(balance.getName()); testDate.setText("Dato: " + new SimpleDateFormat( "dd.MM.yyyy", Locale.getDefault()).format(balance.getCreatedAt())); score1.setText(""+balance.getPairedScore()); score2.setText(""+balance.getSemiTandemScore()); score3.setText(""+balance.getTandemScore()); total.setText(""+balance.getScore()); } else{ testName.setText("Balansetest"); testDate.setText("Ingen balansetester funnet"); score1.setText("-"); score2.setText("-"); score2.setText("-"); total.setText("0"); } } /** * Fills inn all the fields in the StandUp test part of the screen * @param view the View that this fragment uses. */ private void fillStandUpFields(View view){ TextView testName = (TextView) view.findViewById(R.id.testName3); TextView testDate = (TextView) view.findViewById(R.id.testDate3); TextView time = (TextView) view.findViewById(R.id.time3); TextView total = (TextView) view.findViewById(R.id.total3); TextView seatHeight = (TextView) view.findViewById(R.id.seatHeight); if (standUp != null){ testName.setText(standUp.getName()); testDate.setText("Dato: " + new SimpleDateFormat( "dd.MM.yyyy", Locale.getDefault()).format(standUp.getCreatedAt())); time.setText("" + standUp.getTime()); total.setText("" + standUp.getScore()); seatHeight.setText(standUp.getSeatHeight()); } else{ testName.setText("Reise seg test"); testDate.setText("Ingen Resise seg tester funnet"); time.setText("-"); total.setText("0"); seatHeight.setText("-"); } } }
package com.sinodynamic.hkgta.dao.crm; import java.io.Serializable; import java.util.Date; import java.util.List; import org.hibernate.HibernateException; import com.sinodynamic.hkgta.dao.IBaseDao; import com.sinodynamic.hkgta.dto.crm.DaypassPurchaseDto; import com.sinodynamic.hkgta.entity.crm.ServicePlan; import com.sinodynamic.hkgta.entity.crm.ServicePlanAdditionRule; import com.sinodynamic.hkgta.entity.crm.ServicePlanFacility; import com.sinodynamic.hkgta.entity.crm.ServicePlanRightMaster; import com.sinodynamic.hkgta.entity.fms.FacilityType; import com.sinodynamic.hkgta.entity.rpos.PosServiceItemPrice; import com.sinodynamic.hkgta.util.pagination.ListPage; public interface ServicePlanDao extends IBaseDao<ServicePlan>{ public abstract Serializable saveServicePlan(ServicePlan servicePlan) throws HibernateException; public abstract List<FacilityType> getFacilityTypes() throws HibernateException; public abstract List<ServicePlan> getAllServicePlan() throws HibernateException; public abstract ServicePlan getServicePlanById(Long planNo) throws HibernateException; public abstract ServicePlanAdditionRule getServicePlanAdditionRuleByFK(long planNo,String rightCode) throws HibernateException; public abstract ServicePlanFacility getServicePlanFacilityByFK(long planNo,String facilityType) throws HibernateException; public abstract List<ServicePlanRightMaster> getServicePlanRights() throws HibernateException; public abstract void deleteServicePlan(ServicePlan sp) throws HibernateException; public abstract List<ServicePlan> getValidServicPlan(); public abstract List<ServicePlan> getValidCorporateServicPlan(); public abstract List<ServicePlan> getExpiredServicePlans(String status); public abstract List<PosServiceItemPrice> getDaypassPriceItemNo(Long planNo, String type); public abstract List<ServicePlan> getServiceplanByDate(DaypassPurchaseDto dto); public abstract String getServiceplanQuotaById(Long planNo); public abstract List<ServicePlan> getValidDaypass(); public ServicePlan getByplanName(String planName); ListPage getDailyDayPassUsageList(String date, String orderColumn, String order, int pageSize, int currentPage, String filterSQL); }
package controlador; public class GenerarTiempoEstClienteHabSimple { }
/* * 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 demoalchemy; import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyVision; import com.ibm.watson.developer_cloud.alchemy.v1.model.ImageFaces; import com.ibm.watson.developer_cloud.alchemy.v1.model.ImageKeywords; import java.io.File; /** * * @author Jaime Ambrosio */ public class AlchemyVisionDemo { /** * @param args the command line arguments */ public static void main(String[] args) { AlchemyVision service = new AlchemyVision(); service.setApiKey("2c9642caf5d75d2976e6b55637b3a8a23e5f910c"); File image = new File("C:\\Users\\Jaime Ambrosio\\Desktop\\img\\mario.jpg"); Boolean forceShowAll = true; Boolean knowledgeGraph = true; try { ImageKeywords keywords = service.getImageKeywords(image, forceShowAll, knowledgeGraph).execute(); System.out.println(keywords); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("_______________"); try { ImageFaces faces = service.recognizeFaces(image, true).execute(); System.out.println(faces); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package com.example.demoNew.Controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demoNew.Entity.DemoEntity; import com.example.demoNew.Service.DemoInterface; @RestController @RequestMapping("/") public class DemoController { @Autowired private DemoInterface DemoInterface; @PostMapping("/demo") public String getdemo() { return "Welcome"; } @PostMapping("/about") public String about() { return "https://www.google.co.in/"; } @PostMapping("/add") public String getcredit(@RequestBody DemoEntity demo) { DemoInterface.save(demo); return "Credit @SGM LLP"; } @GetMapping("/show") public List<DemoEntity> getData(){ return DemoInterface.findAll(); } }
package com.awakenguys.kmitl.ladkrabangcountry; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.widget.Toast; import com.awakenguys.kmitl.ladkrabangcountry.model.User; public class Profile extends Activity { private static User user = null; private static Context mContext; private static String picURI = null; public static String getPicURI() { return picURI; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); mContext = this; if(user==null||user.getLevel()==User.GUEST) login(); else finish(); } public static boolean isLoggedIn() { return user != null; } public static User getUser() { return user; } public static void logout() { user = null; picURI = null; } public void setUser(User user) { this.user = user; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK) { User user; String fbId = data.getStringExtra("fbId"); String fullName = data.getStringExtra("fullName"); picURI = data.getStringExtra("profileImg"); if(fullName.equals("Guest")) user = new User(null,"Guest",User.GUEST); else user = new User(fbId, fullName, User.MEMBER); new LogInTask().execute(user); } }else Toast.makeText(Profile.this, "error!" , Toast.LENGTH_SHORT).show(); } public void login(){ startActivityForResult(new Intent(this, LogInActivity.class), 1); } private class LogInTask extends AsyncTask<User, Void, User> { @Override protected User doInBackground(User... params) { User user = login(params[0]); return user; } @Override protected void onPostExecute(User user) { super.onPostExecute(user); //setUser(user); ((Activity)mContext).finish(); if(user==null) Toast.makeText(Profile.this, "No internet connection.",Toast.LENGTH_SHORT).show(); Toast.makeText(Profile.this, "Welcome "+user.getName(), Toast.LENGTH_SHORT).show(); } private User login(User login_user) { ContentProvider provider = new ContentProvider(); user = provider.getUserByFbId(login_user.getFbId()); try { if (user == null) { if (login_user.getLevel() != User.GUEST) { HTTPRequest rq = new HTTPRequest(); rq.executeGet("http://203.151.92.199:8888/adduser?fbId=" + login_user.getFbId() + "&name=" + login_user.getName()); user = provider.getUserByFbId(login_user.getFbId()); } else user = new User(null, "Guest", User.GUEST); } } catch (Exception e) { e.printStackTrace(); } finally { return user; } } } }
package com.legaoyi.protocol.down.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 音视频回放控制 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2018-04-09 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "9202_2016" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT1078_9202_MessageBody extends MessageBody { private static final long serialVersionUID = -2222441901600081391L; public static final String MESSAGE_ID = "9202"; /** 逻辑通道号 **/ @JsonProperty("channelId") private int channelId; /** 回放方式 **/ @JsonProperty("playbackType") private int playbackType; /** 快进或快退倍数 **/ @JsonProperty("playTimes") private int playTimes; /** 回放起始时间 **/ @JsonProperty("startTime") private String startTime; public final int getChannelId() { return channelId; } public final void setChannelId(int channelId) { this.channelId = channelId; } public final int getPlaybackType() { return playbackType; } public final void setPlaybackType(int playbackType) { this.playbackType = playbackType; } public final int getPlayTimes() { return playTimes; } public final void setPlayTimes(int playTimes) { this.playTimes = playTimes; } public final String getStartTime() { return startTime; } public final void setStartTime(String startTime) { this.startTime = startTime; } }
package yinq.userModule; import java.lang.reflect.InvocationTargetException; import yinq.Request.HttpRequestManager; import yinq.Request.HttpRequestObservice; import yinq.userModule.requests.UserInfoRequest; import yinq.userModule.requests.UserLoginRequest; /** * Created by YinQ on 2018/11/29. */ public class UserUtil { public UserUtil(){ } public void startLogin(String account, String password, HttpRequestObservice observice) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { UserLoginRequest.LoginParam loginParam = new UserLoginRequest.LoginParam(account, password); HttpRequestManager.createRequest(UserLoginRequest.class, loginParam.toJson(), observice); } public void startGetUserInfo(String userId, HttpRequestObservice observice) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { UserInfoRequest.UserInfoParam param = new UserInfoRequest.UserInfoParam(userId); HttpRequestManager.createRequest(UserInfoRequest.class, param.toJson(), observice); } }
package com.bslp_lab1.changeorg.configuration; import com.bslp_lab1.changeorg.DTO.PetitionDTO; import com.bslp_lab1.changeorg.DTO.ResponseMessageDTO; import com.bslp_lab1.changeorg.DTO.SubscribersDTO; import com.bslp_lab1.changeorg.DTO.UserDTO; import com.bslp_lab1.changeorg.beans.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class ChangeorgConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean @Scope(scopeName = "prototype") public User getUser(){ return new User(); } @Bean @Scope(scopeName = "prototype") public Petition getPetition(){ return new Petition(); } @Bean @Scope(scopeName = "prototype") public Subscribers getSubscribers(){ return new Subscribers(); } @Bean @Scope(scopeName = "prototype") public ResponseMessageDTO getResponseMessageDTO(){ return new ResponseMessageDTO(); } @Bean(name = "UserDTO") @Scope(scopeName = "prototype") public UserDTO getUserDTO(){ return new UserDTO(); } @Bean(name = "PetitionDTO") @Scope(scopeName = "prototype") public PetitionDTO getPetitionDTO() {return new PetitionDTO();} @Bean(name = "SubscribersDTO") @Scope(scopeName = "prototype") public SubscribersDTO getSubscribersDTO() {return new SubscribersDTO();} }
package f.star.iota.milk.ui.acg17.acg; import android.os.Bundle; import f.star.iota.milk.base.ScrollImageFragment; public class ACG17Fragment extends ScrollImageFragment<ACG17Presenter, ACG17Adapter> { public static ACG17Fragment newInstance(String url) { ACG17Fragment fragment = new ACG17Fragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url); bundle.putString("page_suffix", "/"); fragment.setArguments(bundle); return fragment; } @Override protected ACG17Presenter getPresenter() { return new ACG17Presenter(this); } @Override protected ACG17Adapter getAdapter() { return new ACG17Adapter(); } }
package io.jenkins.plugins.audit.filter; import hudson.Extension; import hudson.init.Initializer; import hudson.model.User; import hudson.util.PluginServletFilter; import org.apache.logging.log4j.ThreadContext; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.UUID; @Extension public class RequestContextFilter implements Filter { /** * Registering the filter */ @Initializer public static void init() throws ServletException { PluginServletFilter.addFilter(new RequestContextFilter()); } @Override public void init(FilterConfig filterConfig) throws ServletException { // do nothing } @Override public void destroy() { // do nothing } /** * The filter through which the flow passes is used to set the context level attributes */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { User user = User.current(); ThreadContext.put("userId", user != null ? user.getId() : "SYSTEM"); ThreadContext.putIfNull("requestId", UUID.randomUUID().toString()); if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; ThreadContext.put("requestMethod", httpRequest.getMethod()); ThreadContext.put("requestUri", httpRequest.getRequestURI()); } chain.doFilter(request, response); ThreadContext.clearMap(); } }
package com.zhanwei.java.classloader; public class App { @Override public String toString() { // TODO Auto-generated method stub return "App{}"; } }
package ua.dao; import ua.domain.Category; import java.util.List; public interface CategoryDAO { void add(Category category); void delete(long id); Category findOne(long id); List<Category> list(); byte[] getPictureBody(long id); }
package org.linphone; import android.app.Dialog; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import org.linphone.Utils.AppLog; import org.linphone.core.LinphoneAccountCreator; import org.linphone.core.LinphoneAddress; import org.linphone.core.LinphoneAuthInfo; import org.linphone.core.LinphoneCall; import org.linphone.core.LinphoneCallParams; import org.linphone.core.LinphoneChatMessage; import org.linphone.core.LinphoneChatRoom; import org.linphone.core.LinphoneCore; import org.linphone.core.LinphoneCoreException; import org.linphone.core.LinphoneCoreFactory; import org.linphone.core.LinphoneCoreListenerBase; import org.linphone.core.LinphoneProxyConfig; import org.linphone.mediastream.Log; import java.util.List; /** * Created by qckiss on 2017/8/18. */ public class LinphoneActivity extends AppCompatActivity{ private static LinphoneActivity instance; private LinphoneCoreListenerBase mListener; private LinphoneAddress address; private LinphoneAccountCreator accountCreator; private boolean alreadyAcceptedOrDeniedCall; private LinphoneCall mCall; private TextView textView; static final boolean isInstanciated() { return instance != null; } public static final LinphoneActivity instance() { if (instance != null) return instance; throw new RuntimeException("LinphoneActivity not instantiated yet"); } public void displayCustomToast(final String message, final int duration) { LayoutInflater inflater = getLayoutInflater(); // View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot)); // TextView toastText = (TextView) layout.findViewById(R.id.toastMessage); // toastText.setText(message); final Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(duration); // toast.setView(layout); toast.show(); } public Dialog displayDialog(String text){ Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC)); d.setAlpha(200); // dialog.setContentView(R.layout.dialog); dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); dialog.getWindow().setBackgroundDrawable(d); // TextView customText = (TextView) dialog.findViewById(R.id.customText); // customText.setText(text); return dialog; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_linphone); // mPrefs = LinphonePreferences.instance(); // status.enableSideMenu(false); accountCreator = LinphoneCoreFactory.instance().createAccountCreator(LinphoneManager.getLc(), LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setDomain(getResources().getString(R.string.default_domain)); // accountCreator.setListener(this); initLogin(); textView = (TextView) findViewById(R.id.states_tv); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { answer(); } }); mListener = new LinphoneCoreListenerBase(){ @Override public void messageReceived(LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) { // displayMissedChats(getUnreadMessageCount()); } @Override public void registrationState(LinphoneCore lc, LinphoneProxyConfig proxy, LinphoneCore.RegistrationState state, String smessage) { if (state.equals(LinphoneCore.RegistrationState.RegistrationCleared)) { if (lc != null) { LinphoneAuthInfo authInfo = lc.findAuthInfo(proxy.getIdentity(), proxy.getRealm(), proxy.getDomain()); if (authInfo != null) lc.removeAuthInfo(authInfo); } } // refreshAccounts(); // if(getResources().getBoolean(R.bool.use_phone_number_validation)) { // if (state.equals(LinphoneCore.RegistrationState.RegistrationOk)) { // LinphoneManager.getInstance().isAccountWithAlias(); // } // } // if(state.equals(LinphoneCore.RegistrationState.RegistrationFailed) && newProxyConfig) { // newProxyConfig = false; // if (proxy.getError() == Reason.BadCredentials) { // //displayCustomToast(getString(R.string.error_bad_credentials), Toast.LENGTH_LONG); // } // if (proxy.getError() == Reason.Unauthorized) { // displayCustomToast(getString(R.string.error_unauthorized), Toast.LENGTH_LONG); // } // if (proxy.getError() == Reason.IOError) { // displayCustomToast(getString(R.string.error_io_error), Toast.LENGTH_LONG); // } // } } @Override public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) { if (state == LinphoneCall.State.IncomingReceived) { AppLog.d("收到来电"); upState("收到来电"); // startActivity(new Intent(LinphoneActivity.instance(), CallIncomingActivity.class)); initLinphoneCall(); } else if (state == LinphoneCall.State.OutgoingInit || state == LinphoneCall.State.OutgoingProgress) { AppLog.d("state=OutgoingProgress"); // startActivity(new Intent(LinphoneActivity.instance(), CallOutgoingActivity.class)); } else if (state == LinphoneCall.State.CallEnd || state == LinphoneCall.State.Error || state == LinphoneCall.State.CallReleased) { AppLog.d("state=CallEnd"); // resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); } int missedCalls = LinphoneManager.getLc().getMissedCallsCount(); AppLog.d("MissedCallsCount丢失的数量="+missedCalls); // displayMissedCalls(missedCalls); } }; instance = this; } @Override protected void onResume() { super.onResume(); if (!LinphoneService.isReady()) { AppLog.w("LinphoneService掉了"); startService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class)); } LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); if (lc != null) { lc.addListener(mListener); } } @Override protected void onPause() { LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); if (lc != null) { lc.removeListener(mListener); } super.onPause(); } private void initLogin() { AppLog.d("登录initLogin"); // Bundle extras = new Bundle(); // extras.putString("Phone", null); // extras.putString("Dialcode", null); accountCreator = LinphoneCoreFactory.instance().createAccountCreator(LinphoneManager.getLc(), LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(new LinphoneAccountCreator.LinphoneAccountCreatorListener() { @Override public void onAccountCreatorIsAccountUsed(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { AppLog.d("开启 onAccountCreatorIsAccountUsed"); } @Override public void onAccountCreatorAccountCreated(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorAccountActivated(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorAccountLinkedWithPhoneNumber(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorPhoneNumberLinkActivated(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorIsAccountActivated(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorPhoneAccountRecovered(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorIsAccountLinked(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorIsPhoneNumberUsed(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } @Override public void onAccountCreatorPasswordUpdated(LinphoneAccountCreator accountCreator, LinphoneAccountCreator.Status status) { } }); LinphoneAddress.TransportType transport; // if(transports.getCheckedRadioButtonId() == R.id.transport_udp){ transport = LinphoneAddress.TransportType.LinphoneTransportUdp; // } else { // if(transports.getCheckedRadioButtonId() == R.id.transport_tcp){ // transport = LinphoneAddress.TransportType.LinphoneTransportTcp; // } else { // transport = LinphoneAddress.TransportType.LinphoneTransportTls; // } // } String name = "userc"; String pwd = "123"; String domain = "10.0.0.99"; AppLog.d("开始登录name ="+ name + "pwd=" + pwd + "domain=" + domain); // AssistantActivity.instance().genericLogIn(name, pwd, null, domain, transport); genericLogIn(name, pwd, null, domain, transport); } boolean accountCreated = false; public void genericLogIn(String username, String password, String prefix, String domain, LinphoneAddress.TransportType transport) { if (accountCreated) { // retryLogin(username, password, prefix, domain, transport); } else { logIn(username, password, null, prefix, domain, transport, false); } } private void logIn(String username, String password, String ha1, String prefix, String domain, LinphoneAddress.TransportType transport, boolean sendEcCalibrationResult) { saveCreatedAccount(username, password, ha1, prefix, domain, transport); } private LinphonePreferences mPrefs; public void saveCreatedAccount(String username, String password, String prefix, String ha1, String domain, LinphoneAddress.TransportType transport) { if (accountCreated) return; AppLog.d("开始saveCreatedAccount"); mPrefs = LinphonePreferences.instance(); username = LinphoneUtils.getDisplayableUsernameFromAddress(username); domain = LinphoneUtils.getDisplayableUsernameFromAddress(domain); String identity = "sip:" + username + "@" + domain; try { address = LinphoneCoreFactory.instance().createLinphoneAddress(identity); } catch (LinphoneCoreException e) { Log.e(e); AppLog.e("LinphoneCoreException"); } boolean isMainAccountLinphoneDotOrg = domain.equals(getString(R.string.default_domain)); LinphonePreferences.AccountBuilder builder = new LinphonePreferences.AccountBuilder(LinphoneManager.getLc()) .setUsername(username) .setDomain(domain) .setHa1(ha1) .setPassword(password); if(prefix != null){ builder.setPrefix(prefix); } if (isMainAccountLinphoneDotOrg) {//是linphone的sip服务器 if (false) { builder.setProxy(domain) .setTransport(LinphoneAddress.TransportType.LinphoneTransportTcp); } else { builder.setProxy(domain) .setTransport(LinphoneAddress.TransportType.LinphoneTransportTls); } builder.setExpires("604800") .setAvpfEnabled(true) .setAvpfRRInterval(3) .setQualityReportingCollector("sip:voip-metrics@sip.linphone.org") .setQualityReportingEnabled(true) .setQualityReportingInterval(180) .setRealm("sip.linphone.org") .setNoDefault(false); // mPrefs.enabledFriendlistSubscription(getResources().getBoolean(R.bool.use_friendlist_subscription)); // mPrefs.setStunServer(getString(R.string.default_stun)); mPrefs.setIceEnabled(true); accountCreator.setPassword(password); accountCreator.setHa1(ha1); accountCreator.setUsername(username); } else {//自己的sip服务器 AppLog.d("自己的sip服务器"); String forcedProxy = ""; if (!TextUtils.isEmpty(forcedProxy)) { builder.setProxy(forcedProxy) .setOutboundProxyEnabled(true) .setAvpfRRInterval(5); } if(transport != null) { builder.setTransport(transport); } } if (getResources().getBoolean(R.bool.enable_push_id)) { AppLog.d("开启消息推送"); String regId = mPrefs.getPushNotificationRegistrationID(); String appId = getString(R.string.push_sender_id); if (regId != null && mPrefs.isPushNotificationEnabled()) { AppLog.d("开启消息推送1"); String contactInfos = "app-id=" + appId + ";pn-type=google;pn-tok=" + regId; builder.setContactParameters(contactInfos); } } try { AppLog.d("开始saveNewAccount"); builder.saveNewAccount(); // if(!newAccount) { // displayRegistrationInProgressDialog(); // } accountCreated = true; upState("用户已上线"); } catch (LinphoneCoreException e) { Log.e(e); AppLog.e("LinphoneCoreException"); } } private void upState(final String state) { runOnUiThread(new Runnable() { @Override public void run() { if (textView!=null) textView.setText(state); } }); } private void initLinphoneCall() { mCall = null; // Only one call ringing at a time is allowed每次只能打一个电话 if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) { List<LinphoneCall> calls = LinphoneUtils.getLinphoneCalls(LinphoneManager.getLc()); for (LinphoneCall call : calls) { if (LinphoneCall.State.IncomingReceived == call.getState()) { mCall = call; AppLog.d("得到了call"); break; } } } if (mCall == null) { //The incoming call no longer exists. Log.d("Couldn't find incoming call"); finish(); return; } LinphoneAddress address = mCall.getRemoteAddress(); LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address); if (contact != null) { // LinphoneUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); // name.setText(contact.getFullName()); AppLog.d("得到call name="+contact.getFullName()); } else { // name.setText(LinphoneUtils.getAddressDisplayName(address)); AppLog.d("得到call elsename="+LinphoneUtils.getAddressDisplayName(address)); } // number.setText(address.asStringUriOnly()); AppLog.d("得到call name="+address.asStringUriOnly()); textView.setText("来自"+contact.getFullName()+"的来电"); } /** * 接电话 */ private void answer() { if (alreadyAcceptedOrDeniedCall) { return; } alreadyAcceptedOrDeniedCall = true; LinphoneCallParams params = LinphoneManager.getLc().createCallParams(mCall); boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext()); if (params != null) { params.enableLowBandwidth(isLowBandwidthConnection); }else { Log.e("Could not create call params for call"); } if (params == null || !LinphoneManager.getInstance().acceptCallWithParams(mCall, params)) { // the above method takes care of Samsung Galaxy S Toast.makeText(this, R.string.couldnt_accept_call, Toast.LENGTH_LONG).show(); } else { if (!LinphoneActivity.isInstanciated()) { return; } LinphoneManager.getInstance().routeAudioToReceiver(); upState("已接通,通话中"); // LinphoneActivity.instance().startIncallActivity(mCall); } } }
package objetos.powerUps; import movimiento.Posicion; import objetos.aeronaves.Algo42; import objetos.armas.Arma; import objetos.armas.LaserCannon; /* * Clase que modela los power up que dan un ca��n laser de beneficio. */ public class DeLaser extends PowerUp { private LaserCannon arma; public DeLaser(int x, int y, LaserCannon arma) { super(x, y); this.arma = arma; } public DeLaser(Posicion posicion, LaserCannon arma) { super(posicion); this.arma = arma; } @Override public void darBeneficioA(Algo42 algo42) { this.arma.setBase(algo42); algo42.agregarArma(arma); } public Arma getArma() { return arma; } public void setArma(LaserCannon arma) { this.arma = arma; } }
package car_rent.rent; public enum CarSegment { BASIC, PREMIUM, VIP, TRANSPORT }
/* * @(#) EbmsRoutingInfoService.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.ebmsroutinginfo.service.impl; import org.apache.commons.lang.StringUtils; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.service.impl.BaseService; import com.esum.wp.ebms.ebmsroutinginfo.EbmsRoutingInfo; import com.esum.wp.ebms.ebmsroutinginfo.dao.IEbmsRoutingInfoDAO; import com.esum.wp.ebms.ebmsroutinginfo.service.IEbmsRoutingInfoService; /** * * @author heowon@esumtech.com * @version $Revision: 1.12 $ $Date: 2008/10/28 04:06:36 $ */ public class EbmsRoutingInfoService extends BaseService implements IEbmsRoutingInfoService { /** * Default constructor. Can be used in place of getInstance() */ public EbmsRoutingInfoService () {} public Object selectRoutingInfoList(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; return iEbmsRoutingInfoDAO.selectRoutingInfoList(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object checkEbmsRoutingInfoDuplicate(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; return iEbmsRoutingInfoDAO.checkEbmsRoutingInfoDuplicate(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object searchFromRole(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; EbmsRoutingInfo routingInfo = (EbmsRoutingInfo)object; if(routingInfo.getDbType().equals("mssql")) { EbmsRoutingInfo routingInfo2 = (EbmsRoutingInfo)iEbmsRoutingInfoDAO.searchFromRoleCount(object); int totalCnt = routingInfo2.getTotalCount().intValue(); int mod = totalCnt % routingInfo.getItemCountPerPage().intValue(); int start = ((routingInfo.getCurrentPage().intValue() - 1) * routingInfo.getItemCountPerPage().intValue()) + 1; int end = start+mod == (totalCnt + 1) ? totalCnt : (start + routingInfo.getItemCountPerPage().intValue()) - 1; int offset = start+mod == (totalCnt+1) ? mod : routingInfo.getItemCountPerPage().intValue(); routingInfo.setTotalCount(new Integer(totalCnt)); routingInfo.setItemCount(new Integer(end)); routingInfo.setOffset(new Integer(offset)); } return iEbmsRoutingInfoDAO.searchFromRole(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object searchToRole(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; EbmsRoutingInfo routingInfo = (EbmsRoutingInfo)object; if(routingInfo.getDbType().equals("mssql")) { EbmsRoutingInfo routingInfo2 = (EbmsRoutingInfo)iEbmsRoutingInfoDAO.searchToRoleCount(object); int totalCnt = routingInfo2.getTotalCount().intValue(); int mod = totalCnt % routingInfo.getItemCountPerPage().intValue(); int start = ((routingInfo.getCurrentPage().intValue() - 1) * routingInfo.getItemCountPerPage().intValue()) + 1; int end = start+mod == (totalCnt + 1) ? totalCnt : (start + routingInfo.getItemCountPerPage().intValue()) - 1; int offset = start+mod == (totalCnt+1) ? mod : routingInfo.getItemCountPerPage().intValue(); routingInfo.setTotalCount(new Integer(totalCnt)); routingInfo.setItemCount(new Integer(end)); routingInfo.setOffset(new Integer(offset)); } return iEbmsRoutingInfoDAO.searchToRole(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object searchCpaId(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; EbmsRoutingInfo routingInfo = (EbmsRoutingInfo)object; if(routingInfo.getDbType().equals("mssql")) { EbmsRoutingInfo routingInfo2 = (EbmsRoutingInfo)iEbmsRoutingInfoDAO.searchCpaIdCount(object); int totalCnt = routingInfo2.getTotalCount().intValue(); int mod = totalCnt % routingInfo.getItemCountPerPage().intValue(); int start = ((routingInfo.getCurrentPage().intValue() - 1) * routingInfo.getItemCountPerPage().intValue()) + 1; int end = start+mod == (totalCnt + 1) ? totalCnt : (start + routingInfo.getItemCountPerPage().intValue()) - 1; int offset = start+mod == (totalCnt+1) ? mod : routingInfo.getItemCountPerPage().intValue(); routingInfo.setTotalCount(new Integer(totalCnt)); routingInfo.setItemCount(new Integer(end)); routingInfo.setOffset(new Integer(offset)); } return iEbmsRoutingInfoDAO.searchCpaId(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object selectServiceInfoAll(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; return iEbmsRoutingInfoDAO.selectServiceInfoAll(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object selectAll(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; return iEbmsRoutingInfoDAO.selectAll(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object insertAll(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; EbmsRoutingInfo value = (EbmsRoutingInfo)object; Object obj = iEbmsRoutingInfoDAO.insertAll(value); for(int i=0;i<value.getServiceList().length;i++){ String service = value.getServiceList()[i]; String serviceInfo = value.getServiceInfoIdList()[i]; if(StringUtils.isNotEmpty(service) && StringUtils.isNotEmpty(serviceInfo) ){ value.setService(service); value.setServiceInfoId(serviceInfo); obj = iEbmsRoutingInfoDAO.insertService(value); } } return obj; } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object updateAll(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; EbmsRoutingInfo value = (EbmsRoutingInfo)object; Object obj = iEbmsRoutingInfoDAO.updateService(value); obj= iEbmsRoutingInfoDAO.deleteServiceInfoAll(value); for(int i=0;i<value.getServiceList().length;i++){ String service = value.getServiceList()[i]; String serviceInfo = value.getServiceInfoIdList()[i]; if(StringUtils.isNotEmpty(service) && StringUtils.isNotEmpty(serviceInfo) ){ value.setService(service); value.setServiceInfoId(serviceInfo); obj = iEbmsRoutingInfoDAO.insertService(value); } } return obj; } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object deleteAll(Object object) { try { IEbmsRoutingInfoDAO iEbmsRoutingInfoDAO = (IEbmsRoutingInfoDAO)iBaseDAO; Object obj = iEbmsRoutingInfoDAO.deleteAll(object); obj= iEbmsRoutingInfoDAO.deleteServiceInfoAll(object); return obj; } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } }
package com.jme.puer.backoffice.dao; import java.util.List; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; public interface IBaseMapperDao<E, PK> extends IBaseMapper { /** * @description 详细说明 * @param e */ @Options(useGeneratedKeys = true, keyProperty = "id") void add(final E e); /** * @description 详细说明 * @param e */ @Options(useGeneratedKeys = true, keyProperty = "id") void batchAdd(final List<E> list); /** * @description 详细说明 * @param e */ Integer remove(@Param(value = "id") final PK e); void batchRemove(final PK[] ids); /** * @description 详细说明 * @param e */ Integer update(final E e); /** * @description 详细说明 * @param id * @return * @throws Exception */ E getEntity(@Param(value = "id") final PK id); }
package com.example.crizma_pclaptop.pencil; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by CRIZMA_PC&LAPTOP on 10/06/2018. */ public class networkconfig { private static Retrofit retrofit; private networkconfig() { } public static Retrofit newInstance() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl("http://192.168.1.2/proj/") .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
package Business_Layer.UserManagement; import Business_Layer.Trace.PersonalPage; public class Coach extends Subscription { PersonalPage PersonalPage; protected String qualification; public void setPersonalPage(Business_Layer.Trace.PersonalPage personalPage) { PersonalPage = personalPage; } public Business_Layer.Trace.PersonalPage getPersonalPage() { return PersonalPage; } public Coach(String arg_user_name, String arg_password) { super(arg_user_name, arg_password); // add permissions og the role // permissions.add_permissions(1,0) PersonalPage = new PersonalPage(); } }
package com.cskaoyan; /** * @Author : zjf * @Date : 2019/6/5 下午 03:32 */ public class AliveUser { private static final ThreadLocal<String> thread = new ThreadLocal<>(); public static void setThread(String userName){ thread.set(userName); } public static String getThread(){ return thread.get(); } public static void cleanThread(){ thread.remove(); } }
package com.example.projetpfebam.controller; import com.example.projetpfebam.exception.ResourceNotFoundException; import com.example.projetpfebam.model.*; import com.example.projetpfebam.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/api") public class TacheController { @Autowired private AttestationTravailRepository attestationRepository; @Autowired private TacheDetailRepository taskRepository; @Autowired private AvanceSalaireRepository avancesalRepository; @Autowired private CongeRepository congeRepository; @Autowired private MissionEtrangerRepository missionRepository; public String aujourdhui() { final Date date = new Date(); return new SimpleDateFormat("yyyy-MM-dd").format(date); } @GetMapping(path = "/processus/getattestations") public List<AttestationTravail> getAllAttestations() { System.out.println("*********************"); return attestationRepository.findAll(); } @GetMapping(path = "/tasks") public Map<String, Object> getTasks() { Map<String, Object> map = new HashMap<>(); List<AttestationTravail> attestations = attestationRepository.findAll(); List<AvanceSalaire> avancesalaires = avancesalRepository.findAll(); List<Conge> conges = congeRepository.findAll(); List<MissionEtranger> missions = missionRepository.findAll(); map.put("Demande attestation de travail", attestations); map.put("Demande Avance Salaire", avancesalaires); map.put("Demande Conge", conges); map.put("Demande Mission à l'étranger", missions); return map; } @PostMapping("/processus/addattestation") public AttestationTravail demandeattestation(@RequestBody AttestationTravail attestationTravail) { System.out.println("**********************"); System.out.println(attestationTravail); AttestationTravail attest = attestationRepository.save(attestationTravail); return attest; } @PostMapping("/processus/avancesalaire") public AvanceSalaire demandeavancesalaire(@RequestBody AvanceSalaire avancesalaire) { System.out.println("**********************"); System.out.println(avancesalaire); return avancesalRepository.save(avancesalaire); } @PostMapping("/processus/conge") public Conge demandeconge(@RequestBody Conge conge) { System.out.println("**********************"); System.out.println(conge); return congeRepository.save(conge); } @PostMapping("/processus/mission") public MissionEtranger demandemission(@RequestBody MissionEtranger missionEtranger) { System.out.println("**********************"); System.out.println(missionEtranger); return missionRepository.save(missionEtranger); } @PutMapping("/refusattestation/{id}") public AttestationTravail updateAttestation(@PathVariable(value = "id") Long attestId, @RequestBody AttestationTravail attestation) throws ResourceNotFoundException { AttestationTravail attest = attestationRepository.findById(attestId) .orElseThrow(() -> new ResourceNotFoundException("Attestation travail not found on :: "+ attestId)); attest.setStatut("refusée"); attest.setDate_fin(aujourdhui()); final AttestationTravail attestrefus = attestationRepository.save(attest); return attestrefus; } @PutMapping("/refusavancesal/{id}") public AvanceSalaire updateAvanceSal(@PathVariable(value = "id") Long avancesalId, @RequestBody AvanceSalaire avancesal) throws ResourceNotFoundException { AvanceSalaire avance = avancesalRepository.findById(avancesalId) .orElseThrow(() -> new ResourceNotFoundException("Avance salaire not found on :: "+ avancesalId)); avance.setStatut("refusée"); avance.setDate_fin(aujourdhui()); final AvanceSalaire avancerefus = avancesalRepository.save(avance); return avancerefus; } @PutMapping("/refusconge/{id}") public Conge updateConge(@PathVariable(value = "id") Long congeId, @RequestBody Conge conge) throws ResourceNotFoundException { Conge congee = congeRepository.findById(congeId) .orElseThrow(() -> new ResourceNotFoundException("conge not found on :: "+ congeId)); congee.setStatut("refusée"); congee.setDate_fin(aujourdhui()); final Conge congerefus = congeRepository.save(congee); return congerefus; } @PutMapping("/refusmission/{id}") public MissionEtranger updateMission(@PathVariable(value = "id") Long missionId, @RequestBody MissionEtranger mission) throws ResourceNotFoundException { MissionEtranger missionn = missionRepository.findById(missionId) .orElseThrow(() -> new ResourceNotFoundException("Mission not found on :: "+ missionId)); missionn.setStatut("refusée"); missionn.setDate_fin(aujourdhui()); final MissionEtranger missionrefus = missionRepository.save(missionn); return missionrefus; } }
package com.sevenfive.assignment4.auth; import com.sevenfive.assignment4.DAO; import com.sevenfive.assignment4.auth.models.User; import java.util.HashMap; import java.util.Map; public class Auth implements IAuthentication { private static final String TAG = Auth.class.getSimpleName(); private final Map<String, User> map = new HashMap<>(); private static volatile Auth mInstance; public synchronized static Auth getInstance(){ if(mInstance == null){ mInstance = new Auth(); } return mInstance; } private Auth() { super(); } @Override public boolean verifyCredentials(String token,String username, String password) { //fill the user User user = map.getOrDefault(token,null); user.setUsername(username); user.setRole(DAO.getInstance().getRole(username)); return DAO.getInstance().searchForUser(username,password); } @Override public void invalidateSession(String token) { map.remove(token); } @Override public void logAnnonUser(String token) { User user = new User(); user.setToken(token); map.put(token,user); } @Override public boolean isLoggedIn(String token) { boolean isLoggedIn = false; User usr = map.getOrDefault(token,null); //this means it's an anonymous user if(usr!=null){ isLoggedIn = usr.isAuthenticated(); } return isLoggedIn; } @Override public void authenticateUser(String token, boolean isAuthenticated) { User user = map.getOrDefault(token,null); user.setAuthenticated(true); } @SuppressWarnings({"NullPointerException", "ConstantConditions"}) public boolean isAuthorized(String token, Role targetRole){ User user = getUser(token); String userRole = user.getRole(); Integer userPrivilege = Role.privilegeLevel(userRole); try{ return userPrivilege == Role.ADMIN.privilegeLevel || userPrivilege.equals(targetRole.privilegeLevel); } catch (Exception ex){ return false; } } @Override public User getUser(String token) { return map.getOrDefault(token,null); } public enum Role{ ADMIN(1,"admin"), VENDOR(3,"vendor"), CUSTOMER(2,"customer"); int privilegeLevel; String role; private Role(int v,String role){ privilegeLevel = v; this.role = role; } public int getPrivilegeLevel(){ return privilegeLevel; } @Override public String toString() { return role; } public static Integer privilegeLevel(String role){ switch (role) { case "admin": return ADMIN.privilegeLevel; case "customer": return CUSTOMER.privilegeLevel; case "vendor": return VENDOR.privilegeLevel; } return null; } } }
package object.simulation; public class ResultsDataEntry { private int iteration; private int specimen; private double energy; private double discomfort; private double cost; ResultsDataEntry(int iteration, int specimen, double energy, double discomfort, double cost) { this.iteration = iteration; this.specimen = specimen; this.energy = energy; this.discomfort = discomfort; this.cost = cost; } int get_iteration() { return this.iteration; } int get_specimen() { return this.specimen; } double get_energy() { return this.energy; } double get_discomfort() { return this.discomfort; } double get_cost() { return this.cost; } }
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeu.controller; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.images.ImagesService; import com.google.appengine.api.images.ImagesServiceFactory; import codeu.model.data.User.Sex; import codeu.model.data.User; import codeu.model.store.basic.UserStore; import codeu.model.store.basic.PostStore; import codeu.model.store.basic.CommentStore; import codeu.model.data.Post; import codeu.model.data.Comment; import java.util.*; public class ProfileServlet extends HttpServlet { private UserStore userStore; private PostStore postStore; private CommentStore commentStore; BlobstoreService blobstoreService; ImagesService imagesService; @Override public void init() throws ServletException { super.init(); postStore = PostStore.getInstance(); commentStore = CommentStore.getInstance(); userStore = UserStore.getInstance(); //Some necessities for grabbing images blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); imagesService = ImagesServiceFactory.getImagesService(); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String profileEditName = getNameFromURL(request.getRequestURL()); User user = userStore.getUser(profileEditName); UserStore userStore = UserStore.getInstance(); //Sets the birthday from the user's form if he filled it out String newBirthday = request.getParameter("updated birthday"); if(newBirthday != null) { user.setBirthday(parseDate(newBirthday)); } //Sets the description from the user's form if it's been filled out String newDescription = request.getParameter("updated description"); //Using short circuit boolean to avoid NullPointerException if(newDescription != null && !newDescription.trim().equals("")) { user.setDescription(newDescription); } //Sets the sex from the user's form if it's been changed String newSex = request.getParameter("updated sex"); if(newSex != null && !newSex.equals("default")) { user.setSex(Sex.valueOf(newSex)); } //Sets the email from the user's form if it's been filled out String newEmail = request.getParameter("updated email"); if(newEmail != null && !newEmail.trim().equals("")) { user.setEmail(newEmail); } //Sets occupation based on what the workstatus is for the user String workStatus = request.getParameter("updated work status"); if(workStatus != null && !workStatus.equals("default")) { if(!workStatus.equals("unemployed")) { String f1 = request.getParameter("updated f1"); String f2 = request.getParameter("updated f2"); if(f1 != null && f2 != null & !f1.trim().equals("") && !f2.trim().equals("")) { System.out.println("set occ"); user.setOccupation(user.new Occupation(f1,f2)); } else { //Make them redo the form } } else { user.setOccupation(user.new Occupation()); } } userStore.updateUser(user); doGet(request, response); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Gets the user name from the URL String profileRequestName = getNameFromURL(request.getRequestURL()); //Checks to make sure the page requested is a valid username if (!userStore.isUserRegistered(profileRequestName)) { response.sendRedirect("../404.html"); return; } User currentUser = userStore.getUser(profileRequestName); UUID currentUserID = currentUser.getId(); List<Post> allUsersPosts = postStore.getPostsByUserID(currentUserID.toString()); request.setAttribute("usersPosts", allUsersPosts); List<Comment> allComments = commentStore.getAllComments(); request.setAttribute("totalComments", allComments); if (!userStore.isUserRegistered(profileRequestName)) { response.sendRedirect("../404.html"); return; } request.setAttribute("blobstoreService", blobstoreService); request.setAttribute("requestedProfile", profileRequestName); if(request.getSession().getAttribute("user") != null) { String loggedInUserName = (String) request.getSession().getAttribute("user"); request.setAttribute("canEdit", loggedInUserName.equals(profileRequestName)); } else { request.setAttribute("canEdit", false); } request.getRequestDispatcher("/WEB-INF/view/profile.jsp").forward(request, response); } //A method I'm using to parse dates from String to Date private Date parseDate(String in) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date out; try { out = sdf.parse(in); } catch (Exception e) { out = null; } return out; } //A method I'm using to get the name given either a relative or absolute URL private String getNameFromURL(StringBuffer URL) { String URL_String = URL.toString(); int usernameStartIndex = URL_String.indexOf("/user/"); usernameStartIndex += "/user/".length(); return URL_String.substring(usernameStartIndex); } }
package com.codingchili.instance.model.npc; import com.codingchili.core.context.CoreRuntimeException; /** * @author Robin Duda * * Thrown when an npc is not found. */ public class NoSuchEntityException extends CoreRuntimeException { public NoSuchEntityException(String id) { super("Entity with the given id '" + id + "' not in npc/structure database."); } }
package cn.edu.cqut.util; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.Map; public class CustomResult extends CrmResult<Map<String, Object>> { public CustomResult() { } public CustomResult(List<JsonJ> data) { setJsonJ(data); } public CustomResult(JsonJ data) { setJsonJ(data); } public void setJsonJ(List<JsonJ> data) { super.setData(Lists.transform(data, JsonJ::getContent)); } public void setJsonJ(JsonJ data) { setJsonJ(Collections.singletonList(data)); } }
package pom; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; public class TestClase4 { private WebDriver driver; Levis_Page levis; @Before public void setUp() throws Exception { levis=new Levis_Page(driver); driver = levis.chromeDriverConnection(); levis.Visit("https://www.levi.com.ar/e-shop/hombres/categorias.html"); } @After public void tearDown() throws Exception { driver.quit(); } @Test public void test () throws Exception { levis.click_on_category(); System.out.println("Test completed"); } }
package com.tdr.registrationv3.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.tdr.registrationv3.R; import com.tdr.registrationv3.constants.UrlConstants; public class GlideUtil { /** * 压缩图 * * @param context * @param photoId * @param imageView */ public static void setImg(Context context, String photoId, final ImageView imageView) { String url = UrlConstants.main_host_service + "api/ddc-service/zimgCommon/getImg?photoId=" + photoId + "&width=120&height=120&quality=30"; Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { imageView.setBackgroundDrawable(new BitmapDrawable(resource)); } }); } /** * 原图 * * @param * @param context * @param photoId * @param imageView */ public static void setImgOriginal(Context context, String photoId, final ImageView imageView) { String url = UrlConstants.main_host_service + "api/ddc-service/zimgCommon/getImg?photoId=" + photoId; Glide.with(context).load(url).asBitmap() .placeholder(R.mipmap.image_load)//图片加载出来前,显示的图片 .fallback(R.mipmap.yl_load_error) //url为空的时候,显示的图片 .error(R.mipmap.yl_load_error) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { imageView.setImageBitmap(resource); } }); } }
package com.delaroystudios.alarmreminder; import android.animation.Animator; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.LoaderManager; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.content.res.ColorStateList; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Paint; import android.icu.util.LocaleData; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.delaroystudios.alarmreminder.data.AlarmReminderContract; import com.delaroystudios.alarmreminder.data.AlarmReminderDbHelper; import com.delaroystudios.alarmreminder.reminder.ReminderAlarmService; import java.lang.reflect.Field; import io.paperdb.Paper; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private Toolbar mToolbar; AlarmCursorAdapter mCursorAdapter; AlarmReminderDbHelper alarmReminderDbHelper = new AlarmReminderDbHelper(this); ListView reminderListView; ProgressDialog prgDialog; TextView textView; private static final int VEHICLE_LOADER = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); SharedPreferences prefer = getSharedPreferences("prefer",MODE_PRIVATE); boolean firstStart = prefer.getBoolean("firstStart",true); if(firstStart){ showDialog(); } textView = (TextView) findViewById(R.id.no_reminder); reminderListView = (ListView) findViewById(R.id.list); View emptyView = findViewById(R.id.empty_view); reminderListView.setEmptyView(emptyView); FloatingActionButton mAlarmButton = (FloatingActionButton) findViewById(R.id.fab2); mCursorAdapter = new AlarmCursorAdapter(this, null); reminderListView.setAdapter(mCursorAdapter); reminderListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, AddReminderActivity.class); Uri currentVehicleUri = ContentUris.withAppendedId(AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, id); // Set the URI on the data field of the intent intent.setData(currentVehicleUri); startActivity(intent); } }); FloatingActionButton mAddReminderButton = (FloatingActionButton) findViewById(R.id.fab); mAddReminderButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, AddReminderActivity.class)); } }); getLoaderManager().initLoader(VEHICLE_LOADER, null, this); //Alarm view mAlarmButton.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, RoutesActivity.class)); } }); } private void showDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Lưu ý"); builder.setMessage("Đảm bảo ứng dụng đã được cho phép trong cài đặt để có thể hoạt động."); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("Setting", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0); dialog.dismiss(); } }); builder.show(); SharedPreferences prefer = getSharedPreferences("prefer",MODE_PRIVATE); SharedPreferences.Editor editor = prefer.edit(); editor.putBoolean("firstStart",false); editor.apply(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_setting,menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.lang_en:{ Toast.makeText(this,"English",Toast.LENGTH_SHORT).show(); break; } case R.id.lang_vi:{ Toast.makeText(this,"Việt Nam",Toast.LENGTH_SHORT).show(); break; } case R.id.btn_crash: { showDialog(); } } return true; } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { String[] projection = { AlarmReminderContract.AlarmReminderEntry._ID, AlarmReminderContract.AlarmReminderEntry.KEY_TITLE, AlarmReminderContract.AlarmReminderEntry.KEY_DATE, AlarmReminderContract.AlarmReminderEntry.KEY_TIME, AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT, AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_NO, AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_TYPE, AlarmReminderContract.AlarmReminderEntry.KEY_ACTIVE }; return new CursorLoader(this, // Parent activity context AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, // Provider content URI to query projection, // Columns to include in the resulting Cursor null, // No selection clause null, // No selection arguments null); // Default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursorAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursorAdapter.swapCursor(null); } }
package com.sapl.retailerorderingmsdpharma.MyDatabase; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.sapl.retailerorderingmsdpharma.activities.MyApplication; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by Sony on 05/03/2018. */ public class TABLE_RETAILER_IMAGES { public static String NAME = "RetailerImages"; private static final String LOG_TAG = "TABLE_RETAILER_IMAGES"; public static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + NAME + "(ImageId TEXT,ImageDetails BLOB)"; public static void insertImageData(JSONArray jsonArray) { try { MyApplication.logi(LOG_TAG, "in insertImageData->"); SQLiteDatabase db = MyApplication.db.getWritableDatabase(); db.beginTransaction(); String insert_sql = "insert into " + NAME + " (" + "ImageId,ImageDetails) VALUES(?,?)"; MyApplication.logi(LOG_TAG, "insertImageData insert_sql" + insert_sql); SQLiteStatement statement = db.compileStatement(insert_sql); JSONObject jsonObject = null; int count_array = jsonArray.length(); MyApplication.logi(LOG_TAG, "insertImageData COUNT ISS->" + count_array); for (int i = 0; i < count_array; i++) { jsonObject = jsonArray.getJSONObject(i); statement.clearBindings(); statement.bindString(1, jsonObject.getString("ImageId")); statement.bindString(2, jsonObject.getString("ImageDetails")); statement.execute(); } MyApplication.logi(LOG_TAG, "insertImageData EndTime->"); db.setTransactionSuccessful(); db.endTransaction(); } catch (JSONException e) { e.printStackTrace(); } } public static void delete_table() { SQLiteDatabase db = MyApplication.db.getWritableDatabase(); String str1 = "select * from " + NAME; Cursor c = db.rawQuery(str1, null); int count= c.getCount(); MyApplication.logi(LOG_TAG, "Count"+count); int numRows = db.delete(NAME, null, null); MyApplication.logi(LOG_TAG, "In delete_tbl_timetable_sync"); MyApplication.logi(LOG_TAG, "DeletedRows:->" + numRows); } /*public static boolean RetailerImages_tableHasData() { int num = -1; MyApplication.logi(LOG_TAG, "in RetailerImagestableHasData()"); SQLiteDatabase db = MyApplication.db.getWritableDatabase(); String query = "SELECT * from RetailerImages"; MyApplication.log("In RetailerImages tableHasData query :" + query); Cursor c = db.rawQuery(query, null); num = c.getCount(); MyApplication.log("In RetailerImages has_tbl_data num is count : " + num); if (num > 0) { MyApplication.log("RetailerImages data is there : " + num); c.close(); return true; } else { MyApplication.log("RetailerImages data is not there : " + num); c.close(); return false; } }*/ }
package com.pinyougou.shop.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.github.pagehelper.PageInfo; import com.pinyougou.pojo.TbBrand; import com.pinyougou.pojo.TbSpecification; import com.pinyougou.sellergoods.service.BrandService; import com.pinyougou.sellergoods.service.SpecificationService; import entity.Result; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.UnsupportedEncodingException; import java.util.List; /** * 作者:传奇 * 包名:com.pinyougou.shop.controller * 创建时间:2019/7/25 9:16 */ @RequestMapping("/brand") @RestController public class BrandController { //注入品牌 @Reference BrandService brandService; @RequestMapping("/add") public Result add(@RequestBody TbBrand brand) throws UnsupportedEncodingException { try { brandService.add(brand); return new Result(true,"成功添加,需要审核"); } catch (Exception e) { e.printStackTrace(); return new Result(false,"网络开小差了。。"); } } @RequestMapping("/sepcfindAll") public List<TbBrand> sepcfindAll(){ List<TbBrand> list = brandService.selectAll(); return list; } @RequestMapping("/findPage") public PageInfo<TbBrand> findPage(@RequestParam(value = "pageNo", defaultValue = "1", required = true) Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "10", required = true) Integer pageSize) { return brandService.findPage(pageNo, pageSize); } @RequestMapping("/search") public PageInfo<TbBrand> findPage(@RequestParam(value = "pageNo", defaultValue = "1", required = true) Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "10", required = true) Integer pageSize, @RequestBody TbBrand tbBrand) { return brandService.findPage(pageNo, pageSize, tbBrand); } //模板页面加载查询查询所有审核过的品牌 @RequestMapping("/findAll") public List<TbBrand> findPage() { TbBrand tbBrand = new TbBrand(); tbBrand.setBrandStatus("1"); List<TbBrand> tbBrands = brandService.select(tbBrand); return tbBrands; } }
package hello; import java.util.Scanner; public class hello0 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); System.out.println("1¡¢hello1"); System.out.println("2¡¢hello2"); System.out.println("3¡¢hello3"); System.out.println("4¡¢hello4"); System.out.println("5¡¢hello5"); System.out.println("ÇëÑ¡ÖĞÄãµÄ²Ù×÷£º"); int i = in.nextInt(); if(i == 6) { hello6 h = new hello6(); }else if(i == 2) { hello2 h = new hello2(); } } }
package com.example.finalproject; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView pianoimg = findViewById(R.id.pianoimg); Spinner spinner = findViewById(R.id.notes); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.options, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(this); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); TextView scaletext1 = findViewById(R.id.scaletext1); TextView scaletext2 = findViewById(R.id.scaletext2); switch (position) { case 0: scaletext1.setText("C , D , E , F , G , A , B"); scaletext2.setText("C , D , D# , F , G , G# , A#"); break; case 1: scaletext1.setText("C# , D# , F , F# , G# , A# , C"); scaletext2.setText("C# , D# , E , F# , G# , A , B"); break; case 2: scaletext1.setText("D , E , F# , G , A , B , C#"); scaletext2.setText("D , E , F , G , A , A# , C"); break; case 3: scaletext1.setText("E♭, F, G, A♭, B♭, C, D"); scaletext2.setText("E♭, F, G♭, A♭, B♭, C♭, and D♭"); break; case 4: scaletext1.setText("E , F# , G# , A , B , C# , D#"); scaletext2.setText("E , F# , G , A , B , C , D"); break; case 5: scaletext1.setText("F, G, A, A#, C, D, E"); scaletext2.setText("F, G, A♭, B♭, C, D♭, and E♭"); break; case 6: scaletext1.setText("F♯, G♯, A♯, B, C♯, D♯, E♯"); scaletext2.setText("F♯, G♯, A, B, C♯, D, E"); break; case 7: scaletext1.setText("G, A, B, C, D, E, F♯"); scaletext2.setText("G, A, B♭, C, D, E♭, F"); break; case 8: scaletext1.setText("G♯, A♯, B♯, C♯, D♯, E♯, G"); scaletext2.setText("G♯, A♯, B, C♯, D♯, E, F♯"); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
/* * Copyright (c) 2013-2014, Neuro4j.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.neuro4j.studio.debug.core; import java.io.IOException; import java.net.ConnectException; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.internal.ui.DebugUIPlugin; import org.eclipse.debug.internal.ui.IInternalDebugUIConstants; import org.eclipse.debug.ui.contexts.ISuspendTrigger; import org.eclipse.jdi.Bootstrap; import org.eclipse.jdi.TimeoutException; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMConnector; import org.eclipse.osgi.util.NLS; import org.neuro4j.studio.debug.context.SuspendTrigger; import org.neuro4j.studio.debug.core.launching.LaunchingMessages; import org.neuro4j.studio.debug.core.model.FlowDebugTarget; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.AttachingConnector; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; public class FlowSocketAttachConnector implements IVMConnector { protected static AttachingConnector getAttachingConnector() throws CoreException { AttachingConnector connector = null; Iterator iter = Bootstrap.virtualMachineManager().attachingConnectors().iterator(); while (iter.hasNext()) { AttachingConnector lc = (AttachingConnector) iter.next(); if (lc.name().equals("com.sun.jdi.SocketAttach")) { connector = lc; break; } } if (connector == null) { abort(LaunchingMessages.SocketAttachConnector_Socket_attaching_connector_not_available_3, null, 114); } return connector; } public String getIdentifier() { return IJavaLaunchConfigurationConstants.ID_SOCKET_ATTACH_VM_CONNECTOR; } public String getName() { return LaunchingMessages.SocketAttachConnector_Standard__Socket_Attach__4; } protected static void abort(String message, Throwable exception, int code) throws CoreException { throw new CoreException(new Status(4, DebugExamplesPlugin.getID(), code, message, exception)); } public void connect(Map<String, String> arguments, IProgressMonitor monitor, ILaunch launch) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.SocketAttachConnector_Connecting____1, 2); subMonitor.subTask(LaunchingMessages.SocketAttachConnector_Configuring_connection____1); AttachingConnector connector = getAttachingConnector(); String portNumberString = (String) arguments.get("port"); if (portNumberString == null) { abort(LaunchingMessages.SocketAttachConnector_Port_unspecified_for_remote_connection__2, null, 111); } String host = (String) arguments.get("hostname"); if (host == null) { abort(LaunchingMessages.SocketAttachConnector_Hostname_unspecified_for_remote_connection__4, null, 109); } Map map = connector.defaultArguments(); Connector.Argument param = (Connector.Argument) map.get("hostname"); param.setValue(host); param = (Connector.Argument) map.get("port"); param.setValue(portNumberString); String timeoutString = (String) arguments.get("timeout"); if (timeoutString != null) { param = (Connector.Argument) map.get("timeout"); param.setValue(timeoutString); } ILaunchConfiguration configuration = launch.getLaunchConfiguration(); boolean allowTerminate = false; if (configuration != null) { allowTerminate = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_ALLOW_TERMINATE, false); } subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.SocketAttachConnector_Establishing_connection____2); try { VirtualMachine vm = connector.attach(map); String vmLabel = constructVMLabel(vm, host, portNumberString, configuration); // IDebugTarget debugTarget = JDIDebugModel.newDebugTarget(launch, vm, vmLabel, null, allowTerminate, true); IDebugTarget debugTarget = new FlowDebugTarget(launch, vm, vmLabel, allowTerminate, true, null, true); // int eventPort = findFreePort(); // IDebugTarget debugTarget = new PDADebugTarget(launch, null, 8888, int eventPort); launch.addDebugTarget(debugTarget); addSuspendListener(launch); BreakpoinMng.getInstance().setCurrentTarget(debugTarget); subMonitor.worked(1); subMonitor.done(); } catch (TimeoutException e) { abort(LaunchingMessages.SocketAttachConnector_0, e, 113); } catch (UnknownHostException e) { abort(NLS.bind(LaunchingMessages.SocketAttachConnector_Failed_to_connect_to_remote_VM_because_of_unknown_host____0___1, new String[] { host }), e, 113); } catch (ConnectException e) { abort(LaunchingMessages.SocketAttachConnector_Failed_to_connect_to_remote_VM_as_connection_was_refused_2, e, 113); } catch (IOException e) { abort(LaunchingMessages.SocketAttachConnector_Failed_to_connect_to_remote_VM_1, e, 113); } catch (IllegalConnectorArgumentsException e) { abort(LaunchingMessages.SocketAttachConnector_Failed_to_connect_to_remote_VM_1, e, 113); } } public static int findFreePort() { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } catch (IOException e) { } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return -1; } private void addSuspendListener(ILaunch launch) { ISuspendTrigger trigger = (ISuspendTrigger) launch.getAdapter(ISuspendTrigger.class); if (trigger != null) { trigger.addSuspendTriggerListener(new SuspendTrigger()); } DebugUIPlugin.getDefault().getPreferenceStore().setValue(IInternalDebugUIConstants.PREF_ACTIVATE_DEBUG_VIEW, Boolean.FALSE); } protected String constructVMLabel(VirtualMachine vm, String host, String port, ILaunchConfiguration configuration) { String name = null; try { name = vm.name(); } catch (TimeoutException localTimeoutException) { } catch (VMDisconnectedException localVMDisconnectedException) { } if (name == null) { if (configuration == null) name = ""; else { name = configuration.getName(); } } StringBuffer buffer = new StringBuffer(name); buffer.append('['); buffer.append(host); buffer.append(':'); buffer.append(port); buffer.append(']'); return buffer.toString(); } public Map<String, Connector.Argument> getDefaultArguments() throws CoreException { Map def = getAttachingConnector().defaultArguments(); Connector.IntegerArgument arg = (Connector.IntegerArgument) def.get("port"); arg.setValue(8000); return def; } public List<String> getArgumentOrder() { List list = new ArrayList(2); list.add("hostname"); list.add("port"); return list; } }
package com.jeffdisher.thinktank.crypto; import java.nio.ByteBuffer; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import java.util.UUID; /** * Inspired by JWT (JSON Web Token), but far simpler and specific to ThinkTank uses. May later be replaced by JWT but * there is no compelling reason to use that, at this time (it would add a dependency, requires a more complex * interpretation in ThinkTank code, requires more error handling/hardening around the JSON parser, and is larger). * This token has the following format: * -[0] - version byte - always 0. * -[1-16] - user UUID bytes in big-endian. * -[17-24] - expiry time in milliseconds since epoch. * -[25-n] - SHA512withECDSA signature in ASN.1 DER encoding (34-36 bytes long). * * Note that the token is always serialized as a Base64 string. */ public class BinaryToken { private static final int UUID_SIZE = Long.BYTES + Long.BYTES; private static final byte VERSION = 0; public static String createToken(PrivateKey key, UUID uuid, long expiryMillis) { ByteBuffer buffer = ByteBuffer.allocate(Byte.BYTES + UUID_SIZE + Long.BYTES); buffer.put(VERSION); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); buffer.putLong(expiryMillis); byte[] data = buffer.array(); byte[] signature = CryptoHelpers.sign(key, data); byte[] token = new byte[data.length + signature.length]; System.arraycopy(data, 0, token, 0, data.length); System.arraycopy(signature, 0, token, data.length, signature.length); return Base64.getEncoder().encodeToString(token); } public static UUID validateToken(PublicKey key, long nowMillis, String encodedToken) { byte[] raw = Base64.getDecoder().decode(encodedToken); byte[] data = new byte[Byte.BYTES + UUID_SIZE + Long.BYTES]; byte[] signature = new byte[raw.length - data.length]; System.arraycopy(raw, 0, data, 0, data.length); System.arraycopy(raw, data.length, signature, 0, signature.length); UUID valid = null; boolean isValid = CryptoHelpers.verify(key, data, signature); if (isValid) { ByteBuffer buffer = ByteBuffer.wrap(data); byte version = buffer.get(); if (VERSION == version) { long most = buffer.getLong(); long least = buffer.getLong(); long expiryMillis = buffer.getLong(); if (expiryMillis > nowMillis) { valid = new UUID(most, least); } } } return valid; } }
package com.doterob.transparencia.connector.contract.extractor.local.scq; /** * Created by dotero on 07/05/2016. */ public interface ScqPDFRowConstants { public static final int ROW_1 = 180; public static final float STEP = 42.5f; public static final int ROWS = 8; public static final int[] PHASES = {0, 4, -4, 8, -8, 12, -12, 16, -16, 20, -20, 24, -24}; }
package com.avalon.coe.backward; import com.avalon.coe.Producer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.kafka.clients.producer.ProducerRecord; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; /** * Created by adam on 1/24/17. */ public class RunProducer extends Producer { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RunProducer.class); public static void main(String[] args) throws IOException { if (args.length < 1) { LOGGER.error("must pass avro schema file name as argument"); System.exit(-1); } RunProducer producer = new RunProducer(); producer.sendData(args[0]); } private void sendData(String avroSchema) throws IOException { String key = "backward"; String topic = "backward"; Schema schema = new Schema.Parser().parse(new File("./src/main/resources/" + avroSchema)); GenericRecord avroRecord = new GenericData.Record(schema); avroRecord.put("user_id", "a568523"); avroRecord.put("event_id", "abc12345"); avroRecord.put("event_timestamp", "1485294737"); if (avroSchema.equals("user_new.avsc")) { avroRecord.put("event_type", "page_hit"); } LOGGER.info("created GenericRecord: " + avroRecord.toString()); ProducerRecord<String, GenericRecord> record = new ProducerRecord<>(topic, key, avroRecord); LOGGER.info("sending record to topic: " + topic); getProducer().send(record); LOGGER.info("record sent"); getProducer().close(); } }
package com.gaoshin.appbooster.service; import com.gaoshin.appbooster.entity.Application; import com.gaoshin.appbooster.entity.ApplicationType; public interface AppResolver { Application getApplication(String id); ApplicationType getType(); }
package com.sshfortress.common.huanxinutil; public class entity { private String uuid; private String type; private String created; private String modified; private String username; private String activated; private String nickname; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getActivated() { return activated; } public void setActivated(String activated) { this.activated = activated; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }
package com.yoga.controller; import java.sql.Timestamp; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.yoga.dao.TbCourseDAO; import com.yoga.dao.TbMemberCourseDAO; import com.yoga.dao.TbMemberCourseDetailDAO; import com.yoga.dao.TbStaffCourseClassroomsDAO; import com.yoga.dto.MemberCourseDetailDTO; import com.yoga.entity.TbCourse; import com.yoga.entity.TbMember; import com.yoga.entity.TbMemberCourse; import com.yoga.entity.TbMemberCourseDetail; import com.yoga.entity.TbStaffCourseClassrooms; import com.yoga.util.Constants; import com.yoga.util.JsonResponse; import com.yoga.util.Page; /** * action * * @author wwb * */ @Controller @RequestMapping("/") public class TbMemberCourseDetailController { /** * 获取dao */ private TbCourseDAO dao = new TbCourseDAO(); private TbMemberCourseDAO memberCourseDAO = new TbMemberCourseDAO(); private TbMemberCourseDetailDAO memberCourseDetailDAO = new TbMemberCourseDetailDAO(); private TbStaffCourseClassroomsDAO staffCourseClassroomsDAO = new TbStaffCourseClassroomsDAO(); /** * 添加信息 * * @return */ @RequestMapping(value = "memberCourse/add", method = RequestMethod.POST, consumes = "application/json") @ResponseBody public JsonResponse<TbMemberCourse> add(@RequestBody final MemberCourseDetailDTO[] memberCourseDetailDTOs) { JsonResponse<TbMemberCourse> jsonResponse = new JsonResponse<TbMemberCourse>(); try { // 用会员的编号+时间,作为消费的编号 // TODO 修改数据库的字段长度 // TODO还有一个数量没考虑到 double cost = 0.0; for (MemberCourseDetailDTO memberConsumeDetailDTO : memberCourseDetailDTOs) { String consumeId = memberConsumeDetailDTO.getCourseId(); TbStaffCourseClassrooms findById = staffCourseClassroomsDAO.findById(Integer.parseInt(consumeId)); String courseId = findById.getTbCourse().getCourseId(); TbCourse findById2 = dao.findById(courseId); String consumePrice = findById2.getCoursePrice(); cost += Double.parseDouble(consumePrice); } String memberCourseId = (memberCourseDetailDTOs[0].getMemberId() + System.currentTimeMillis()); TbMemberCourse entity = getBean(memberCourseId, memberCourseDetailDTOs[0].getMemberId(), cost + ""); memberCourseDAO.save(entity); for (MemberCourseDetailDTO memberCourseDetailDTO : memberCourseDetailDTOs) { TbMemberCourseDetail memberCourseDetail = new TbMemberCourseDetail(); TbStaffCourseClassrooms tbCourse = new TbStaffCourseClassrooms(); tbCourse.setId(Integer.parseInt(memberCourseDetailDTO.getCourseId())); TbMemberCourse tbMemberCourse = new TbMemberCourse(); tbMemberCourse.setMemberCourseId(memberCourseId); memberCourseDetail.setTbCourse(tbCourse); memberCourseDetail.setTbMemberCourse(tbMemberCourse); memberCourseDetailDAO.save(memberCourseDetail); } jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.COURSE, Constants.SUCCESS)); jsonResponse.setSuccess(true); } catch (Exception e) { e.printStackTrace(); jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.COURSE, Constants.FAILURE)); } return jsonResponse; } /** * 删除信息 * * @param id * @param name * @param price * @return */ @RequestMapping(value = "memberCourse/delete", method = RequestMethod.GET) public ModelAndView delete(final String id, final String memberId, String cost) { try { TbMemberCourse entity = getBean(id, memberId, cost); memberCourseDAO.update(entity); memberCourseDAO.delete(entity); memberCourseDetailDAO.delete(entity.getMemberCourseId()); } catch (Exception e) { e.printStackTrace(); } return new ModelAndView("memberCourse/index"); } /** * 获取列表 * * @param page * @param size * @param id * @param name * @param price * @return */ @RequestMapping(value = "memberCourse/list.html", method = RequestMethod.GET) @ResponseBody public JsonResponse<TbMemberCourse> list(@RequestParam(required = true, defaultValue = "1") int page, @RequestParam(required = true, defaultValue = "10") int size, @RequestParam(required = false) final String id, @RequestParam(required = false) final String name) { JsonResponse<TbMemberCourse> jsonResponse = new JsonResponse<TbMemberCourse>(); // 获取对应的参数 String[] params = new String[] { id, name }; try { if (params != null) { for (int i = 0; i < params.length; i++) { // 编码有问题,get传过来的参数 if (params[i] != null && !"".equals(params[i])) { String newStr = new String(params[i].getBytes("iso8859-1"), "UTF-8"); params[i] = newStr; } } } Page<TbMemberCourse> findAll = memberCourseDAO.findAll(page, size, params); jsonResponse.setSuccess(true); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.COURSE, Constants.SUCCESS)); jsonResponse.setPage(findAll); } catch (Exception e) { jsonResponse.setSuccess(false); jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.COURSE, Constants.FAILURE)); } return jsonResponse; } /** * 重构代码 * * @param id订单号 * @param memberId会员编号 * @param cost消费总额 * @return */ private TbMemberCourse getBean(final String id, final String memberId, String cost) { TbMemberCourse entity = null; try { entity = new TbMemberCourse(); entity.setMemberCourseId(id); TbMember tbMember = new TbMember(); tbMember.setMemberId(memberId); entity.setTbMember(tbMember); entity.setCreateTime(new Timestamp(System.currentTimeMillis())); entity.setCost(cost); } catch (Exception e) { e.printStackTrace(); } return entity; } }
package presz.bddtdd.tests.java.process; public enum RetourVirement { Ok, SoldeDepasse, PlafondDepasse, Ko }
package org.littlewings.infinispan.embedded.server.rest.test; import org.littlewings.infinispan.embedded.server.rest.EnableInfinispanEmbeddedRestServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableInfinispanEmbeddedRestServer public class App { public static void main(String... args) { SpringApplication.run(App.class, args); } }
package exercicio05; public class IngressoNormal extends Ingresso { IngressoNormal(float valorIngresso) { super(valorIngresso); // TODO Auto-generated constructor stub } public void total() { System.out.println("O valor do ingresso e: "+this.getValorIngresso()); } }
/** * Este paquete contiene la definicion de beans. */ package org.athento.nuxeo.rm.bean;
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.test; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.node.ObjectNode; import pl.edu.icm.unity.types.I18nString; import pl.edu.icm.unity.types.I18nStringJsonUtil; public class I18nJsonTest { @Test public void serializationIsReversible() { I18nString tested = new I18nString("defVal"); tested.addValue("pl", "val1"); tested.addValue("en", "val2"); ObjectNode json = I18nStringJsonUtil.toJson(tested); I18nString ret = I18nStringJsonUtil.fromJson(json); Assert.assertEquals(tested, ret); } }
package drivetrain; public class TankDriveControl extends DriveControl{//control robot in tank mode private static TankDriveControl tankdrivecontrol; //singleton instance private TankDriveControl() { } public static TankDriveControl getInstance(){ //get singleton instance if(tankdrivecontrol == null) { tankdrivecontrol = new TankDriveControl(); } return tankdrivecontrol; } @Override public void execute(double x1, double y1, double x2, double y2){ super.execute(y1, y2, 0, 0); //set motors based on two y-axis } }
package controller; import java.util.ArrayList; import java.util.Calendar; import model.ReplyMaterialDTO; public class ReplyMaterialController { private ArrayList<ReplyMaterialDTO> list; private int id; public ReplyMaterialController() { id = 1; list = new ArrayList<>(); ReplyMaterialDTO r1 = new ReplyMaterialDTO(); r1.setId(id++); r1.setFoodId(1); r1.setWriterId(1); r1.setContent("고마워용"); r1.setWrittenDate(Calendar.getInstance()); list.add(r1); r1 = new ReplyMaterialDTO(); r1.setId(id++); r1.setFoodId(2); r1.setWriterId(2); r1.setContent("완전 위꼴"); r1.setWrittenDate(Calendar.getInstance()); list.add(r1); } public ReplyMaterialDTO selectOne(int id) { for (ReplyMaterialDTO r : list) { if (r.getId() == id) { return r; } } return null; } // 푸드 id 받아서 해당 id 값과 일치하도록 하는 메소드 public ArrayList<ReplyMaterialDTO> selectById(int foodId) { ArrayList<ReplyMaterialDTO> temp = new ArrayList<>(); for (ReplyMaterialDTO r : list) { if (r.getFoodId() == foodId) { temp.add(r); } } return temp; } public void add(ReplyMaterialDTO r) { r.setId(id++); r.setWrittenDate(Calendar.getInstance()); list.add(r); } public void delete(ReplyMaterialDTO r) { list.remove(r); } // validateUserId public boolean validateWriterId(int writerId) { for(ReplyMaterialDTO r : list) { if(writerId == r.getWriterId()) { return true; } } return false; } }
package com.sunrj.application.System.dao; import java.util.List; import java.util.Map; public interface ssmTestDao { public List<Map<String,Object>> testMapper(); }