text
stringlengths 10
2.72M
|
|---|
/*
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.cloud.cloudant.v1.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* The postFind options.
*/
public class PostFindOptions extends GenericModel {
/**
* Whether to update the index prior to returning the result.
*/
public interface Update {
/** false. */
String X_FALSE = "false";
/** true. */
String X_TRUE = "true";
/** lazy. */
String LAZY = "lazy";
}
protected String db;
protected Map<String, Object> selector;
protected String bookmark;
protected Boolean conflicts;
protected Boolean executionStats;
protected List<String> fields;
protected Long limit;
protected Long skip;
protected List<Map<String, String>> sort;
protected Boolean stable;
protected String update;
protected List<String> useIndex;
protected Long r;
/**
* Builder.
*/
public static class Builder {
private String db;
private Map<String, Object> selector;
private String bookmark;
private Boolean conflicts;
private Boolean executionStats;
private List<String> fields;
private Long limit;
private Long skip;
private List<Map<String, String>> sort;
private Boolean stable;
private String update;
private List<String> useIndex;
private Long r;
private Builder(PostFindOptions postFindOptions) {
this.db = postFindOptions.db;
this.selector = postFindOptions.selector;
this.bookmark = postFindOptions.bookmark;
this.conflicts = postFindOptions.conflicts;
this.executionStats = postFindOptions.executionStats;
this.fields = postFindOptions.fields;
this.limit = postFindOptions.limit;
this.skip = postFindOptions.skip;
this.sort = postFindOptions.sort;
this.stable = postFindOptions.stable;
this.update = postFindOptions.update;
this.useIndex = postFindOptions.useIndex;
this.r = postFindOptions.r;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Instantiates a new builder with required properties.
*
* @param db the db
* @param selector the selector
*/
public Builder(String db, Map<String, Object> selector) {
this.db = db;
this.selector = selector;
}
/**
* Builds a PostFindOptions.
*
* @return the new PostFindOptions instance
*/
public PostFindOptions build() {
return new PostFindOptions(this);
}
/**
* Adds an fields to fields.
*
* @param fields the new fields
* @return the PostFindOptions builder
*/
public Builder addFields(String fields) {
com.ibm.cloud.sdk.core.util.Validator.notNull(fields,
"fields cannot be null");
if (this.fields == null) {
this.fields = new ArrayList<String>();
}
this.fields.add(fields);
return this;
}
/**
* Adds an sort to sort.
*
* @param sort the new sort
* @return the PostFindOptions builder
*/
public Builder addSort(Map<String, String> sort) {
com.ibm.cloud.sdk.core.util.Validator.notNull(sort,
"sort cannot be null");
if (this.sort == null) {
this.sort = new ArrayList<Map<String, String>>();
}
this.sort.add(sort);
return this;
}
/**
* Adds an useIndex to useIndex.
*
* @param useIndex the new useIndex
* @return the PostFindOptions builder
*/
public Builder addUseIndex(String useIndex) {
com.ibm.cloud.sdk.core.util.Validator.notNull(useIndex,
"useIndex cannot be null");
if (this.useIndex == null) {
this.useIndex = new ArrayList<String>();
}
this.useIndex.add(useIndex);
return this;
}
/**
* Set the db.
*
* @param db the db
* @return the PostFindOptions builder
*/
public Builder db(String db) {
this.db = db;
return this;
}
/**
* Set the selector.
*
* @param selector the selector
* @return the PostFindOptions builder
*/
public Builder selector(Map<String, Object> selector) {
this.selector = selector;
return this;
}
/**
* Set the bookmark.
*
* @param bookmark the bookmark
* @return the PostFindOptions builder
*/
public Builder bookmark(String bookmark) {
this.bookmark = bookmark;
return this;
}
/**
* Set the conflicts.
*
* @param conflicts the conflicts
* @return the PostFindOptions builder
*/
public Builder conflicts(Boolean conflicts) {
this.conflicts = conflicts;
return this;
}
/**
* Set the executionStats.
*
* @param executionStats the executionStats
* @return the PostFindOptions builder
*/
public Builder executionStats(Boolean executionStats) {
this.executionStats = executionStats;
return this;
}
/**
* Set the fields.
* Existing fields will be replaced.
*
* @param fields the fields
* @return the PostFindOptions builder
*/
public Builder fields(List<String> fields) {
this.fields = fields;
return this;
}
/**
* Set the limit.
*
* @param limit the limit
* @return the PostFindOptions builder
*/
public Builder limit(long limit) {
this.limit = limit;
return this;
}
/**
* Set the skip.
*
* @param skip the skip
* @return the PostFindOptions builder
*/
public Builder skip(long skip) {
this.skip = skip;
return this;
}
/**
* Set the sort.
* Existing sort will be replaced.
*
* @param sort the sort
* @return the PostFindOptions builder
*/
public Builder sort(List<Map<String, String>> sort) {
this.sort = sort;
return this;
}
/**
* Set the stable.
*
* @param stable the stable
* @return the PostFindOptions builder
*/
public Builder stable(Boolean stable) {
this.stable = stable;
return this;
}
/**
* Set the update.
*
* @param update the update
* @return the PostFindOptions builder
*/
public Builder update(String update) {
this.update = update;
return this;
}
/**
* Set the useIndex.
* Existing useIndex will be replaced.
*
* @param useIndex the useIndex
* @return the PostFindOptions builder
*/
public Builder useIndex(List<String> useIndex) {
this.useIndex = useIndex;
return this;
}
/**
* Set the r.
*
* @param r the r
* @return the PostFindOptions builder
*/
public Builder r(long r) {
this.r = r;
return this;
}
}
protected PostFindOptions(Builder builder) {
com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.db,
"db cannot be empty");
com.ibm.cloud.sdk.core.util.Validator.notNull(builder.selector,
"selector cannot be null");
db = builder.db;
selector = builder.selector;
bookmark = builder.bookmark;
conflicts = builder.conflicts;
executionStats = builder.executionStats;
fields = builder.fields;
limit = builder.limit;
skip = builder.skip;
sort = builder.sort;
stable = builder.stable;
update = builder.update;
useIndex = builder.useIndex;
r = builder.r;
}
/**
* New builder.
*
* @return a PostFindOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the db.
*
* Path parameter to specify the database name.
*
* @return the db
*/
public String db() {
return db;
}
/**
* Gets the selector.
*
* JSON object describing criteria used to select documents. The selector specifies fields in the document, and
* provides an expression to evaluate with the field content or other data.
*
* The selector object must:
* * Be structured as valid JSON.
* * Contain a valid query expression.
*
* Using a selector is significantly more efficient than using a JavaScript filter function, and is the recommended
* option if filtering on document attributes only.
*
* Elementary selector syntax requires you to specify one or more fields, and the corresponding values required for
* those fields. You can create more complex selector expressions by combining operators.
*
* Operators are identified by the use of a dollar sign `$` prefix in the name field.
*
* There are two core types of operators in the selector syntax:
* * Combination operators: applied at the topmost level of selection. They are used to combine selectors. In addition
* to the common boolean operators (`$and`, `$or`, `$not`, `$nor`) there are three combination operators: `$all`,
* `$elemMatch`, and `$allMatch`. A combination operator takes a single argument. The argument is either another
* selector, or an array of selectors.
* * Condition operators: are specific to a field, and are used to evaluate the value stored in that field. For
* instance, the basic `$eq` operator matches when the specified field contains a value that is equal to the supplied
* argument.
*
* @return the selector
*/
public Map<String, Object> selector() {
return selector;
}
/**
* Gets the bookmark.
*
* Opaque bookmark token used when paginating results.
*
* @return the bookmark
*/
public String bookmark() {
return bookmark;
}
/**
* Gets the conflicts.
*
* A boolean value that indicates whether or not to include information about existing conflicts in the document.
*
* @return the conflicts
*/
public Boolean conflicts() {
return conflicts;
}
/**
* Gets the executionStats.
*
* Use this option to find information about the query that was run. This information includes total key lookups,
* total document lookups (when `include_docs=true` is used), and total quorum document lookups (when each document
* replica is fetched).
*
* @return the executionStats
*/
public Boolean executionStats() {
return executionStats;
}
/**
* Gets the fields.
*
* JSON array that uses the field syntax. Use this parameter to specify which fields of a document must be returned.
* If it is omitted, the entire document is returned.
*
* @return the fields
*/
public List<String> fields() {
return fields;
}
/**
* Gets the limit.
*
* Maximum number of results returned. The `type: text` indexes are limited to 200 results when queried.
*
* @return the limit
*/
public Long limit() {
return limit;
}
/**
* Gets the skip.
*
* Skip the first 'n' results, where 'n' is the value that is specified.
*
* @return the skip
*/
public Long skip() {
return skip;
}
/**
* Gets the sort.
*
* JSON array of sort syntax elements to determine the sort order of the results.
*
* @return the sort
*/
public List<Map<String, String>> sort() {
return sort;
}
/**
* Gets the stable.
*
* Whether or not the view results should be returned from a "stable" set of shards.
*
* @return the stable
*/
public Boolean stable() {
return stable;
}
/**
* Gets the update.
*
* Whether to update the index prior to returning the result.
*
* @return the update
*/
public String update() {
return update;
}
/**
* Gets the useIndex.
*
* Use this option to identify a specific index for query to run against, rather than by using the IBM Cloudant Query
* algorithm to find the best index.
*
* @return the useIndex
*/
public List<String> useIndex() {
return useIndex;
}
/**
* Gets the r.
*
* The read quorum that is needed for the result. The value defaults to 1, in which case the document that was found
* in the index is returned. If set to a higher value, each document is read from at least that many replicas before
* it is returned in the results. The request will take more time than using only the document that is stored locally
* with the index.
*
* @return the r
*/
public Long r() {
return r;
}
}
|
package com.bon.wx.domain.vo;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* @program: 后台
*
* @description: 菜单视图类
*
* @author: Bon
*
* @create: 2018-06-03 17:24
**/
public class MenuVO implements Serializable{
@ApiModelProperty(value = "ID")
private Long menuId;
@ApiModelProperty(value = "菜单名称")
private String name;
@ApiModelProperty(value = "菜单地址")
private String path;
@ApiModelProperty(value = "视图文件路径")
private String component;
@ApiModelProperty(value = "跳转地址(如果设置为noredirect会在面包屑导航中无连接)")
private String redirect;
@ApiModelProperty(value = "菜单显示名称")
private String title;
@ApiModelProperty(value = "菜单图标")
private String icon;
@ApiModelProperty(value = "00:true,01:false如果设置true,会在导航中隐藏")
private String hidden;
@ApiModelProperty(value = "00:true,01:false没有子菜单也会显示在导航中")
private String alwaysShow;
@ApiModelProperty(value = "数据库id地址")
private String dataPath;
@ApiModelProperty(value = "父菜单id")
private Long parent;
@ApiModelProperty(value = "父菜单name")
private String parentName;
public MenuVO(){}
public MenuVO(Long menuId, String name, String path, String component, String redirect, String title, String icon, String hidden, String alwaysShow, String dataPath, Long parent, String parentName) {
this.menuId = menuId;
this.name = name;
this.path = path;
this.component = component;
this.redirect = redirect;
this.title = title;
this.icon = icon;
this.hidden = hidden;
this.alwaysShow = alwaysShow;
this.dataPath = dataPath;
this.parent = parent;
this.parentName = parentName;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getRedirect() {
return redirect;
}
public void setRedirect(String redirect) {
this.redirect = redirect;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getHidden() {
return hidden;
}
public void setHidden(String hidden) {
this.hidden = hidden;
}
public String getAlwaysShow() {
return alwaysShow;
}
public void setAlwaysShow(String alwaysShow) {
this.alwaysShow = alwaysShow;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getDataPath() {
return dataPath;
}
public void setDataPath(String dataPath) {
this.dataPath = dataPath;
}
}
|
package ru.mcfr.oxygen.framework.extensions;
import ro.sync.ecss.extensions.api.AuthorAccess;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ro.sync.ecss.extensions.api.structure.AuthorOutlineCustomizer;
import ro.sync.ecss.extensions.api.structure.RenderingInformation;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
/**
* Simple Document Framework Author Outline customizer used for custom filtering and nodes rendering
* in the Outline.
*/
public class MOFAuthorOutlineCustomizer extends AuthorOutlineCustomizer {
/**
* Ignore 'b' nodes.
*/
public boolean ignoreNode(AuthorNode node) {
if (node.getName().equals("b")) {
return true;
}
// Default behavior
return false;
}
/**
* For every node render its name in the Outline (with the first letter capitalized).
* Set 'Paragraph' as render for 'para' nodes
* Render the title text for 'section' nodes and add 'Section' as additional info and tooltip.
*/
public void customizeRenderingInformation(
RenderingInformation renderInfo) {
// Get the node to be rendered
AuthorNode node = renderInfo.getNode();
String name = node.getName();
if (name.length() > 0) {
if ("para".equals(name)) {
name = "Paragraph";
} else {
// Capitalize the first letter
name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
}
}
// Render additional attribute value
String additionalAttrValue = renderInfo.getAdditionalRenderedAttributeValue();
if (additionalAttrValue != null && additionalAttrValue.length() > 0) {
renderInfo.setAdditionalRenderedAttributeValue("[" + additionalAttrValue + "]");
}
// Set the render text
renderInfo.setRenderedText("[" + name + "]");
// Render the title text in the 'section' additional info.
if (node.getName().equals("section")) {
if (node instanceof AuthorElement) {
// Get the 'section' content nodes
List<AuthorNode> contentNodes = ((AuthorElement) node).getContentNodes();
if (contentNodes.size() > 0) {
AuthorNode authorNode = contentNodes.get(0);
if ("title".equals(authorNode.getName())) {
try {
// Render the title
String textContent = authorNode.getTextContent();
if (textContent != null && textContent.trim().length() > 0) {
if (textContent.length() > 20) {
textContent = textContent.substring(0, 20);
}
renderInfo.setRenderedText(textContent);
// Set 'Section' as additional info
renderInfo.setAdditionalRenderedText("[Section]");
// Set the tooltip text
renderInfo.setTooltipText(textContent);
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* Customize the popUp menu.
* If the selected node is a 'title' from 'section' remove the 'Delete'
* action from the popUp menu and add the 'Remove content' action if the selection
* is single.
*/
public void customizePopUpMenu(Object popUp, final AuthorAccess authorAccess) {
if (authorAccess != null) {
if (popUp instanceof JPopupMenu) {
JPopupMenu popupMenu = (JPopupMenu) popUp;
// Find the selected paths from the Outliner
TreePath[] selectedPaths = authorAccess.getOutlineAccess().getSelectedPaths(true);
for (TreePath treePath : selectedPaths) {
Object[] authorNodesPath = treePath.getPath();
if (authorNodesPath.length > 0) {
// Find the selected node (last node from the list of path nodes)
final AuthorNode selectedAuthorNode = (AuthorNode) authorNodesPath[authorNodesPath.length - 1];
// Find if the current selected node is a title from section
if ("title".equals(selectedAuthorNode.getName()) &&
"section".equals(selectedAuthorNode.getParent().getName())) {
// Find the popUp item corresponding to the 'Delete' action
Component[] components = popupMenu.getComponents();
int deleteItemIndex = 0;
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JMenuItem) {
String itemText = ((JMenuItem) components[i]).getText();
if ("Delete".equals(itemText)) {
// The 'Remove Content' item will be added at the same index
deleteItemIndex = i;
// Remove the 'Delete' action
popupMenu.remove(deleteItemIndex);
}
}
}
if (selectedPaths.length == 1) {
// Add the 'Remove content' action
JMenuItem sdfMenuItem = new JMenuItem("Remove Content");
sdfMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Remove title content
int startOffset = selectedAuthorNode.getStartOffset();
int endOffset = selectedAuthorNode.getEndOffset();
if (endOffset > startOffset + 1) {
authorAccess.getDocumentController().delete(
startOffset + 1,
endOffset);
}
}
});
// Add the menu item in the menu
popupMenu.add(sdfMenuItem, deleteItemIndex);
}
break;
}
}
}
}
}
}
}
|
package revolt.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import revolt.backend.entity.RTA;
@Repository
public interface RTARepository extends JpaRepository<RTA, Long> {
// List<RTA> findAllByActive(Boolean b);
}
|
package checkPt1.Model;
import java.awt.Color;
import java.awt.Graphics;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JComponent;
public class Goal extends Coordinate implements Drawable {
ArrayList<CoreObject> occupiedList;
boolean trueGoal;
Robot robot;
public boolean yetToReach;
Catcher catcher;
float catcherConfidenceThreshold;
float catcherDistanceThreshold;
PrintWriter writer;
public Goal(float x, float y, boolean trueGoal, Robot robot, float catcherConfidenceThreshold, float catcherDistanceThreshold,PrintWriter writer) {
super(x, y);
occupiedList = new ArrayList<CoreObject>();
this.trueGoal = trueGoal;
this.robot = robot;
yetToReach = true;
this.catcher = null;
this.catcherConfidenceThreshold = catcherConfidenceThreshold;
this.catcherDistanceThreshold = catcherDistanceThreshold;
this.writer = writer;
// TODO Auto-generated constructor stub
}
public boolean contains(Coordinate co){
return (co.getX() == getX() && co.getY() == getY());
}
public void setCatcher(Catcher catcher){
this.catcher = catcher;
}
@Override
public void update(JComponent comp) {
if(trueGoal && contains(catcher) && yetToReach){
writer.println(catcherConfidenceThreshold +", "+catcherDistanceThreshold+", "+"CATCHER");
System.out.println(catcherConfidenceThreshold +", "+catcherDistanceThreshold+", "+"CATCHER");
yetToReach = false;
}
if(trueGoal && contains(robot) && yetToReach){
writer.println(catcherConfidenceThreshold +", "+catcherDistanceThreshold+", "+"ROBOT");
System.out.println(catcherConfidenceThreshold +", "+catcherDistanceThreshold+", "+"ROBOT");
yetToReach = false;
}
}
@Override
public void draw(Graphics g) {
if(trueGoal){
g.setColor(Color.GREEN);
} else {
g.setColor(Color.YELLOW);
}
super.draw(g);
}
}
|
package com.lucasirc.servercatalog.service;
import java.util.Map;
public interface ResourceTransformer<T> {
public T contentToEntity(String content);
public T contentToEntity(long id,String content);
public Map entityToMap(T entity);
}
|
package FlowProccessor.config;
public class ProcessorConfig {
private boolean debugMode;
public boolean isDebugMode() {
return debugMode;
}
private void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
public static class ProcessorConfigBuilder {
private boolean debugMode;
public ProcessorConfigBuilder() {}
public ProcessorConfig build() {
ProcessorConfig config = new ProcessorConfig();
config.setDebugMode(
debugMode
);
return config;
}
public ProcessorConfigBuilder debugMode(boolean debugMode) {
this.debugMode = debugMode;
return this;
}
}
}
|
public class week3qsn3
{
public static void main(String[]args)
{
int n=13;
if(n%3==0)
if(n%5==0){
System.out.println("it is divisible by both 3and 5");
}
else
{
System.out.println("it is divisible by 3 but not 5");
}
else
{
System.out.println("it is not divisible");
}
}
}
|
/*
* This file is a part of VideoLibrary Interface
* Copyright © Vyacheslav Krylov (slavone@protonmail.ch) 2021
*
* 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 me.vkryl.videolib;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
/**
* VideoLibrary Interface
*
* All methods must be thread-safe.
*
* Most of the methods return data asynchronously.
* Library implementation is free to invoke {@link Callback}'s methods on any thread.
*/
public interface VideoLibrary {
/**
* @return Library name
*/
String getName ();
/**
* @return Library version
*/
String getVersion ();
/**
* Provides information about supported formats asynchronously.
*
* @param context Context
* @param callback callback to invoke
*/
void getSupportedFormats (Context context, Callback<AvailableFormats, VideoLibraryError> callback);
/**
* Provides an information about the input video, and supported features.
*
* @param context Context
* @param uri Input video path, file:// or content://
* @param prepareTrimmingCache True, if library should generate {@link InputVideoInformation#trimCache} that will be passed by the client to {@link #correctTrimSegment(Context, Uri, TimeSegmentsCache, TimeSegment, boolean, Callback)} once it's no longer needed.
* False, if library should not generate such cache.
* @param callback Callback to invoke
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long getVideoInformation (Context context, Uri uri, boolean prepareTrimmingCache, Callback<InputVideoInformation, VideoLibraryError> callback);
/**
* Corrects trim start/end timestamp to the actual one that will be used in the output video.
*
* This might be useful if only keyframe-accurate video trimming is supported,
* or could be slightly changed for optimization purposes.
*
* This provides user an ability to ensure that no extra frames will be included in the final video,
* and no essential frames will be dropped.
*
* @param context Context
* @param uri Input video path, file:// or content://.
* @param timeSegmentsCache Library cache relevant to this video generated in {@link #getVideoInformation(Context, Uri, boolean, Callback)}
* @param segment Trim values generated by the user interface
* @param correctEnd True, if user has changed the {@link TimeSegment#endTimeUs}, which should be corrected.
* False, if user has changed the {@link TimeSegment#startTimeUs}, which should be corrected.
* When one value is changed, the other one should be kept as-is.
* @param callback Callback to invoke once frame-accurate timestamps will
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long correctTrimSegment (Context context, Uri uri, TimeSegmentsCache timeSegmentsCache, TimeSegment segment, boolean correctEnd, Callback<TimeSegment, VideoLibraryError> callback);
/**
* Creates a static image with output video preview without a need in waiting the video to be generated.
*
* This method shouldn't rely on the precise match of the output video quality, but
* shouldn't miss any essential parameters that affect the content.
*
* @param context Context
* @param uri Input video path, file:// or content://.
* @param maxSize Maximum size of the biggest side of the output image
* @param configuration Conversion configuration
* @param callback Callback to invoke
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long generateThumbnail (Context context, Uri uri, int maxSize, OutputVideoConfiguration configuration, OverlayProvider overlayProvider, Callback<Bitmap, VideoLibraryError> callback);
/**
* Provides an estimated video output size for the given configuration.
*
* @param context Context
* @param uri Input video path, file:// or content://.
* @param configuration Conversion configuration
* @param callback Callback to invoke
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long estimateOutputVideoSize (Context context, Uri uri, OutputVideoConfiguration configuration, Callback<EstimatedOutputSize, VideoLibraryError> callback);
/**
* Converts the input video or .GIF image based on the provided configuration.
*
* @param context Context
* @param inputVideoPath Path to the input video or .GIF image. file:// or content://
* @param configuration Conversion configuration
* @param overlayProvider Overlay provider
* @param destinationPath Destination video path.
* @param callback Callback to invoke during the conversion process.
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long convertVideo (Context context, Uri inputVideoPath, OutputVideoConfiguration configuration, OverlayProvider overlayProvider, String destinationPath, ConversionCallback callback);
/**
* Generates the video from the still image.
*
* @param context Context
* @param inputImagePath Path to the image on which the video should be based. file:// or content://
* @param durationUs Output duration in microseconds
* @param configuration Output video configuration.
* @param overlayProvider Overlay provider
* @param destinationPath Destination video path
* @param callback Callback to invoke during the generation process.
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long generateVideoFromImage (Context context, Uri inputImagePath, double durationUs, OutputVideoConfiguration configuration, OverlayProvider overlayProvider, String destinationPath, ConversionCallback callback);
/**
* Generates the video file from animated .GIF image
*
* @param context Context
* @param inputGifPath Path to the image on which the video should be based. file:// or content://
* @param configuration Output video configuration.
* @param overlayProvider Overlay provider
* @param destinationPath Destination video path
* @param callback Callback to invoke during the generation process.
*
* @return Task identifier that could be cancelled via {@link #cancel(long)}
*/
long generateVideoFromGif (Context context, Uri inputGifPath, OutputVideoConfiguration configuration, OverlayProvider overlayProvider, String destinationPath, ConversionCallback callback);
/**
* Cancels the task by its identifier.
*
* @param taskId task identifier obtained through other methods.
*/
void cancel (long taskId);
}
|
package xtrus.nhvan.mgr.nhmca.vo;
public class NhMcaInfo {
// primary key
private String interfaceId;
// fields
private String useInbound;
private String inboundIfId;
private String inboundUseEvent;
private String useOutbound;
private String outboundServerIp;
private int outboundServerPort;
private int outboundConnTimeout; // 단위: 밀리초
private int outboundMaxRetryCnt;
private int outboundCheckInterval; // 단위: 밀리초
private String parsingRule;
private String regDate; // "yyyyMMddHHmmss"
private String modDate; // "yyyyMMddHHmmss"
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getUseInbound() {
return useInbound;
}
public void setUseInbound(String useInbound) {
this.useInbound = useInbound;
}
public String getInboundIfId() {
return inboundIfId;
}
public void setInboundIfId(String inboundIfId) {
this.inboundIfId = inboundIfId;
}
public String getInboundUseEvent() {
return inboundUseEvent;
}
public void setInboundUseEvent(String inboundUseEvent) {
this.inboundUseEvent = inboundUseEvent;
}
public String getUseOutbound() {
return useOutbound;
}
public void setUseOutbound(String useOutbound) {
this.useOutbound = useOutbound;
}
public String getOutboundServerIp() {
return outboundServerIp;
}
public void setOutboundServerIp(String outboundServerIp) {
this.outboundServerIp = outboundServerIp;
}
public int getOutboundServerPort() {
return outboundServerPort;
}
public void setOutboundServerPort(int outboundServerPort) {
this.outboundServerPort = outboundServerPort;
}
public int getOutboundConnTimeout() {
return outboundConnTimeout;
}
public void setOutboundConnTimeout(int outboundConnTimeout) {
this.outboundConnTimeout = outboundConnTimeout;
}
public int getOutboundMaxRetryCnt() {
return outboundMaxRetryCnt;
}
public void setOutboundMaxRetryCnt(int outboundMaxRetryCnt) {
this.outboundMaxRetryCnt = outboundMaxRetryCnt;
}
public int getOutboundCheckInterval() {
return outboundCheckInterval;
}
public void setOutboundCheckInterval(int outboundCheckInterval) {
this.outboundCheckInterval = outboundCheckInterval;
}
public String getParsingRule() {
return parsingRule;
}
public void setParsingRule(String parsingRule) {
this.parsingRule = parsingRule;
}
public String getRegDate() {
return regDate;
}
public void setRegDate(String regDate) {
this.regDate = regDate;
}
public String getModDate() {
return modDate;
}
public void setModDate(String modDate) {
this.modDate = modDate;
}
}
|
package sheep.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
@Entity
public class Member {
@Id
@GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name ="USERNMAE")
private String username;
@Embedded
private Period workPeriod;
@Embedded
private Address homeAddress;
@ElementCollection //컬랙션들은 일대다로 풀어서 별도의 테이블로 만들어야한다.
@CollectionTable(name="FAVORITE_FOOD" //이게 테이블명
,joinColumns = @JoinColumn(name = "MEMBER_ID")) //이게 외래키
@Column(name = "FOOD_NAME") //이게 속성명
private Set<String> favoriteFoods = new HashSet<>();
// create table FAVORITE_FOOD (
// MEMBER_ID bigint not null,
// FOOD_NAME varchar(255)
// )
//이렇게 값 타입으로 매핑하지말고,
// @ElementCollection(fetch = FetchType.LAZY)// 여기 기본값은 지연로딩이다.
// @CollectionTable(name="ADDRESS",joinColumns =
// @JoinColumn(name = "MEMBER_ID"))// MEMBER_ID를 외래키로 잡는다.// 테이블명은 ADDRESS이다.
// private List<Address> adressHistory = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)
@JoinColumn(name ="MEMBER_ID")
private List<AddressEntity> addressHistory = new ArrayList<>();
// create table ADDRESS (
// MEMBER_ID bigint not null,
// city varchar(255),
// street varchar(255),
// zipcode varchar(255)
// )
//위에 Address로 homeAddress가 있는데 여기 workAddress가 또 있다면.. @AttributeOverride(속성 재정의)를 하자.
@Embedded
@AttributeOverrides({
@AttributeOverride(name="city",column = @Column(name= "WORK_CITY")),
@AttributeOverride(name="street",column = @Column(name= "WORK_STREET")),
@AttributeOverride(name="zipcode",column = @Column(name= "WORK_ZIPCODE"))
})
private Address workAddress;
// create table Member (
// MEMBER_ID bigint not null,
// city varchar(255),
// street varchar(255),
// zipcode varchar(255),
// USERNMAE varchar(255),
// WORK_CITY varchar(255),
// WORK_STREET varchar(255),
// WORK_ZIPCODE varchar(255),
// endDate timestamp,
// startDate timestamp,
// primary key (MEMBER_ID)
// )
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Period getWorkPeriod() {
return workPeriod;
}
public void setWorkPeriod(Period workPeriod) {
this.workPeriod = workPeriod;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public Set<String> getFavoriteFoods() {
return favoriteFoods;
}
public void setFavoriteFoods(Set<String> favoriteFoods) {
this.favoriteFoods = favoriteFoods;
}
public Address getWorkAddress() {
return workAddress;
}
public void setWorkAddress(Address workAddress) {
this.workAddress = workAddress;
}
public List<AddressEntity> getAddressHistory() {
return addressHistory;
}
public void setAddressHistory(List<AddressEntity> addressHistory) {
this.addressHistory = addressHistory;
}
}
//@Entity
//public class Member extends BaseEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "MEMBER_ID")//
// private Long id;
//
// private String name;
//
// @ManyToOne(fetch = FetchType.EAGER)
// @JoinColumn(name="TEAM_ID")
// private Team team;
//
// public Team getTeam() {
// return team;
// }
//
// public void setTeam(Team team) {
// this.team = team;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//}
|
package net.tanpeng.arithmetic.arithmetic4.reference;
import java.util.ArrayList;
import java.util.List;
public class SortedBinaryTree<E> {
private Node<E> root; // 根节点
private int size; // 二叉树元素个数
/**
* 二叉树节点
*/
private static class Node<E> {
E element; // 节点元素
Node<E> lChild; // 左孩子
Node<E> rChild; // 右孩子
public Node(E element) {
this(element, null, null);
}
public Node(E element, Node<E> lChild, Node<E> rChild) {
this.element = element;
this.lChild = lChild;
this.rChild = rChild;
}
}
public SortedBinaryTree(List<E> elements) {
for (E e : elements) {
add(e);
}
}
public SortedBinaryTree(E[] elements) {
for (E e : elements) {
add(e);
}
}
public SortedBinaryTree() {
}
/**
* 判断当前元素是否存在于树中
*
* @param element
* @return
*/
public boolean contains(E element) {
return search(root, element);
}
/**
* 递归搜索,查找当前以curRoot为根节点的树中element存在与否
*
* @param curRoot
* @param element
* @return
*/
@SuppressWarnings("unchecked")
private boolean search(Node<E> curRoot, E element) {
if (curRoot == null)
return false;
Comparable<? super E> e = (Comparable<? super E>) element;
int cmp = e.compareTo(curRoot.element);
if (cmp > 0) {
// 查找的元素大于当前根节点对应的元素,向右走
return search(curRoot.rChild, element);
} else if (cmp < 0) {
// 查找的元素小于当前根节点对应的元素,向左走
return search(curRoot.lChild, element);
} else {
// 查找的元素等于当前根节点对应的元素,返回true
return true;
}
}
/**
* 非递归搜索,查找当前以curRoot为根节点的树中的element是否存在
*
* @param curRoot 二叉排序树的根节点
* @param element 被搜索的元素
* @param target target[0]指向查找路径上最后一个节点: 如果当前查找的元素存在,则target[0]指向该节点
* @return
*/
@SuppressWarnings("unchecked")
private boolean find(Node<E> curRoot, E element, Node<E>[] target) {
if (curRoot == null)
return false;
Node<E> tmp = curRoot;
Comparable<? super E> e = (Comparable<? super E>) element;
while (tmp != null) {
int cmp = e.compareTo(tmp.element);
target[0] = tmp;
if (cmp > 0) {
// 查找的元素大于当前节点对应的元素,向右走
tmp = tmp.rChild;
} else if (cmp < 0) {
// 查找的元素小于当前节点对应的元素,向左走
tmp = tmp.lChild;
} else {
// 查找的元素等于当前根节点对应的元素,返回true
return true;
}
}
return false;
}
/**
* 向二叉排序树中添加元素,如果当前元素已经存在,则添加失败,返回false,如果当前元素不存在,则添加成功,返回true
*/
@SuppressWarnings("unchecked")
public boolean add(E element) {
if (root == null) {
root = new Node<E>(element);
size++;
return true;
}
Node<E>[] target = new Node[1];
if (!find(root, element, target)) {
// 当前元素不存在,插入元素
// 此时target节点即为需要插入的节点的父节点
Comparable<? super E> e = (Comparable<? super E>) element;
int cmp = e.compareTo(target[0].element);
Node<E> newNode = new Node<E>(element);
if (cmp > 0) {
// 插入的元素大于target指向的节点元素
target[0].rChild = newNode;
} else {
// 插入的元素小于target指向的节点元素
target[0].lChild = newNode;
}
size++;
return true;
}
return false;
}
/**
* 删除二叉排序树中的元素,如果当前元素不存在,则删除失败,返回false;如果当前元素存在,则删除该元素,重构二叉树,返回true
*
* @param element
* @return
*/
@SuppressWarnings("unchecked")
public boolean remove(E element) {
Node<E>[] target = new Node[1];
if (find(root, element, target)) {
// 被删除的元素存在,则继续执行删除操作
remove(target[0]);
return true;
}
return false;
}
/**
* 释放当前节点
*
* @param node
*/
private void free(Node<E> node) {
node.element = null;
node.lChild = null;
node.rChild = null;
node = null;
}
/**
* 删除二叉排序树中指定的节点
*
* @param node
*/
private void remove(Node<E> node) {
Node<E> tmp;
if (node.lChild == null && node.rChild == null) {
// 当前node为叶子节点,删除当前节点,则node = null;
node = null;
} else if (node.lChild == null && node.rChild != null) {
// 如果被删除的节点左子树为空,则只需要重新连接其右子树
tmp = node;
node = node.rChild;
free(tmp);
} else if (node.lChild != null && node.rChild == null) {
// 如果被删除的节点右子树为空,则只需要重新连接其左子树
tmp = node;
node = node.lChild;
free(tmp);
} else {
// 当前被删除的节点左右子树均存在,不为空
// 找到离当前node节点对应元素且最近的节点target(左子树的最右边节点 或者 右子树最左边节点)
// 将node节点元素替换成target节点的元素,将target节点删除
tmp = node; // tmp是target的父节点
Node<E> target = node.lChild; // 找到左子树最大子树
while (target.rChild != null) { // 在左子树中进行右拐
tmp = target;
target = target.rChild;
}
node.element = target.element; // node.element元素替换为target.element
if (tmp == node) {
// tmp == node 说明没有在左子树中进行右拐,也就是node节点的左孩子没有右孩子,
// 需要重新连接tmp节点左孩子
tmp.lChild = target.lChild;
} else {
// tmp != node, 进行了右拐,那么将重新连接tmp的右子树,将target.lChild赋值给tmp.rChild
tmp.rChild = target.lChild;
}
// 释放节点
free(target);
}
// 删除成功,size--;
size--;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public List<E> preOrderTraverse() {
List<E> list = new ArrayList<E>();
preOrderTraverse(root, list);
return list;
}
private void preOrderTraverse(Node<E> curRoot, List<E> list) {
if (curRoot == null)
return;
E e = curRoot.element;
list.add(e);
preOrderTraverse(curRoot.lChild, list);
preOrderTraverse(curRoot.rChild, list);
}
public List<E> inOrderTraverse() {
List<E> list = new ArrayList<E>();
inOrderTraverse(root, list);
return list;
}
private void inOrderTraverse(Node<E> curRoot, List<E> list) {
if (curRoot == null)
return;
inOrderTraverse(curRoot.lChild, list);
list.add(curRoot.element);
inOrderTraverse(curRoot.rChild, list);
}
public List<E> postOrderTraverse() {
List<E> list = new ArrayList<E>();
postOrderTraverse(root, list);
return list;
}
private void postOrderTraverse(Node<E> curRoot, List<E> list) {
if (curRoot == null)
return;
inOrderTraverse(curRoot.lChild, list);
inOrderTraverse(curRoot.rChild, list);
list.add(curRoot.element);
}
/**
* 返回中序遍历结果
*/
@Override
public String toString() {
return inOrderTraverse().toString();
}
public static void main(String[] args) {
Integer[] elements = new Integer[]{62, 88, 58, 47, 73, 99, 35, 51, 93, 29, 37, 49, 56, 36, 48, 50};
SortedBinaryTree<Integer> tree = new SortedBinaryTree<Integer>(elements);
System.out.println(tree);
System.out.println(tree.contains(93));
System.out.println(tree.size());
System.out.println(tree.remove(47));
System.out.println(tree.preOrderTraverse());
System.out.println(tree.size());
}
}
|
package com.blog.utils;
/**
* 系统常量接口
*/
public interface SystemConstants {
String SUCCESS = "success";
/**
* 评论状态 1-未审核 2-已审核
*/
int COMMENT_STATE_OK = 2;
int COMMENT_STATE_NO = 1;
}
|
package edu.athens.cs.gradegeneratortest;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class GradeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade);
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new StudentMasterFragment();
fm.beginTransaction()
.add(R.id.fragment_container,fragment)
.commit();
}
}
}
|
package com.cs.promotion;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.EnumSet;
import java.util.Set;
/**
* @author Hadi Movaghar
*/
public class PromotionTriggerType implements UserType {
private final Logger logger = LoggerFactory.getLogger(PromotionTriggerType.class);
@Override
public int[] sqlTypes() {
return new int[]{Types.VARCHAR};
}
@Override
public Class returnedClass() {
return Set.class;
}
@Override
public boolean equals(final Object x, final Object y)
throws HibernateException {
if (!(x instanceof Set && y instanceof Set)) {
return false;
}
final Set xSet = (Set) x;
final Set ySet = (Set) y;
return xSet.equals(ySet);
}
@Override
public int hashCode(final Object x)
throws HibernateException {
return x.hashCode();
}
@Nullable
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor session, final Object owner)
throws HibernateException, SQLException {
final String dbData = rs.getString(names[0]);
if (Strings.isNullOrEmpty(dbData)) {
return EnumSet.noneOf(PromotionTrigger.class);
}
final Iterable<String> strings = Splitter.on(";").split(dbData);
final EnumSet<PromotionTrigger> triggers = EnumSet.noneOf(PromotionTrigger.class);
for (final String trigger : strings) {
try {
triggers.add(PromotionTrigger.valueOf(trigger));
} catch (final IllegalArgumentException | NullPointerException e) {
logger.error("PromotionTrigger {} cannot be mapped to any of the PromotionTrigger values [{}]", trigger, PromotionTrigger.values());
}
}
return triggers;
}
@Override
public void nullSafeSet(final PreparedStatement st, final Object value, final int index, final SessionImplementor session)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
return;
}
@SuppressWarnings("unchecked") final Set<PromotionTrigger> triggers = (Set<PromotionTrigger>) value;
final String joined = Joiner.on(";").join(triggers);
st.setString(index, joined);
}
@Nullable
@Override
public Object deepCopy(final Object value)
throws HibernateException {
if (value == null) {
return null;
}
@SuppressWarnings("unchecked") final Set<PromotionTrigger> triggers = (Set<PromotionTrigger>) value;
return EnumSet.copyOf(triggers);
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(final Object value)
throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(final Serializable cached, final Object owner)
throws HibernateException {
return cached;
}
@Override
public Object replace(final Object original, final Object target, final Object owner)
throws HibernateException {
return original;
}
}
|
package com.teaboot.context.entity;
import java.util.Map;
import java.util.Set;
import com.teaboot.context.beans.BeansType;
public class EntityType{
public EntityType() {
}
String classMap;
Map<String,MethodType> fieldMap;
Object obj;
BeansType beansType;
public String getClassMap() {
return classMap;
}
public void setClassMap(String classMap) {
this.classMap = classMap;
}
public Map<String, MethodType> getFieldMap() {
return fieldMap;
}
public void setFieldMap(Map<String, MethodType> fieldMap) {
this.fieldMap = fieldMap;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public BeansType getBeansType() {
return beansType;
}
public void setBeansType(BeansType beansType) {
this.beansType = beansType;
}
public String hashName(String path, String className){
Set<String> sets = fieldMap.keySet();
String matchPath = path.replaceFirst(className, "");
System.out.println(matchPath);
if(sets.contains(matchPath)){
return matchPath;
}
return null;
}
public MethodType getInitMethod(){
for(String key : fieldMap.keySet()){
MethodType mehod = fieldMap.get(key);
if(mehod.beansType == BeansType.INIT)return fieldMap.get(key);
}
return null;
}
@Override
public String toString() {
return "EntityType [classMap=" + classMap + ", fieldMap=" + fieldMap + ", obj=" + obj + ", beansType="
+ beansType + "]";
}
}
|
package com.davivienda.sara.entitys;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Zona
* Descripción : Zonas de ubicación
* Fecha : 18/02/2008 05:52:16 PM
* @author : jjvargas
**/
@Entity
@Table(name = "ZONA")
@NamedQueries( {
@NamedQuery(
name = "Zona.RegistroUnico",
query = "select object(o) from Zona o where o.idZona = :idZona"),
@NamedQuery(
name = "Zona.todos", query = "select object(o) from Zona o order by o.idZona")
})
public class Zona implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID_ZONA", nullable = false)
private Integer idZona;
@Column(name = "ZONA", nullable = false)
private String zona;
@Column(name = "DESCRIPCION_ZONA", nullable = false)
private String descripcionZona;
public Zona() {
}
public Zona(Integer idZona) {
this.idZona = idZona;
}
public Zona(Integer idZona, String zona, String descripcionZona) {
this.idZona = idZona;
this.zona = zona;
this.descripcionZona = descripcionZona;
}
public Integer getIdZona() {
return idZona;
}
public void setIdZona(Integer idZona) {
this.idZona = idZona;
}
public String getZona() {
return zona;
}
public void setZona(String zona) {
this.zona = zona;
}
public String getDescripcionZona() {
return descripcionZona;
}
public void setDescripcionZona(String descripcionZona) {
this.descripcionZona = descripcionZona;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idZona != null ? idZona.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Zona)) {
return false;
}
Zona other = (Zona) object;
if ((this.idZona == null && other.idZona != null) || (this.idZona != null && !this.idZona.equals(other.idZona))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.davivienda.sara.entitys.Zona[idZona=" + idZona + "]";
}
public Zona actualizarEntity(Zona obj){
setDescripcionZona(obj.descripcionZona);
setIdZona(obj.idZona);
setZona(obj.zona);
return this;
}
}
|
/*
* 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 gui;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Ilham
*/
public class HomePanel extends JPanel {
private JLabel welcomeLabel;
public HomePanel() {
setLayout(new BorderLayout());
welcomeLabel = new JLabel("WELCOME TO THE APP");
add(welcomeLabel, BorderLayout.CENTER);
}
}
|
package com.unionfind_data;
import java.util.Random;
public class Test {
@org.junit.Test
public void test1() {
int size =10000000;
int m = 10000000;
/*UnionFind_1 u1 = new UnionFind_1(size);
double time1 = testUF(u1, m);
System.out.println("UnionFind_1: " +time1+" s");
UnionFind_2 u2 = new UnionFind_2(size);
double time2 = testUF(u2, m);
System.out.println("UnionFind_2: " +time2+" s");*/
UnionFind_3 u3 = new UnionFind_3(size);
double time3 = testUF(u3, m);
System.out.println("UnionFind_3: " +time3+" s");
UnionFind_4 u4 = new UnionFind_4(size);
double time4 = testUF(u4, m);
System.out.println("UnionFind_4: " +time4+" s");
UnionFind_5 u5 = new UnionFind_5(size);
double time5 = testUF(u5, m);
System.out.println("UnionFind_5: " +time5+" s");
UnionFind_6 u6 = new UnionFind_6(size);
double time6 = testUF(u6, m);
System.out.println("UnionFind_6: " +time6+" s");
}
public double testUF(UnionFind uf , int m) {
long start = System.nanoTime();
Random r = new Random();
for(int i=0;i<m;i++){
int a = r.nextInt(uf.size());
int b = r.nextInt(uf.size());
uf.unionElements(a, b);
}
for(int i=0;i<m;i++){
int a = r.nextInt(uf.size());
int b = r.nextInt(uf.size());
uf.isConnected(a, b);
}
long end = System.nanoTime();
return (end-start) / 1000000000.0;
}
}
|
package com.web.minimalistsremotecontrol;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
LinearLayout llvert;
int _id = 1;
java.net.Socket _s;
int _AddressId = 0;
int _PortId = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
llvert = new LinearLayout(this);
llvert.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
llvert.setId(_id++);
llvert.setBackgroundColor(Color.BLACK);
MakeConnectPanel();
this.setContentView(llvert);
}
private void MakeConnection(String ip, String port){
java.net.InetSocketAddress address = new java.net.InetSocketAddress(ip, Integer.parseInt(port));
try{
_s = new java.net.Socket();
_s.connect(address,3000);
}catch(Exception ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void MakeConnectPanel(){
llvert.removeAllViews();
EditText etPort = new EditText(this);
EditText etAddress = new EditText(this);
Button bConnect = new Button(this);
RelativeLayout rl = new RelativeLayout(this);
rl.setId(_id++);
rl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
etAddress.setWidth(150);
etAddress.setHint("Ip Address");
etAddress.setInputType(InputType.TYPE_CLASS_TEXT);
etAddress.setId(_id++);
_AddressId = etAddress.getId();
rl.addView(etAddress);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.RIGHT_OF, (_id-1));
etPort.setWidth(80);
etPort.setHint("Port");
etPort.setInputType(InputType.TYPE_CLASS_NUMBER);
etPort.setId(_id++);
_PortId = etPort.getId();
rl.addView(etPort,lp);
lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, (_id-2));
bConnect.setId(_id++);
bConnect.setText("Connect");
rl.addView(bConnect,lp);
bConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(((EditText)((View)v.getParent()).findViewById(_AddressId)).getText().toString().equals("") || ((EditText)((View)v.getParent()).findViewById(_PortId)).getText().toString().equals("")) return;
MakeConnection(((EditText)((View)v.getParent()).findViewById(_AddressId)).getText().toString(),((EditText)((View)v.getParent()).findViewById(_PortId)).getText().toString());
llvert.removeAllViews();
MakeButtonPanel();
setContentView(llvert);
}
});
llvert.addView(rl);
}
private void MakeButtonPanel(){
llvert.removeAllViews();
RelativeLayout rl = new RelativeLayout(this);
rl.setId(_id++);
rl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
rl.addView(MakeButton("<--"));
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.RIGHT_OF, (_id-1));
rl.addView(MakeButton("-->"), lp);
lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, (_id-2));
rl.addView(MakeButton("F5"), lp);
lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, (_id-2));
lp.addRule(RelativeLayout.RIGHT_OF,(_id-1));
rl.addView(MakeButton("ESC"), lp);
lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, (_id-2));
rl.addView(MakeButton("EXIT"), lp);
llvert.addView(rl);
}
private Button MakeButton(String sText){
Button b = new Button(this);
b.setId(_id++);
b.setText(sText);
int width = this.getWindowManager().getDefaultDisplay().getWidth();
int height = this.getWindowManager().getDefaultDisplay().getHeight();
b.setWidth(width>>1);
b.setHeight(height>>2);
b.setTextSize(b.getWidth()>>1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button thisButton = (Button)v;
if(thisButton.getText().toString().equals("EXIT")){
try{
closeSocket();
MakeConnectPanel();
return;
}catch(Exception ex){
Toast.makeText(getBaseContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
}
int iCode = Protocol(thisButton.getText().toString());
try{
byte[] buffer = new byte[5];
buffer[0] = 3;
buffer[1] = (byte)(iCode>>24);
buffer[2] = (byte)(iCode>>16);
buffer[3] = (byte)(iCode>>8);
buffer[4] = (byte)(iCode);
_s.getOutputStream().write(buffer);
_s.getOutputStream().flush();
}
catch(Exception ex){
Toast.makeText(getBaseContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
}
});
return b;
}
private int Protocol(String s){
int iReturn = 0;
if(s.equalsIgnoreCase("0")) iReturn = 0;
if(s.equalsIgnoreCase("1")) iReturn = 1;
if(s.equalsIgnoreCase("2")) iReturn = 2;
if(s.equalsIgnoreCase("3")) iReturn = 3;
if(s.equalsIgnoreCase("4")) iReturn = 4;
if(s.equalsIgnoreCase("5")) iReturn = 5;
if(s.equalsIgnoreCase("6")) iReturn = 6;
if(s.equalsIgnoreCase("7")) iReturn = 7;
if(s.equalsIgnoreCase("8")) iReturn = 8;
if(s.equalsIgnoreCase("9")) iReturn = 9;
if(s.equalsIgnoreCase("ESC")) iReturn = 10;
if(s.equalsIgnoreCase("F1")) iReturn = 11;
if(s.equalsIgnoreCase("F2")) iReturn = 12;
if(s.equalsIgnoreCase("F3")) iReturn = 13;
if(s.equalsIgnoreCase("F4")) iReturn = 14;
if(s.equalsIgnoreCase("F5")) iReturn = 15;
if(s.equalsIgnoreCase("F6")) iReturn = 16;
if(s.equalsIgnoreCase("F7")) iReturn = 17;
if(s.equalsIgnoreCase("F8")) iReturn = 18;
if(s.equalsIgnoreCase("F9")) iReturn = 19;
if(s.equalsIgnoreCase("F10")) iReturn = 20;
if(s.equalsIgnoreCase("F11")) iReturn = 21;
if(s.equalsIgnoreCase("F12")) iReturn = 22;
if(s.equalsIgnoreCase("F13")) iReturn = 23;
if(s.equalsIgnoreCase("F14")) iReturn = 24;
if(s.equalsIgnoreCase("F15")) iReturn = 25;
if(s.equalsIgnoreCase("F16")) iReturn = 26;
if(s.equalsIgnoreCase("F17")) iReturn = 27;
if(s.equalsIgnoreCase("F18")) iReturn = 28;
if(s.equalsIgnoreCase("F19")) iReturn = 29;
if(s.equalsIgnoreCase("F20")) iReturn = 30;
if(s.equalsIgnoreCase("F21")) iReturn = 31;
if(s.equalsIgnoreCase("F22")) iReturn = 32;
if(s.equalsIgnoreCase("F23")) iReturn = 33;
if(s.equalsIgnoreCase("F24")) iReturn = 34;
if(s.equalsIgnoreCase("<--")) iReturn = 35;
if(s.equalsIgnoreCase("-->")) iReturn = 36;
return iReturn;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Connect");
menu.add("Actions");
return true;
}
private void closeSocket(){
try{
if(this._s != null){
this._s.getOutputStream().write(-1);
this._s.shutdownOutput();
this._s.close();
}
}catch(Exception ex){
Toast.makeText(getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onBackPressed() {
closeSocket();
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().toString().toLowerCase().equals("connect")){
try{
closeSocket();
}catch(Exception ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
this.MakeConnectPanel();
}
if(item.getTitle().toString().toLowerCase().equals("actions")){
this.MakeButtonPanel();
}
return super.onOptionsItemSelected(item);
}
}
|
package org.w2b.designpatterns.singleton;
public class ClassHolderSingleton {
private static final ClassHolderSingleton INSTANCE = null;
/* Private constructor */
private ClassHolderSingleton() {
/* the body of the constructor here */
}
/* Access point to the unique instance of the singleton */
public static ClassHolderSingleton getInstance() {
return INSTANCE;
}
private static class JavaSingletonHolder{
private static final ClassHolderSingleton INSTANCE = new ClassHolderSingleton();
}
}
|
package craps_project;
import java.io.IOException;
public interface GameState {
boolean pointOff() throws IOException;
boolean pointOn() throws IOException;
}
|
package com.yf.accountmanager.sqlite;
import java.util.List;
import java.util.Set;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.yf.accountmanager.common.IConstants;
import com.yf.accountmanager.sqlite.ISQLite.AccountColumns;
public class AccountService {
public static Context context;
/**
* method:addAccount
*
* @param cv
* @return
*/
public static long addAccount(ContentValues cv) {
SQLiteDatabase db = ISQLite.getInstance(context).getWritableDatabase();
cv.remove(IConstants.ID);
long id = db.insert(ISQLite.TABLE_ACCOUNT, null, cv);
return id;
}
/**
* method:batchAddAccount
*
* @param cvs
* @return
*/
public static boolean batchAddAccount(List<ContentValues> cvs) {
SQLiteDatabase db = ISQLite.getInstance(context).getWritableDatabase();
for (int i = 0; i < cvs.size(); i++) {
ContentValues cv = cvs.get(i);
cv.remove(IConstants.ID);
long id = db.insert(ISQLite.TABLE_ACCOUNT, null, cv);
}
return true;
}
/**
* method:removeAccount
*
* @param idset
* @return
*/
public static boolean removeAccount(Set<Integer> idset) {
SQLiteDatabase db = ISQLite.getInstance(context).getWritableDatabase();
int count = db.delete(ISQLite.TABLE_ACCOUNT, "_id in("
+ CommonService.concatenateIds(idset) + ")", null);
return count > 0;
}
/**
* method:removeAccountBySite
*
* @param sitename
* @return
*/
public static boolean removeAccountBySite(String sitename) {
SQLiteDatabase db = ISQLite.getInstance(context).getWritableDatabase();
int count = db.delete(ISQLite.TABLE_ACCOUNT, AccountColumns.SITENAME
+ "=?", new String[] { sitename });
return count > 0;
}
/**
* method:updateAccount
*
* @param cv
* @param id
* @return
*/
public static boolean updateAccount(ContentValues cv, long id) {
cv.remove(IConstants.ID);
SQLiteDatabase db = ISQLite.getInstance(context).getWritableDatabase();
int count = db.update(ISQLite.TABLE_ACCOUNT, cv, "_id=?",
new String[] { id + "" });
return count > 0;
}
/**
* method:queryByColName
*
* @param colName
* @return
*/
public static Cursor queryByColumn(String colName,String colValue){
SQLiteDatabase db = ISQLite.getInstance(context).getReadableDatabase();
Cursor cursor = null;
if (IConstants.MATCH_ALL.equals(colValue)) {
cursor = db.rawQuery("select * from " + ISQLite.TABLE_ACCOUNT
+ " order by " + AccountColumns.SITENAME, null);
} else {
cursor = db.rawQuery("select * from " + ISQLite.TABLE_ACCOUNT
+ " where " + colName + "=? order by "
+ AccountColumns.SITENAME, new String[] { colValue });
}
return cursor;
}
/**
* method: queryDistinctColumn
*
* @param columnName
* @return
*/
public static Cursor queryDistinctColumnWithId(String columnName) {
return ISQLite
.getInstance(context)
.getReadableDatabase()
.rawQuery(
"select " + columnName + ",_id from "
+ ISQLite.TABLE_ACCOUNT + " group by "
+ columnName + " order by " + columnName, null);
}
public static Cursor queryDistinctColumn(String columnName){
return ISQLite
.getInstance(context)
.getReadableDatabase()
.rawQuery(
"select distinct " + columnName
+ " from " + ISQLite.TABLE_ACCOUNT
+ " order by " + columnName, null);
}
}
|
package com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.livebgsetting;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.BgPicBean;
import com.gxtc.huchuan.bean.LiveBgSettingBean;
import com.gxtc.huchuan.bean.LiveManagerBean;
import com.gxtc.huchuan.bean.LiveRoomBean;
import com.gxtc.huchuan.bean.event.EventLiveManager;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
/**
* Describe: 课堂管理 > 课堂简介
* Created by ALing on 2017/3/23 .
*/
public class LiveBgIntroduceActivity extends BaseTitleActivity implements View.OnClickListener,LiveBgSettingContract.View{
@BindView(R.id.et_live_intro)
EditText mEtLiveIntro;
private LiveBgSettingContract.Presenter mPresenter;
private HashMap<String, String> map;
private String token;
private String chatRoomId;
private String mIntroduce; //上个页面传过来的简介
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_bg_introduce);
}
@Override
public void initView() {
super.initView();
getBaseHeadView().showTitle(getString(R.string.title_live_bg_intro));
}
@Override
public void initData() {
super.initData();
new LiveBgSettingPrensenter(this);
mIntroduce = getIntent().getStringExtra("introduce");
if (mIntroduce != null){
mEtLiveIntro.setText(mIntroduce);
mEtLiveIntro.setSelection(mIntroduce.length());
}
token = UserManager.getInstance().getToken();
chatRoomId = UserManager.getInstance().getUser().getChatRoomId();
}
@Override
public void initListener() {
super.initListener();
getBaseHeadView().showBackButton(this);
getBaseHeadView().showHeadRightButton(getString(R.string.label_save), this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//返回
case R.id.headBackButton:
finish();
break;
//保存
case R.id.headRightButton:
save();
break;
}
}
private void save() {
if (TextUtils.isEmpty(mEtLiveIntro.getText().toString())) {
ToastUtil.showShort(this, getString(R.string.toast_empty_series_intro));
return;
} else {
map = new HashMap<>();
map.put("token", token);
map.put("id", chatRoomId);
map.put("introduce", mEtLiveIntro.getText().toString());
mPresenter.saveChatRoomSetting(map);
}
}
@Override
public void tokenOverdue() {
GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
}
@Override
public void showLiveManageData(LiveRoomBean bean) {
}
@Override
public void showPicList(List<BgPicBean> picData) {}
@Override
public void showCompressSuccess(File file) {}
@Override
public void showCompressFailure() {}
@Override
public void showUploadingSuccess(String url) {}
@Override
public void showChatRoomSetting(LiveBgSettingBean bean) {
ToastUtil.showShort(this,getString(R.string.modify_success));
String introduce = bean.getIntroduce();
Intent intent = new Intent();
intent.putExtra("introduce",introduce);
setResult(RESULT_OK,intent);
// EventBusUtil.post(new EventLiveManager(introduce));
finish();
}
@Override
public void showLoadMore(List<BgPicBean> datas) {
}
@Override
public void showNoMore() {
}
@Override
public void showManagerList(LiveManagerBean bean) {
}
@Override
public void showMoreManagerList(LiveManagerBean bean) {
}
@Override
public void setPresenter(LiveBgSettingContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
@Override
public void showLoadFinish() {
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {
getBaseEmptyView().showEmptyView();
}
@Override
public void showReLoad() {
mPresenter.getLiveManageData(map);
}
@Override
public void showError(String info) {
ToastUtil.showShort(this,info);
}
@Override
public void showNetError() {
getBaseEmptyView().showNetWorkView(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.getLiveManageData(map);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy();
}
}
|
package org.systemsbiology.gaggle.cereopsis.core;
import org.apache.activemq.spring.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.systemsbiology.gaggle.cereopsis.goose.CereopsisGoose;
import org.systemsbiology.gaggle.cereopsis.serialization.CompactNetworkToGaggleNetworkConverter;
import org.systemsbiology.gaggle.cereopsis.serialization.CompactNetwork;
import org.systemsbiology.gaggle.cereopsis.serialization.CompactNetworkSerializer;
import org.systemsbiology.gaggle.cereopsis.serialization.SerializableDataMatrix;
import org.systemsbiology.gaggle.core.datatypes.Namelist;
import org.systemsbiology.gaggle.core.datatypes.Cluster;
import javax.jms.*;
import net.sf.json.JSONObject;
/*
* Copyright (C) 2009 by Institute for Systems Biology,
* Seattle, Washington, USA. All rights reserved.
*
* This source code is distributed under the GNU Lesser
* General Public License, the text of which is available at:
* http://www.gnu.org/copyleft/lesser.html
*/
public class TopicListener implements MessageListener {
private CereopsisGoose goose;
public TopicListener(CereopsisGoose goose) {
this.goose = goose;
}
public void onMessage(Message message) {
//System.out.println("Got a message!");
//System.out.println("its class is " + message.getClass().getName());
ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
try {
if (textMessage.getStringProperty("MessageType") != null) {
//System.out.println("its type is " + message.getStringProperty("MessageType"));
//System.out.println("Message content:\n" + textMessage.getText());
JSONObject jsonObject = JSONObject.fromObject( textMessage.getText() );
String target = "Boss";
if (message.getStringProperty("Target") != null) {
target = message.getStringProperty("Target");
}
handleMessage(textMessage.getStringProperty("MessageType"), jsonObject.toString(), target);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
protected void handleMessage(String messageType, String message, String target) {
if (messageType.equals("Namelist")) {
handleNamelist(message, target);
} else if (messageType.equals("RequestGooseName")) {
goose.gotGooseNameRequest();
} else if (messageType.equals("Network")) {
handleNetwork(message, target);
} else if (messageType.equals("DataMatrix")) {
handleMatrix(message, target);
} else if (messageType.equals("Cluster")) {
handleCluster(message, target);
} else if (messageType.equals("Show")) {
goose.showGoose(target);
} else if (messageType.equals("Hide")) {
goose.hideGoose(target);
}
}
protected void handleNamelist(String message, String target) {
JSONObject jsonObject = JSONObject.fromObject(message);
Namelist namelist = (Namelist) JSONObject.toBean( jsonObject, Namelist.class );
goose.broadcastNamelist(namelist, target);
}
protected void handleNetwork(String message, String target) {
CompactNetwork cn = CompactNetworkSerializer.serializeFromJSON(message);
CompactNetworkToGaggleNetworkConverter converter = new CompactNetworkToGaggleNetworkConverter(cn);
goose.broadcastNetwork(converter.toGaggleNetwork(), target);
}
protected void handleMatrix(String message, String target) {
JSONObject bodyObject = JSONObject.fromObject(message);
SerializableDataMatrix m = (SerializableDataMatrix) JSONObject.toBean(bodyObject, SerializableDataMatrix.class);
goose.broadcastMatrix(m.toDataMatrix(), target);
}
protected void handleCluster(String message, String target) {
JSONObject bodyObject = JSONObject.fromObject(message);
Cluster c = (Cluster)JSONObject.toBean(bodyObject, Cluster.class);
goose.broadcastCluster(c, target);
}
public void run() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("Broadcast");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(this);
connection.start();
System.out.println("Waiting for messages...");
}
}
|
package org.aksw.autosparql.commons.nlp.pos;
import static org.junit.Assert.*;
import org.junit.Test;
public class StanfordPartOfSpeechTaggerTest
{
@Test public void testStanfordPartOfSpeechTagger()
{
String s = StanfordPartOfSpeechTagger.INSTANCE.tag("The quick brown fox jumps over the lazy dog.");
assertEquals("The/DT quick/JJ brown/JJ fox/NN jumps/VBZ over/IN the/DT lazy/JJ dog/NN ./.",s);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.reintegros.general.formato;
/**
* TituloLogGeneral - 24/10/2019 Descripcion : Formato de configuracion de los
* reportes ejecucion cargue masivo de timbres Version : 1.0
*
* @author juan jaime Davivienda 2019
*/
public class TituloCargasMasivasTimbres {
public static String[] tituloHoja;
static {
tituloHoja = new String[2];
tituloHoja[0] = "Reporte cargas masivas timbres.";
tituloHoja[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
/**
* Titulos de las columnas
*/
public static String[] tituloColumnas = {
"CAJERO",
"PROVDIASGTE_MAQUINA",
"PROVDIASGTE_LINEA",
"DIFERENCIAS",
"OBSERVACION",
"OCCA",
"AUMENTO",
"DISMINUCION",
"SOBRANTE",
"FALTANTE",
"NOVEDAD",
"ASIGNADO_A",
"PROVEEDOR",
"CLASIFICACION",
"TIPIFICACION_TRANSPORTADORA",
"RESULTADO_EJECUCION"
};
public static String[] tituloColumnasIngreso = {
"CAJERO",
"PROVDIASGTE_MAQUINA",
"PROVDIASGTE_LINEA",
"DIFERENCIAS",
"OBSERVACION",
"OCCA",
"AUMENTO",
"DISMINUCION",
"SOBRANTE",
"FALTANTE",
"NOVEDAD",
"ASIGNADO_A",
"PROVEEDOR",
"CLASIFICACION",
"TIPIFICACION_TRANSPORTADORA"};
}
|
package com.xiv.gearplanner.controllers.Importers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.xiv.gearplanner.exceptions.AriyalaParserException;
import com.xiv.gearplanner.exceptions.UnexpectedHtmlStructureException;
import com.xiv.gearplanner.models.Job;
import com.xiv.gearplanner.models.JobBIS;
import com.xiv.gearplanner.models.importers.AriyalaBIS;
import com.xiv.gearplanner.models.importers.AriyalaItem;
import com.xiv.gearplanner.models.inventory.*;
import com.xiv.gearplanner.parser.AriyalaBISParser;
import com.xiv.gearplanner.parser.URLS;
import com.xiv.gearplanner.services.GearService;
import com.xiv.gearplanner.services.ItemService;
import com.xiv.gearplanner.services.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Controller
public class BISImportController {
private JobService jobDao;
private GearService gearDao;
private ItemService itemDao;
@Value("${chrome-driver-install-location}")
String driverLocation;
@Autowired
public BISImportController(JobService jobDao, GearService gearDao, ItemService itemDao) {
this.jobDao = jobDao;
this.gearDao = gearDao;
this.itemDao = itemDao;
}
@GetMapping("/bis/importer")
public String importBIS(Model model) {
return "import/bis";
}
// Verify Page
@PostMapping("/bis/importer")
public String showBIS(Model model, @RequestParam(name = "bis") String id, @RequestParam(name = "name") String name) throws AriyalaParserException {
System.setProperty("webdriver.chrome.driver", driverLocation);
try {
AriyalaBISParser parser = new AriyalaBISParser(URLS.BIS);
AriyalaBIS ariyalaBIS = parser.getBISbyId(id);
if(ariyalaBIS.getItems().isEmpty()) {
model.addAttribute("error","Problem importing from ariyala. (Possible bad Code)");
}
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(ariyalaBIS);
model.addAttribute("name", name);
model.addAttribute("bisStr",json);
model.addAttribute("bis", ariyalaBIS);
} catch(UnexpectedHtmlStructureException e) {
model.addAttribute("error","Problem importing from ariyala. (HTML Issue)");
} catch (JsonProcessingException e) {
e.printStackTrace();
}
model.addAttribute("displayResult",true);
return "import/bis";
}
@PostMapping("/bis/importer/save")
public String saveBIS(Model model, @RequestParam(name ="bisJson") String json,
@RequestParam(name="bis-name-submit") String name) throws IOException {
// get bis object from page
ObjectMapper mapper = new ObjectMapper();
AriyalaBIS bis = mapper.readValue(json, AriyalaBIS.class);
Job job = jobDao.getJobs().findJobByAbbr(bis.getClassAbbr());
List<GearWithMelds> gearWithMelds = new ArrayList<>();
Food food = null;
// Loop for items ariyala
for(AriyalaItem item: bis.getItems()) {
System.out.println(item.getName() + item.getId());
Gear gear = gearDao.getGears().getFirstByOriginalId(item.getId().intValue());
if(gear == null) {
food = itemDao.getItems().findFoodByOriginalId(item.getId().intValue());
}
if(gear != null) {
List<Materia> melds = new ArrayList<>();
// Adding melds to list of melds for gear.
for (Map.Entry<Integer, String[]> me : item.getMateriaSlot().entrySet()) {
String[] val = me.getValue();
melds.add(materiaFromString(val[0]));
// val[1]; //color
}
gearWithMelds.add(new GearWithMelds(gear, melds));
}
}
JobBIS jobBIS = new JobBIS(bis.getId(),name,job);
jobBIS.setMelded(gearWithMelds);
if(food != null) {
jobBIS.setFood(food);
}
jobDao.getSets().save(jobBIS);
// save bis to db
model.addAttribute("json",json);
return "import/bisSaved";
}
Materia materiaFromString(String statString) {
String pattern = "^([A-Za-z ]+).([0-9]+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(statString);
System.out.println(statString);
if (m.find()) {
System.out.println("Found value: " + m.group(1)); //word
System.out.println("Found value: " + m.group(2)); //value
Materia materia =itemDao.getItems()
.getMateriaByStat(m.group(1).trim(),Long.parseLong(m.group(2)));
System.out.println(materia.toString());
return materia;
}
return null;
}
}
|
package com.bistel.listener;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.core.task.TaskExecutor;
import com.bistel.common.WebCache;
import com.bistel.util.ObjectConvertorUtils;
import com.bistel.tracesummary.model.OnDemandTraceSummaryRequestInfo;
public class AdhocSummaryRequestSender {
//logger
private Log log;
// Name of the rabbitmq exchange for adhocsummary request
private String requestExchange;
// Name of the rabbitmq exchange for adhocsummary response
private String responseExchange;
// Rabbit MQ Host name
private String host;
// RabbitMQ port
private String port;
// RabbitMq user name
private String user;
// Rabbitmq password
private String password;
// Request routing key
private String reqRoutingKey;
/** cache instance */
private WebCache webcache;
/** thread pool */
private TaskExecutor taskExecutor;
/**
* Method for sending adhoc summary request to queue
* @param searchInput - map containing request objects
* @param functions - name of functions to invoke
* @param context - listner context
* @param sessionId - user session id
* @throws NumberFormatException
* @throws IOException
* @throws CloneNotSupportedException
*/
public void sendRequest(Map<String, OnDemandTraceSummaryRequestInfo> searchInput,String[] functions, String context, String sessionId) throws NumberFormatException, IOException, CloneNotSupportedException{
if(searchInput!=null && searchInput.size()>0
&& functions!=null && functions.length>0){
if(log.isDebugEnabled())
log.debug("Sending request for Context : "+context+", Functions : "+ Arrays.toString(functions)+", searchInput : "+searchInput);
Map<String, OnDemandTraceSummaryRequestInfo> listnerInput = new HashMap<String, OnDemandTraceSummaryRequestInfo>();
for (Map.Entry<String,OnDemandTraceSummaryRequestInfo> entry : searchInput.entrySet()) {
OnDemandTraceSummaryRequestInfo infoTemp = entry.getValue().clone();
infoTemp.setFunctions(functions);
infoTemp.setContext(context);
if(log.isDebugEnabled())
log.debug("Adhoc search request made for : "+ infoTemp);
//creating request message client
MessagingClient requestClient = new MessagingClient(host, Integer.parseInt(port), user, password, requestExchange, null,null);
if(log.isDebugEnabled())
log.debug("Request Message Client :"+requestClient);
//publishing message on queue
requestClient.publishMessage(ObjectConvertorUtils.toBytes(infoTemp), reqRoutingKey);
listnerInput.put(entry.getKey(), infoTemp);
}
if(log.isDebugEnabled())
log.debug("Adhoc summary request sent successfully. Message count published :"+listnerInput.size());
//creating message client
MessagingClient responseClient = new MessagingClient(host, Integer.parseInt(port), user, password, responseExchange, context, context);
if(log.isDebugEnabled())
log.debug("Response Message Client :"+responseClient);
//invoking listener thread
taskExecutor.execute(new OnDemandTraceSummaryResponseListener(listnerInput,webcache,responseClient,sessionId));
}else{
log.warn("Adhoc summary request deferred as request object or function value is invalid !!!");
}
}
public void setLog(Log log) {
this.log = log;
}
public void setRequestExchange(String requestExchange) {
this.requestExchange = requestExchange;
}
public void setResponseExchange(String responseExchange) {
this.responseExchange = responseExchange;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(String port) {
this.port = port;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setReqRoutingKey(String reqRoutingKey) {
this.reqRoutingKey = reqRoutingKey;
}
public void setWebcache(WebCache webcache) {
this.webcache = webcache;
}
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
}
|
package barryalan.ediary70;
/**
* Created by Al on 10/30/2017.
*/
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class goalsMenu extends AppCompatActivity implements AdapterView.OnItemClickListener{
final databaseHelper db = new databaseHelper(this);
user User1 = new user();
//Declare page components
LinearLayout navigationBar;
Button btn_barVisibility;
ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goals_menu);
//Link components to the ones on the page
navigationBar = (LinearLayout)findViewById(R.id.navigationBar);
btn_barVisibility = (Button)findViewById(R.id.btn_barVisibility);
lv = (ListView) findViewById(R.id.lv_Ggoals);
//Fill out the list view with all the user's goals
populateGoalListView();
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int position, long id) {
String timeRemaining = "";
User1.currentUserGoalNumber = position + 1;
//Creates and fills a list of the users in the database
List<user> usersArrayList = new ArrayList<>(db.getUsers());
//Iterating through the whole list of users
for(int i = 0; i <= usersArrayList.size() - 1; i++){
//Finding the user object that contains the information of the current user
if(usersArrayList.get(i).getId() == User1.currentUserID){
//Getting the correct info for the current user
String goalNames = usersArrayList.get(i).getUserGoalNames();
String goalDescriptions = usersArrayList.get(i).getUserGoalDescriptions();
String goalTimes = usersArrayList.get(i).getUserGoalTimes();
//Declaring the strings that will hold the data of the goal that was clicked on
String goalName = "";
String goalDescription = "";
String goalTime = "";
//Getting the right values for the name,description, and time of the goal selected
for(int j = 0; j < position + 1; j ++){
goalName = goalNames.substring(1, goalNames.indexOf("&",goalNames.indexOf("&") + 1));
goalNames = goalNames.substring(goalNames.indexOf("&",goalNames.indexOf("&") + 1));
goalDescription = goalDescriptions.substring(1, goalDescriptions.indexOf("&",goalDescriptions.indexOf("&") + 1));
goalDescriptions = goalDescriptions.substring(goalDescriptions.indexOf("&",goalDescriptions.indexOf("&") + 1));
goalTime = goalTimes.substring(1, goalTimes.indexOf("&",goalTimes.indexOf("&") + 1));
goalTimes = goalTimes.substring(goalTimes.indexOf("&",goalTimes.indexOf("&") + 1));
}
//Splitting goalTime Ex. 2-Minutes into timeAmount = "2" and timeType = "Minutes"
String timeAmount = goalTime.substring(0,goalTime.indexOf("-"));
String timeType = goalTime.substring(goalTime.indexOf("-") + 1);
//Creates and displays floating message box with goal information
goalInfoMessage(view,goalName.toUpperCase(),
"Description:\n" + " " + goalDescription + "\n\n"
+"Time Allowed:\n" + " " + timeAmount + " " + timeType + "\n\n"
+"Time Remaining:\n" + " " + timeRemaining + "\n\n" );
}
}
}
//Fills out the list view on the page with information
public void populateGoalListView(){
//Grabbing all users from the database
List<user> usersArrayList = new ArrayList<>(db.getUsers());
//Create a list to hold all the goal names of this user
ArrayList<String> listData = new ArrayList<>();
//Using the currentUsername obtained on the login page find the current user's ID
for(int i = 0; i <= usersArrayList.size() - 1; i++){
//Finding the user object that contains the information of the current user
if(usersArrayList.get(i).getUserUsername().compareTo(User1.currentUserName) == 0){
User1.currentUserID = usersArrayList.get(i).getId();
//Populate listData with all the goal names for this user's goals if the user has goals saved
if(!TextUtils.isEmpty(usersArrayList.get(i).getUserGoalNames())){
String goalNames = usersArrayList.get(i).getUserGoalNames().toUpperCase();
String goalName;
while(goalNames.compareTo("&") != 0) {
goalName = goalNames.substring(1, goalNames.indexOf("&",goalNames.indexOf("&") + 1));
listData.add(goalName);
goalNames = goalNames.substring(goalNames.indexOf("&",goalNames.indexOf("&") + 1));
}
}
}
}
//Populate the listView with the items in the listData list
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
public void goalInfoMessage(final View v, final String title, String message){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
//When the Delete button on the pop up box is pressed
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
deleteVerificationMessage(v,"Are you sure you want to delete?","");
}
});
//When the Edit button on the pop up box is pressed
alertDialog.setNegativeButton("Edit", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
gotoEditGoalActivity(v);
}
});
alertDialog.show();
}
public void deleteVerificationMessage(final View v, final String title, String message){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
//Sets pop up box content
alertDialog.setTitle(title);
alertDialog.setMessage(message);
//If the Delete button is pressed inside the pop up text box
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
//Create and fill a list with the users in the database
List<user> usersArrayList = new ArrayList<>(db.getUsers());
//Iterate as many times as the amount of users
for(int i = 0; i < db.getUserCount().getCount() ; i++){
//Finding the user object for the current user
if(usersArrayList.get(i).getId() == User1.currentUserID ) {
//Retrieving the current user's data from the database
String goalNames = usersArrayList.get(i).getUserGoalNames();
String goalDescriptions = usersArrayList.get(i).getUserGoalDescriptions();
String goalTimes = usersArrayList.get(i).getUserGoalTimes();
//Removing the deleted data from the strings
goalNames = findNewString(goalNames);
goalDescriptions = findNewString(goalDescriptions);
goalTimes = findNewString(goalTimes);
//Update the goal name, description, and time entries for that user object
usersArrayList.get(i).setUserGoalNames(goalNames);
usersArrayList.get(i).setUserGoalDescriptions(goalDescriptions);
usersArrayList.get(i).setUserGoalTimes(goalTimes);
//Update the database with the changes made to that user object
db.updateUser(usersArrayList.get(i));
//Display toast message
Toast.makeText(getApplicationContext(),"Deletion has been made",Toast.LENGTH_SHORT).show();
}
}
//Update the list view display of the current goals
populateGoalListView();
}
});
//If the Cancel button is pressed inside the pop up text box
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
Toast.makeText(goalsMenu.this,"You have canceled the deletion", Toast.LENGTH_SHORT).show();
}
});
//Make the pop up box visible
alertDialog.show();
}
//Deletes the section of a string with index specified by the currentUserGoalNumber
public String findNewString(String originalString){
String part2 = originalString;
String part1 = "";
for(int j = 0; j < User1.currentUserGoalNumber; j ++) {
//If you try to delete the last goal on the listView
if(j + 1 == lv.getCount()){
//If there is only one goal
if(lv.getAdapter().getCount() == 1){
return "";
}
//If there is more than one goal
return originalString.substring(0, originalString.lastIndexOf("&", originalString.length() - 2) + 1);
}
//Part 2 is the string after the part that needs to be deleted
part2 = part2.substring(part2.indexOf("&", part2.indexOf("&") + 1));
}
//Part 1 is the string before the part that needs to be deleted
part1 = originalString.substring(originalString.indexOf("&"),originalString.lastIndexOf("&",originalString.indexOf(part2)-1));
//If you try to delete anything besides the last goal on the listView
return part1 + part2;
}
//Changes the visibility of the navigation bar
public void changeBarVisibility(View view){
if(navigationBar.getVisibility() == View.VISIBLE){
navigationBar.setVisibility(View.GONE);
btn_barVisibility.setText(">\n>\n>");
}
else{
navigationBar.setVisibility(View.VISIBLE);
btn_barVisibility.setText("<\n<\n<");
}
}
//LINK TO THE NEW GOAL PAGE THROUGH THE BUTTON-------------------------------
public void gotoNewGoalActivity(View view) {
Intent name = new Intent(this, newGoal.class);
startActivity(name);
}
//LINK TO THE LOGIN PAGE THROUGH THE BUTTON-------------------------------
public void gotoEditGoalActivity(View view) {
Intent name = new Intent(this, EditGoal.class);
startActivity(name);
}
//LINK TO THE HEALTH MENU PAGE THROUGH THE BUTTON-------------------------------
public void gotoHealthCareMenuActivity(View view) {
Intent name = new Intent(this, healthCareMenu.class);
startActivity(name);
}
//LINK TO THE CONTACTS PAGE THROUGH THE BUTTON-------------------------------
public void gotoContactsActivity(View view) {
Intent name = new Intent(this, contactsPage.class);
startActivity(name);
}
//LINK TO THE LOGIN PAGE THROUGH THE BUTTON-------------------------------
public void gotoLoginActivity(View view) {
Intent name = new Intent(this, login.class);
startActivity(name);
}
public void logoutVerificationMessage(final View v){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
//Sets pop up box content
alertDialog.setTitle("Are you sure you want to log out?");
alertDialog.setMessage("You will be required to re-enter your login information to come back");
//If the Log out button is pressed inside the pop up text box
alertDialog.setPositiveButton("Log out", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
gotoLoginActivity(v);
}
});
//If the Cancel button is pressed inside the pop up text box
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
}
});
//Make the pop up box visible
alertDialog.show();
}
}
|
package Views.Inventory;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import Controllers.Inventory.AddInventoryController;
import MVC.MasterFrame;
import Models.InventoryModel;
import Models.PartModel;
public class AddInventoryPartView extends JPanel{
private MasterFrame master;
private InventoryModel model;
private PartModel partModel;
private String[] locations;
private String[] parts;
private String myTitle = "Add Inventory Part";
private ArrayList<String> partList = new ArrayList();
private ArrayList<String> locationsList = new ArrayList();
JComboBox locationsBox;
JComboBox partsBox;
JComboBox productsBox;
JLabel location = new JLabel("Choose Location");
JLabel part = new JLabel("Choose Part");
JLabel quantity = new JLabel("Quantity: ");
JTextField qText = new JTextField(20);
JButton save = new JButton("Save");
public AddInventoryPartView(MasterFrame m){
master = m;
model = master.getInventoryModel();
AddInventoryController controller = new AddInventoryController(this, master);
this.setLayout(new GridLayout(7,1));
partModel = master.getPartModel();
partModel.setPartArrayList();
partList = partModel.getPartArrayList();
parts = new String[partList.size()];
parts = partList.toArray(parts);
partsBox = new JComboBox(parts);
model.setLocationsArrayList();
locationsList = model.getLocationsArrayList();
locations = new String[locationsList.size()];
locations = locationsList.toArray(locations);
locationsBox = new JComboBox(locations);//locationBox = new JComboBox
save.addActionListener(controller);
this.add(location);
this.add(locationsBox);
this.add(part);
this.add(partsBox);
this.add(quantity);
this.add(qText);
this.add(save);
}
public String getTitle(){
return myTitle;
}
public String getLocationValue(){
String str = (String)locationsBox.getSelectedItem();
return str;
}
public String getPartValue(){
String str = (String)partsBox.getSelectedItem();
return str;
}
public int getQText(){
return Integer.parseInt(qText.getText());
}
}
|
package hwl4;
import java.util.Random;
public class GuessTheLetterGame {
public static void startGame() {
Random rand = new Random();
int letter = 0;
int minIndex = 65;
int maxIndex = 90;
int exitIndex = 48;
int ansver;
boolean endGame = false;
System.out.println("Для выхода из игры введите \"0\"");
while (!endGame) {
letter = rand.nextInt(25) + 65;
System.out.println("Загадайте букву");
ansver = (int)MainClassl4.gSc.next().toCharArray()[0];
if (ansver == exitIndex)
break;
if ((ansver < minIndex) || (ansver > maxIndex)) {
System.out.println("Введена не верная буква");
} else {
if (ansver==letter) {
System.out.println("«Right»");
break;
} else
{
System.out.println( ansver<letter? "«You’re too low»":"«You’re too high»");
}
}
}
}
}
|
package my-package;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"to",
"distance"
})
public class London implements Serializable
{
@JsonProperty("to")
private String to;
@JsonProperty("distance")
private Integer distance;
private final static long serialVersionUID = -1873525364616450771L;
@JsonProperty("to")
public String getTo() {
return to;
}
@JsonProperty("to")
public void setTo(String to) {
this.to = to;
}
@JsonProperty("distance")
public Integer getDistance() {
return distance;
}
@JsonProperty("distance")
public void setDistance(Integer distance) {
this.distance = distance;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(London.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("to");
sb.append('=');
sb.append(((this.to == null)?"<null>":this.to));
sb.append(',');
sb.append("distance");
sb.append('=');
sb.append(((this.distance == null)?"<null>":this.distance));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.distance == null)? 0 :this.distance.hashCode()));
result = ((result* 31)+((this.to == null)? 0 :this.to.hashCode()));
return result;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof London) == false) {
return false;
}
London rhs = ((London) other);
return (((this.distance == rhs.distance)||((this.distance!= null)&&this.distance.equals(rhs.distance)))&&((this.to == rhs.to)||((this.to!= null)&&this.to.equals(rhs.to))));
}
}
|
package dev.liambloom.softwareEngineering.chapter5;
import dev.liambloom.softwareEngineering.Globals;
public class $ {
public static boolean between (int min, int max, int c) {
return min < c && c < max;
}
public static int mid (int a, int b, int c) {
int min = Globals.Math.min(a, b, c);
int max = Globals.Math.max(a, b, c);
return between(min, max, a) ? a : between(min, max, b) ? b : c;
}
public static double logBase (int base, int val) {
return Math.log(val) / Math.log(base);
}
public static double log2 (int val) {
return logBase(2, val);
}
}
|
package com.qzdatasoft.comm.dao.util;
/**
* 类型转变
*/
import java.util.Date;
public class TypeUtil {
public static Object cast(String value, Class propertyType) {
String className = convertType(propertyType);
return cast(className, value);
}
private static Object cast(String className, String value) {
if (className.equals("string")) {
return value;
} else if (className.equals("bool")) {
return Boolean.valueOf(value);
} else if (className.equals("date")) {
return new Date(value);
} else if (className.equals("short")) {
return Short.valueOf(value);
} else if (className.equals("int")) {
return Integer.valueOf(value);
} else if (className.equals("long")) {
return Long.valueOf(value);
} else if (className.equals("float")) {
return Float.valueOf(value);
} else if (className.equals("double")) {
return Double.valueOf(value);
} else if (className.equals("byte")) {
return Byte.valueOf(value);
} else if (className.equals("char")) {
return new Character(value.charAt(0));
} else {
throw new RuntimeException("[" + className + "," + value + "类型转化错误");
}
}
public static String convertType(Class clazz) {
if (clazz.isPrimitive()) {
if (clazz.equals(Boolean.TYPE))
return "bool";
else {
String classname = clazz.getName();
int pos = classname.lastIndexOf(".");
return classname.substring(pos + 1);
}
}
String local_name = clazz.getName();
String common_name = null;
if (local_name.equals("java.lang.String")) {
common_name = "string";
} else if (local_name.equals("java.lang.Boolean")) {
common_name = "bool";
} else if (local_name.equals("java.util.Date")) {
common_name = "date";
} else if (local_name.equals("java.lang.Short")) {
common_name = "short";
} else if (local_name.equals("java.lang.Integer")) {
common_name = "int";
} else if (local_name.equals("java.lang.Long")) {
common_name = "long";
} else if (local_name.equals("java.lang.Float")) {
common_name = "float";
} else if (local_name.equals("java.lang.Double")) {
common_name = "double";
} else if (local_name.equals("java.lang.Byte")) {
common_name = "byte";
} else if (local_name.equals("java.lang.Character")) {
common_name = "char";
} else if (local_name.equals("java.lang.Object")) {
common_name = "object";
} else {
common_name = clazz.getName();
}
return common_name;
}
}
|
/*
* Copyright 2002-2016 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.jms.connection;
import jakarta.jms.Connection;
import jakarta.jms.ConnectionConsumer;
import jakarta.jms.ConnectionMetaData;
import jakarta.jms.Destination;
import jakarta.jms.ExceptionListener;
import jakarta.jms.JMSException;
import jakarta.jms.ServerSessionPool;
import jakarta.jms.Session;
import jakarta.jms.Topic;
/**
* @author Juergen Hoeller
*/
public class TestConnection implements Connection {
private ExceptionListener exceptionListener;
private int startCount;
private int closeCount;
@Override
public Session createSession(boolean b, int i) throws JMSException {
return null;
}
@Override
public Session createSession(int sessionMode) throws JMSException {
return null;
}
@Override
public Session createSession() throws JMSException {
return null;
}
@Override
public String getClientID() throws JMSException {
return null;
}
@Override
public void setClientID(String paramName) throws JMSException {
}
@Override
public ConnectionMetaData getMetaData() throws JMSException {
return null;
}
@Override
public ExceptionListener getExceptionListener() throws JMSException {
return exceptionListener;
}
@Override
public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
this.exceptionListener = exceptionListener;
}
@Override
public void start() throws JMSException {
this.startCount++;
}
@Override
public void stop() throws JMSException {
}
@Override
public void close() throws JMSException {
this.closeCount++;
}
@Override
public ConnectionConsumer createConnectionConsumer(Destination destination, String paramName, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
@Override
public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String paramName, String paramName1, ServerSessionPool serverSessionPool, int i) throws JMSException {
return null;
}
@Override
public ConnectionConsumer createSharedConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
return null;
}
@Override
public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
return null;
}
public int getStartCount() {
return startCount;
}
public int getCloseCount() {
return closeCount;
}
}
|
package com.cinema.biz.dao;
import java.util.List;
import java.util.Map;
import com.cinema.biz.model.SimThreshold;
import com.cinema.biz.model.base.TSimThreshold;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface SimThresholdMapper extends Mapper<TSimThreshold>,MySqlMapper<TSimThreshold>{
/**列表*/
List<SimThreshold> getList(Map<String, Object> paraMap);
/**详情*/
SimThreshold getDetail(Map<String, Object> paraMap);
}
|
package itcs4180.otherintents;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Simple intent
// Doesn't require any permissions
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.uncc.edu"));
startActivity(intent);
// This one requires permission from user!!!
// TO make a phone call
Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:7046877476"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent1); // Will give an error. need to add something (the blob above
// was added automatically :'D )
}
}
|
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class Map extends Mapper<LongWritable,Text,Text,IntWritable>{
private Text Column1 = new Text("Column1");
private Text Column2 = new Text("Column2");
public void map(LongWritable Key, Text Value, Context context) throws IOException, InterruptedException {
String line = Value.toString();
String Cols[] = line.split(",");
context.write(Column1, new IntWritable(Integer.parseInt(Cols[0])));
context.write(Column2, new IntWritable(Integer.parseInt(Cols[1])));
}
}
|
/**
*
*/
package enumerate;
import enumerate.Days;
/**
* @author Aloy
*
*/
public class Working_days {
/**
*
*/
public Working_days() {
// TODO Auto-generated constructor stub
}
private static void weekend(Days d) {
// TODO Auto-generated method stub
if(d.equals(Days.sunday)){
System.out.println("value= "+ d +"is a holiday");
}
else if(d.equals(Days.unidentified)){
System.out.println("value="+ d +"is a not a valid data in the list of days");
}
else if(!(d.equals(Days.sunday))){
System.out.println("value= "+ d +"is not a holiday");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (Days d : Days.values()) {
weekend(d);
}
}
}
|
package com.romens.yjkgrab.ui;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.PushService;
import com.avos.avoscloud.SaveCallback;
import com.romens.yjkgrab.model.Order;
import com.romens.yjkgrab.ui.activity.YJKActivity;
import com.romens.yjkgrab.utils.AVOSCloudHelper;
import java.util.ArrayList;
/**
* Created by myq on 15-12-7.
*/
public class GrabApplication extends Application {
public String getInstallationId() {
return installationId;
}
public void setInstallationId(String installationId) {
this.installationId = installationId;
}
private String installationId;
public ArrayList<Order> getData() {
return data;
}
public void setData(ArrayList<Order> data) {
this.data = data;
}
private ArrayList<Order> data = new ArrayList<>();
public Order queryOrderById(String objectId) {
for (Order order : data) {
if (TextUtils.equals(objectId, order.getObjectId())) {
return order;
}
}
return null;
}
@Override
public void onCreate() {
super.onCreate();
AVOSCloudHelper.init(this);
//// 订阅频道,当该频道消息到来的时候,打开对应的 Activity
PushService.subscribe(this, "public", YJKActivity.class);
//第一个参数是当前的 context,第二个参数是频道名称,第三个参数是回调对象的类,回调对象是指用户点击通知栏的通知进入的 Activity 页面。
//PushService.subscribe(this, "private", Callback1.class);
// PushService.subscribe(this, "protected", Callback2.class);
//退订频道也很简单:
//PushService.unsubscribe(context, "protected");
//退订之后需要重新保存 Installation
//AVInstallation.getCurrentInstallation().saveInBackground();
//你可以通过以下代码保存你的 Installation id。如果你的系统之前还没有 Installation id, 系统会为你自动生成一个。如果你的应用卸载后,Installation id也将会被删除
// 设置默认打开的 Activity
PushService.setDefaultPushCallback(this, YJKActivity.class);
AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
public void done(AVException e) {
if (e == null) {
// 保存成功
setInstallationId(AVInstallation.getCurrentInstallation().getInstallationId());
// 关联 installationId 到用户表等操作……
Log.i(">>>>>>>>>>>>", "installationId=" + installationId);
} else {
// 保存失败,输出错误信息
e.printStackTrace();
}
}
});
}
}
|
package com.fotoable.fotoime.ui;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.inputmethod.keyboard.KeyboardLayoutSet;
import com.android.inputmethod.keyboard.KeyboardTheme;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.crashlytics.android.core.CrashlyticsCore;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flurry.android.FlurryAgent;
import com.fotoable.adloadhelper.ads.AnimateNativeAdViewLayout;
import com.fotoable.adloadhelper.ads.IAdViewCallBackListener;
import com.fotoable.adloadhelper.ads.NativeAdViewLayout;
import com.fotoable.adloadhelper.ads.NativeAdViewManager;
import com.fotoable.adloadhelper.ads.adsbean.NativeAdBase;
import com.fotoable.fotoime.BuildConfig;
import com.fotoable.fotoime.FotoApplication;
import com.fotoable.fotoime.R;
import com.fotoable.fotoime.adapter.SectionedRecyclerViewAdapter;
import com.fotoable.fotoime.ads.BannerAdViewInMainTop;
import com.fotoable.fotoime.ads.BigAdViewInMainInterfaceBottom;
import com.fotoable.fotoime.network.FotoRestClient;
import com.fotoable.fotoime.theme.GroupThemeItem;
import com.fotoable.fotoime.theme.ThemeConstant;
import com.fotoable.fotoime.theme.ThemeTools;
import com.fotoable.fotoime.theme.apk.APKRescourceUtil;
import com.fotoable.fotoime.theme.apk.ThemeResourceManager;
import com.fotoable.fotoime.theme.bean.CustomThemeItem;
import com.fotoable.fotoime.utils.AdCache;
import com.fotoable.fotoime.utils.Constants;
import com.fotoable.fotoime.utils.DataCollectConstant;
import com.fotoable.fotoime.utils.DownloadThemeUtil;
import com.fotoable.fotoime.utils.MobileUtil;
import com.fotoable.fotoime.utils.MutableConstants;
import com.fotoable.fotoime.utils.NetWorkUtils;
import com.fotoable.fotoime.utils.PackageUtil;
import com.fotoable.fotoime.utils.SharedPreferenceHelper;
import com.fotoable.fotoime.utils.SoftInputUtil;
import com.fotoable.fotoime.utils.ThemeUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import cz.msebera.android.httpclient.Header;
import io.fabric.sdk.android.Fabric;
/**
* 主题界面
*/
public class ThemeFragment extends Fragment {
private String TAG = ThemeFragment.class.getSimpleName();
public static final double IMAGE_RATE = 228.0 * 100 / 321.0; //键盘图片高宽比(高/宽)
private Context mContext;
private SharedPreferences mThemePrefs;
private int mCurrentCheckedTheme = 0;
private SectionRecyclerViewAdapter mSimpleStringRecyclerViewAdapter;
private boolean isVisable = false;
// 上面的广告
private LinearLayout adViewTopContainer;
private GridLayoutManager gridLayoutManager;
private ArrayList<GroupThemeItem> groupThemeItems;
private View contentView;
private boolean isKeyboardHideByTouch = false;
private SharedPreferences sharedPreferences;
private boolean firstPopupActivateTheme = true;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mThemePrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
sharedPreferences = getContext().getSharedPreferences(Constants.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
mContext = getContext();
initSection();
// updateConfig();
}
// 更新配置文件
private void updateConfig() {
if (NetWorkUtils.isNetWorkAvailable(getActivity())) {
long lastRequstTime = mThemePrefs.getLong(Constants.LAST_REQUEST_KEYBOARD_THEME_CONFIG, 0l);
// 是否过期
if (System.currentTimeMillis() - lastRequstTime > Constants.IME_THEME_CONFIG_INTERVAL_TIME) {
// TODO:此处只能为 2.5.3~9.9.9
String version = BuildConfig.VERSION_NAME;
Constants.KEYBOARD_THEME_CONFIG_URL = String.format(Constants.KEYBOARD_THEME_CONFIG_URL, version);
if (BuildConfig.LOG_DEBUG) {
Log.i(TAG, "--------- theme config------- request:" + Constants.KEYBOARD_THEME_CONFIG_URL);
}
// 请求配置文件
FotoRestClient.get(Constants.KEYBOARD_THEME_CONFIG_URL, null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
final String response = new String(responseBody, Charset.defaultCharset());
if (BuildConfig.LOG_DEBUG) {
Log.i(TAG, "--------- theme config------- response:" + response);
}
// 持久化到本地
ThemeTools.writeFileData(MutableConstants.KEYBOARD_THEME_CONFIG_NAME, response);
// 记录时间
mThemePrefs.edit().putLong(Constants.LAST_REQUEST_KEYBOARD_THEME_CONFIG, System.currentTimeMillis()).apply();
final String data = ThemeTools.readFileData(MutableConstants.KEYBOARD_THEME_CONFIG_NAME);
groupThemeItems = ThemeTools.json2GroupThemeItemList(data);
if (mSimpleStringRecyclerViewAdapter != null) {
try {
mSimpleStringRecyclerViewAdapter.notifyDataSetChanged();
} catch (Exception e) {
CrashlyticsCore.getInstance().logException(e);
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
// 更新icon配置文件
FotoRestClient.get(MutableConstants.FOTO_GIFTBOX_CONFIG_URL, null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
final String response = new String(responseBody, Charset.defaultCharset());
ThemeTools.writeFileData(MutableConstants.FOTO_GIFTBOX_CONFIG_NAME, response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
} else {
if (BuildConfig.LOG_DEBUG)
Log.i(TAG, "------ not expire ----");
}
}
}
public void initSection() {
final String data = ThemeTools.readFileData(MutableConstants.KEYBOARD_THEME_CONFIG_NAME);
groupThemeItems = ThemeTools.json2GroupThemeItemList(data);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
isVisable = true;
checkTopAdsUpdate();
// 获取当前id
getCurrentCheckedThemeId();
updateByItemChecked();
//检查广告是否过期
if (AdCache.mThemeMiddleAdView != null) {
AdCache.mThemeMiddleAdView.updateNativeAd();
}
if (AdCache.mThemeBottomAdView != null) {
AdCache.mThemeBottomAdView.updateNativeAd();
}
} else {
isVisable = false;
}
if (BuildConfig.LOG_DEBUG) {
Log.i(TAG, "---- setUserVisibleHint:" + isVisibleToUser + "------");
}
}
private void initTopAdView() {
/** 是否移除广告 **/
return;
}
private void checkTopAdsUpdate() {
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()) return;
if (AdCache.mTopAdView != null && adViewTopContainer != null) {
if (AdCache.mTopAdView.getIsLoadSuccessed()) {
ViewGroup viewGroup = (ViewGroup) AdCache.mTopAdView.getParent();
if (viewGroup != null) {
viewGroup.removeAllViews();
}
adViewTopContainer.addView(AdCache.mTopAdView);
adViewTopContainer.setVisibility(View.VISIBLE);
} else {
adViewTopContainer.setVisibility(View.GONE);
}
AdCache.mTopAdView.updateNativeAd();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getCurrentCheckedThemeId();
contentView = inflater.inflate(R.layout.foto_fragment_theme, container, false);
RecyclerView mRecyclerView = (RecyclerView) contentView.findViewById(R.id.foto_recyclerview_theme);
setupRecyclerView(mRecyclerView);
adViewTopContainer = (LinearLayout) contentView.findViewById(R.id.foto_theme_top_adview);
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()) {
adViewTopContainer.setVisibility(View.GONE);
}
initTopAdView();
return contentView;
}
public void getCurrentCheckedThemeId() {
// 获取默认
final String klpThemeIdString = mThemePrefs.getString(KeyboardTheme.KLP_KEYBOARD_THEME_KEY, "0");
try {
mCurrentCheckedTheme = Integer.valueOf(klpThemeIdString);
} catch (Exception e) {
mCurrentCheckedTheme = 0;
}
}
private void setupRecyclerView(RecyclerView recyclerView) {
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
mSimpleStringRecyclerViewAdapter = new SectionRecyclerViewAdapter(groupThemeItems);
recyclerView.setAdapter(mSimpleStringRecyclerViewAdapter);
mSimpleStringRecyclerViewAdapter.setLayoutManager(gridLayoutManager);
//add by mee
// int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.foto_main_recycler_view_space);
// recyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));
//滑动弹出激活更多keyboard—PIP主题
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
boolean fotoImeEnabled = Constants.isActiveKeyboard;
if (dy > 0 && !fotoImeEnabled) {
//应用第一次开启设置activity,之后都不开启设置Activity
firstPopupActivateTheme = sharedPreferences.getBoolean(Constants.FIRST_POPUP_ACTIVATE_THEME, true);
if (firstPopupActivateTheme) {
sharedPreferences.edit().putBoolean(Constants.FIRST_POPUP_ACTIVATE_THEME, false).apply();
Intent intent = new Intent(ThemeFragment.this.mContext, KeyboardPipInfoWindowActivity.class);
startActivity(intent);
}
}
}
});
/*recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
// LogUtil.i(TAG, "recyclerView--addOnItemTouchListener-- onInterceptTouchEvent");
if (e.getAction() == MotionEvent.ACTION_DOWN) {
LogUtil.i(TAG, "recyclerView--addOnItemTouchListener-- onInterceptTouchEvent--ACTION_DOWN");
MainActivity mActivity = (MainActivity) getContext();
if (mActivity == null) return false;
if (mActivity.isKeyboardShown()) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
isKeyboardHideByTouch = true;
//return true;
}
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
LogUtil.i(TAG, "recyclerView--addOnItemTouchListener-- onRequestDisallowInterceptTouchEvent");
}
});*/
}
@Override
public void onResume() {
super.onResume();
getCurrentCheckedThemeId();
if (mSimpleStringRecyclerViewAdapter != null) {
mSimpleStringRecyclerViewAdapter.notifyDataSetChanged();
}
if (isVisable) {
checkTopAdsUpdate();
}
if (BuildConfig.LOG_DEBUG) {
Log.i(TAG, "--- onResume ---");
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (adViewTopContainer != null) {
adViewTopContainer.removeAllViews();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (AdCache.mThemeMiddleAdView != null){
AdCache.mThemeMiddleAdView.setIAdViewCallBackListener(null);
if (AdCache.mThemeMiddleAdView.getParent() != null){
final ViewGroup parent = (ViewGroup) AdCache.mThemeMiddleAdView.getParent();
parent.removeAllViews();
}
}
if (AdCache.mThemeBottomAdView != null){
AdCache.mThemeBottomAdView.setIAdViewCallBackListener(null);
if (AdCache.mThemeBottomAdView.getParent() != null){
final ViewGroup parent = (ViewGroup) AdCache.mThemeBottomAdView.getParent();
parent.removeAllViews();
}
}
}
@Override
public void onDetach() {
super.onDetach();
}
public void updateByItemChecked() {
if (mSimpleStringRecyclerViewAdapter != null)
mSimpleStringRecyclerViewAdapter.notifyDataSetChanged();
}
public class SectionRecyclerViewAdapter extends SectionedRecyclerViewAdapter<SectionRecyclerViewAdapter.ItemViewHolder> {
private final int THEME_ITEM = -1;
private final int AD_ITEM = 0;
private final int THEME_SELECTION_TITLE = -2;
private ArrayList<GroupThemeItem> groupThemeItems;
public SectionRecyclerViewAdapter(ArrayList<GroupThemeItem> items) {
this.groupThemeItems = items;
}
@Override
public int getSectionCount() {
return groupThemeItems != null ? groupThemeItems.size() : 0;
}
@Override
public int getItemCount(int section) {
if (groupThemeItems != null) {
final GroupThemeItem groupThemeItem = groupThemeItems.get(section);
if (groupThemeItem != null) {
int size = groupThemeItem.getCustomThemeItems().size();
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()){
return size == 0 ? 0 : (size > 6 ? 6 : size);
}
return size == 0 ? 1 : (size > 6 ? 6 : size);
}
}
return 0;
}
@Override
public int getItemViewType(int section, int relativePosition, int absolutePosition) {
if (section == 1 || section == 7) {
return AD_ITEM;
}
return super.getItemViewType(section, relativePosition, absolutePosition);
}
@Override
public void onBindHeaderViewHolder(ItemViewHolder holder, int section) {
final GroupThemeItem groupThemeItem = groupThemeItems.get(section);
final String groupName = groupThemeItem.getGroupName();
final ArrayList<CustomThemeItem> items = groupThemeItem.getCustomThemeItems();
RecyclerView.LayoutParams param = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
if (groupName != null && groupName.length() > 0) {
holder.itemView.setVisibility(View.VISIBLE);
holder.title.setText(groupName);
if (items != null && items.size() > 6) {
holder.ll_title_more.setVisibility(View.VISIBLE);
holder.ll_title_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ThemeMoreActivity.class);
intent.putExtra(ThemeMoreActivity.GROUP_NAME, groupName);
intent.putParcelableArrayListExtra(ThemeMoreActivity.THEMES, items);
startActivity(intent);
}
});
} else {
holder.ll_title_more.setVisibility(View.GONE);
}
param.height = LinearLayout.LayoutParams.WRAP_CONTENT;
param.width = LinearLayout.LayoutParams.MATCH_PARENT;
} else {
holder.itemView.setVisibility(View.GONE);
param.height = 0;
param.width = 0;
}
/** 此处处理推荐位标签下无文件 **/
if (groupThemeItem.getCustomThemeItems().size() == 0){
holder.itemView.setVisibility(View.GONE);
param.height = 0;
param.width = 0;
}
holder.itemView.setLayoutParams(param);
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int section, int relativePosition, int absolutePosition) {
switch (holder.mViewType) {
case THEME_ITEM: {
final ArrayList<CustomThemeItem> customThemeItems = groupThemeItems.get(section).getCustomThemeItems();
if (customThemeItems.size() == 0){
holder.itemView.setVisibility(View.GONE);
return;
}else {
holder.itemView.setVisibility(View.VISIBLE);
}
getThemeItemHolder(holder, relativePosition, customThemeItems);
}
break;
case AD_ITEM: {
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()) return;
getAdItemHolder(holder, section);
}
break;
}
}
private void getThemeItemHolder(final ItemViewHolder holder, final int position, final ArrayList<CustomThemeItem> customThemeItems) {
final CustomThemeItem customThemeItem = customThemeItems.get(position);
//设置选中状态
setThemeType(holder, customThemeItem);
//设置键盘图片背景
if (customThemeItem.getPreviewPhotoPath().startsWith("http://")) {
holder.mBgImageView.setImageURI(Uri.parse(customThemeItem.getPreviewPhotoPath()));
} else {
int drawableId = ThemeTools.getDrawableId(getActivity(), customThemeItem.getPreviewPhotoPath());
holder.mBgImageView.setImageURI(Uri.parse("res:///" + drawableId));
}
holder.title.setText(customThemeItem.getThemeName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleItemClick(customThemeItem);
}
});
}
private void setThemeType(ItemViewHolder holder, CustomThemeItem customThemeItem) {
int themeType = customThemeItem.getType();
//如果是广告
if (themeType == CustomThemeItem.ThemeType.FEATURED) {
holder.iv_type_ad.setVisibility(View.VISIBLE);
holder.iv_type_ad.setImageResource(R.drawable.foto_ad_choice);
holder.iv_theme_type.setVisibility(View.GONE);
return;
}
holder.iv_type_ad.setVisibility(View.GONE);
//1 如果是选中
if (customThemeItem.getThemeId() == mCurrentCheckedTheme) {
// holder.iv_foto_theme_type.setImageResource(R.drawable.foto_theme_item_current);
holder.iv_theme_type.setVisibility(View.GONE);
holder.iv_type_ad.setVisibility(View.VISIBLE);
holder.iv_type_ad.setImageResource(R.drawable.res_theme_using);
}
//2 未选中,是本地
else if (themeType == CustomThemeItem.ThemeType.DEFAULT) {
holder.iv_theme_type.setVisibility(View.GONE);
}
//3 未选中,不是本地
else {
boolean apkInstalled = PackageUtil.isApkInstalled(mContext, customThemeItem.getThemePackageName());
if (apkInstalled) { //如果皮肤包已安装
holder.iv_theme_type.setVisibility(View.GONE);
} else {
holder.iv_theme_type.setImageResource(R.drawable.foto_theme_item_download);
holder.iv_theme_type.setVisibility(View.VISIBLE);
}
}
}
private void handleItemClick(CustomThemeItem customThemeItem) {
if (customThemeItem.getType() == CustomThemeItem.ThemeType.DEFAULT) {
if (!ThemeUtil.isActivateThemeOrNot(getContext())) {
return;
}
// 上一个id
int lastThemeId = mCurrentCheckedTheme;
mCurrentCheckedTheme = customThemeItem.getThemeId();
if (lastThemeId == mCurrentCheckedTheme) {
if (isKeyboardHideByTouch) {
isKeyboardHideByTouch = false;
} else {
SoftInputUtil.toggleSoftInput(mContext);
}
return;
}
KeyboardTheme.saveKeyboardThemeId("" + mCurrentCheckedTheme, mThemePrefs);
EmojiViewManager.getInstance().clear();
updateByItemChecked();
KeyboardLayoutSet.onKeyboardThemeChanged();
// 清空自定义壁纸
mThemePrefs.edit().putString(ThemeConstant.DIY_BACKGROUND_PATH, "").apply();
// 清空apk主题
ThemeResourceManager.getInstance().clearApkResource();
// 统计切换主题
HashMap<String, String> hashMap = new HashMap();
hashMap.put("lastThemeId", (1000 + lastThemeId) + "");
hashMap.put("currentThemeId", (1000 + mCurrentCheckedTheme) + "");
// FlurryAgent.logEvent(DataCollectConstant.SWITCH_THEMES, hashMap);
if (Fabric.isInitialized()) {
final CustomEvent customEvent = new CustomEvent(DataCollectConstant.SWITCH_THEMES);
customEvent.putCustomAttribute("lastThemeId", (1000 + lastThemeId) + "");
customEvent.putCustomAttribute("currentThemeId", (1000 + mCurrentCheckedTheme) + "");
Answers.getInstance().logCustom(customEvent);
}
SoftInputUtil.toggleSoftInput(mContext);
// 推荐位
} else if (customThemeItem.getType() == CustomThemeItem.ThemeType.FEATURED) {
// 统计推荐位
MobileUtil.dataCollectLog(DataCollectConstant.FEATURE_OTHER_APP);
ThemeTools.openUrl(getActivity(), customThemeItem.getDownloadUrl());
} else if (customThemeItem.getType() == CustomThemeItem.ThemeType.DOWNLOAD_WALLPAPER) {
} else if (customThemeItem.getType() == CustomThemeItem.ThemeType.DIY_WALLPAPER) {
} else if (customThemeItem.getType() == CustomThemeItem.ThemeType.APK_THEME) {
boolean apkInstalled = PackageUtil.isApkInstalled(mContext, customThemeItem.getThemePackageName());
if (apkInstalled) {
if (!ThemeUtil.isActivateThemeOrNot(getContext())) {
return;
}
// 上一个id
int lastThemeId = mCurrentCheckedTheme;
mCurrentCheckedTheme = customThemeItem.getThemeId();
if (lastThemeId == mCurrentCheckedTheme) {
if (isKeyboardHideByTouch) {
isKeyboardHideByTouch = false;
} else {
SoftInputUtil.toggleSoftInput(mContext);
}
if (ThemeResourceManager.getInstance().getApkRescourceUtil() != null)
return;
}
final Context packageNameContext = ThemeTools.getPackageNameContext(customThemeItem.getThemePackageName());
if (packageNameContext == null) return;
// 如果上一个资源是主题包,清空
if (ThemeResourceManager.getInstance().getApkRescourceUtil() != null) {
ThemeResourceManager.getInstance().getApkRescourceUtil().clearResource();
}
// 清空自定义壁纸
mThemePrefs.edit().putString(ThemeConstant.DIY_BACKGROUND_PATH, "").apply();
// 持久化包名,id
ThemeResourceManager.getInstance().setApkRescourceUtil(new APKRescourceUtil(packageNameContext));
EmojiViewManager.getInstance().clear();
updateByItemChecked();
KeyboardLayoutSet.onKeyboardThemeChanged();
// 刷新主题
getContext().sendBroadcast(new Intent(ThemeConstant.UPDATE_THEME_ACTION));
// 统计切换主题
HashMap<String, String> hashMap = new HashMap();
hashMap.put("lastThemeId", (1000 + lastThemeId) + "");
hashMap.put("currentThemeId", (1000 + mCurrentCheckedTheme) + "");
// FlurryAgent.logEvent(DataCollectConstant.SWITCH_THEMES, hashMap);
if (Fabric.isInitialized()) {
final CustomEvent customEvent = new CustomEvent(DataCollectConstant.SWITCH_THEMES);
customEvent.putCustomAttribute("lastThemeId", (1000 + lastThemeId) + "");
customEvent.putCustomAttribute("currentThemeId", (1000 + mCurrentCheckedTheme) + "");
Answers.getInstance().logCustom(customEvent);
}
SoftInputUtil.toggleSoftInput(mContext);
} else {
// ThemeTools.openUrl(getActivity(), customThemeItem.getDownloadUrl());
DownloadThemeUtil.downloadHandle(getContext(), customThemeItem);
}
} else {
}
}
private void getAdItemHolder(final ItemViewHolder holder, final int position) {
if (position == 1) {
// if (AdCache.mThemeMiddleAdView == null) {
// AdCache.mThemeMiddleAdView = new AnimateNativeAdViewLayout(FotoApplication.getInstance(),
// new BigAdViewInMainInterfaceBottom(FotoApplication.getInstance()),
// MutableConstants.AD_THEME_MIDDLE, null);
//
// }
// holder.adContainer.removeAllViews();
// ViewGroup viewGroup = (ViewGroup) AdCache.mThemeMiddleAdView.getParent();
// if (viewGroup != null) {
// viewGroup.removeAllViews();
// }
// holder.adContainer.addView(AdCache.mThemeMiddleAdView);
// holder.adContainer.setVisibility(View.VISIBLE);
} else if (position == 7) {
// if (AdCache.mThemeBottomAdView == null) {
// AdCache.mThemeBottomAdView = new AnimateNativeAdViewLayout(FotoApplication.getInstance(),
// new BigAdViewInMainInterfaceBottom(FotoApplication.getInstance()),
// MutableConstants.AD_THEME_BOTTOM, null);
// }
// holder.adContainer.removeAllViews();
// ViewGroup viewGroup = (ViewGroup) AdCache.mThemeBottomAdView.getParent();
// if (viewGroup != null) {
// viewGroup.removeAllViews();
// }
// holder.adContainer.addView(AdCache.mThemeBottomAdView);
// holder.adContainer.setVisibility(View.VISIBLE);
}
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
switch (viewType) {
case THEME_ITEM: {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_resource_list_item, parent, false);
}
break;
case AD_ITEM: {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_theme_ad_item, parent, false);
}
break;
case THEME_SELECTION_TITLE: {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_theme_selection_title, parent, false);
}
break;
}
return new ItemViewHolder(view, viewType);
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
SimpleDraweeView mBgImageView;
ImageView iv_theme_type;
ImageView iv_type_ad;
TextView title;
LinearLayout ll_title_more;
ViewGroup adContainer;
public int mViewType;
public ItemViewHolder(View view, int type) {
super(view);
mViewType = type;
if (mViewType == THEME_ITEM) {
mBgImageView = (SimpleDraweeView) itemView.findViewById(R.id.res_theme_center_ic);
// 设置placeHolder
try{
GenericDraweeHierarchy hierarchy = mBgImageView.getHierarchy();
hierarchy.setPlaceholderImage(R.drawable.foto_image_loading);
}catch (Exception e){
mBgImageView.getHierarchy().setPlaceholderImage(new ColorDrawable(Color.parseColor("#b3767676")));
}catch (OutOfMemoryError error){
mBgImageView.getHierarchy().setPlaceholderImage(new ColorDrawable(Color.parseColor("#b3767676")));
}
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getItemHight());
mBgImageView.setLayoutParams(layoutParams);
iv_theme_type = (ImageView) itemView.findViewById(R.id.iv_foto_theme_type);
iv_type_ad = (ImageView) itemView.findViewById(R.id.iv_foto_resource_item_type_ad);
title = (TextView) itemView.findViewById(R.id.res_theme_name);
} else if (mViewType == THEME_SELECTION_TITLE) {
title = (TextView) itemView.findViewById(R.id.foto_theme_selection_title);
ll_title_more = (LinearLayout) itemView.findViewById(R.id.ll_foto_theme_selection_more);
} else if (mViewType == AD_ITEM){
adContainer = (ViewGroup) itemView.findViewById(R.id.foto_bottom_adview);
/** 是否移除广告 **/
if (SharedPreferenceHelper.hasRemoveAd()){
adContainer.setVisibility(View.GONE);
}
}
}
private int getItemHight() {
int displayWidth = MobileUtil.getDisplayWidth(mContext);
int itemWidth = (displayWidth - MobileUtil.dp2px(mContext, 44)) / 2;
return (int) (itemWidth * IMAGE_RATE / 100);
}
}
}
class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpaceItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) != 0)
outRect.top = space;
}
}
}
|
package com.yoti.api.client.spi.remote;
import static org.junit.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import org.junit.Before;
import org.junit.Test;
import com.yoti.api.client.Date;
public class DateAttributeValueTest {
private static final String VALID_DATE_STRING = "2016-05-01";
private byte[] VALID_DATE_BYTES;
private static final String INVALID_DATE_VALUE_STRING = "2016-13-01";
private static final String INVALID_DATE_FORMAT_STRING = "2016-MAR-01";
@Before
public void before() throws UnsupportedEncodingException {
VALID_DATE_BYTES = VALID_DATE_STRING.getBytes("UTF-8");
}
@Test
public void parseFrom_shouldParseValidString() throws UnsupportedEncodingException, ParseException {
DateAttributeValue date = DateAttributeValue.parseFrom(VALID_DATE_STRING);
assertDate(date);
}
@Test
public void parseFrom_shouldParseValidArray() throws UnsupportedEncodingException, ParseException {
DateAttributeValue date = DateAttributeValue.parseFrom(VALID_DATE_BYTES);
assertDate(date);
}
@Test(expected = ParseException.class)
public void parseFrom_shouldNotParseInvalidDateFormat() throws UnsupportedEncodingException, ParseException {
DateAttributeValue.parseFrom(INVALID_DATE_FORMAT_STRING);
}
@Test(expected = ParseException.class)
public void parseFrom_shouldNotParseInvalidDateValue() throws UnsupportedEncodingException, ParseException {
DateAttributeValue.parseFrom(INVALID_DATE_VALUE_STRING);
}
@Test
public void toString_shouldFormatDateCorrectly() throws UnsupportedEncodingException, ParseException {
DateAttributeValue date = DateAttributeValue.parseFrom(VALID_DATE_STRING);
String result = date.toString();
assertEquals(VALID_DATE_STRING, result);
}
private void assertDate(Date date) {
assertEquals(2016, date.getYear());
assertEquals(5, date.getMonth());
assertEquals(1, date.getDay());
}
}
|
/*
* Created on Mar 2, 2007
*
*/
package com.citibank.ods.modules.client.customerprvtcmpl.functionality.valueobject;
/**
* @author bruno.zanetti
*
*/
public class CustomerPrvtCmplMovementListFncVO extends BaseCustomerPrvtCmplListFncVO
{
private String m_lastUpdUserIdSrc;
public static final String C_LAST_UPD_USER_ID_DESCRIPTION = "Usuário";
/**
* @return Returns lastUpdUserIdSrc.
*/
public String getLastUpdUserIdSrc()
{
return m_lastUpdUserIdSrc;
}
/**
* @param lastUpdUserIdSrc_ Field lastUpdUserIdSrc to be setted.
*/
public void setLastUpdUserIdSrc( String lastUpdUserIdSrc_ )
{
m_lastUpdUserIdSrc = lastUpdUserIdSrc_;
}
}
|
package utils;
import java.io.IOException;
import javax.servlet.http.*;
import javax.servlet.jsp.PageContext;
public class Util {
public static int parseIntOr(String str, int value) {
if ( !(str == "" || str == null) ) {
value = Integer.parseInt(str);
}
return value;
}
public static void sendErr(PageContext pageContext, Exception err) {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
HttpSession session = pageContext.getSession();
session.setAttribute("err", err);
String ctxPath = request.getContextPath();
try {
response.sendRedirect(ctxPath + "/error.jsp");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void redirectLogin(PageContext pageContext) {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
String ctxPath = request.getContextPath();
try {
response.sendRedirect(ctxPath + "/login.jsp");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String nullToBlank(String str) {
if (str == null) str = "";
return str;
}
}
|
package com.txxlc.utils;
import java.util.Random;
/**
*qq登陆时生成随机密码的方法
* */
public class PasswordGenerator {
public String passwordGenerator(){
String password="";
char[] en ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
Random random = new Random();
for(int i=0;i<6;i++){
password=password+en[ random.nextInt(51)];
}
return password;
}
}
|
package com.atlassian.bitbucket.jenkins.internal.client;
import com.atlassian.bitbucket.jenkins.internal.model.BitbucketRepository;
/**
* Repository client, used to interact with a remote repository for all operations except cloning
* source code.
*/
public interface BitbucketRepositoryClient extends BitbucketClient<BitbucketRepository> {
}
|
package com.carlos.theculinaryapp;
public class RecipeItem {
private String name;
private String imageFile;
private String recipeUuid;
private String ownerUuid;
public String getOwnerUuid() {
return ownerUuid;
}
public void setOwnerUuid(String ownerUuid) {
this.ownerUuid = ownerUuid;
}
public RecipeItem(String name, String imageFile) {
this.name = name;
this.imageFile = imageFile;
}
public String getName() {
return name;
}
public String getImageFile() {
return imageFile;
}
public String getRecipeUuid() {
return recipeUuid;
}
public void setRecipeUuid(String s){
recipeUuid = s;
}
}
|
package com.javawebtutor.Controllers.ClientControllers;
import com.javawebtutor.Controllers.Controller;
import com.javawebtutor.Controllers.LogInController;
import com.javawebtutor.Models.*;
import com.javawebtutor.Models.Classes.ClientCarCheck;
import com.javawebtutor.Utilities.HibernateUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ClientCheckCarRepairStateController extends Controller implements Initializable{
@FXML private TableView<ClientCarCheck> tv1;
@FXML private TableColumn<ClientCarCheck, String> tab1;
@FXML private TableColumn<ClientCarCheck, String> tab2;
@FXML private TableColumn<ClientCarCheck, String> tab3;
@FXML private TableColumn<ClientCarCheck, String> tab4;
@FXML private TableColumn<ClientCarCheck, String> tab5;
SessionFactory factory = HibernateUtil.getSessionFactory();
private ObservableList<ClientCarCheck> personData = FXCollections.observableArrayList();
public void initialize(URL location, ResourceBundle resources) {
Session session = factory.getCurrentSession();
session.getTransaction().begin();
Users user;
user = session.get(Users.class, LogInController.loggedUserId);
tv1.setItems(personData);
for (Cars car : user.getCars()) {
Repairs r1;
RepairsState rs1;
r1 = session.get(Repairs.class, car.getCars());
rs1 = session.get(RepairsState.class, r1.getRepairId());
ClientCarCheck a = new ClientCarCheck(
car.getCarModels().getCarMarks().getMarkName(),
car.getCarModels().getModelName(),
r1.getRepairCauses(),
rs1.getStates().getName(),
r1.getPrice()
);
// System.out.println(car.getCarModels().getCarMarks().getMarkName() + " " + car.getCarModels().getModelName() + " " + r1.getRepairCauses() + " " + rs1.getStates().getName() + " " + r1.getPrice());
tab1.setCellValueFactory(new PropertyValueFactory<>("mark"));
tab2.setCellValueFactory(new PropertyValueFactory<>("model"));
tab3.setCellValueFactory(new PropertyValueFactory<>("repairCauses"));
tab4.setCellValueFactory(new PropertyValueFactory<>("state"));
tab5.setCellValueFactory(new PropertyValueFactory<>("price"));
personData.add(a);
}
session.close();
}
public void backButton(ActionEvent event) throws IOException {
this.changeScene(event, "/ClientMainScene.fxml");
}
}
|
package cr.ac.tec.ce1103.structures.trees;
/**
*
* @author Adrian Sanchez
*
*/
public class NodoAVLTree <AnyType extends Comparable>{
public int dato, fe;
NodoAVLTree hijoIzquierdo, hijoDerecho;
NodoAVLTree(AnyType d) {
this.dato = (int) d;
this.fe = 0;
this.hijoDerecho = null;
this.hijoIzquierdo = null;
}
//
}
|
package com.appspot.smartshop.map;
import java.util.List;
import java.util.Set;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.appspot.smartshop.R;
import com.appspot.smartshop.ui.product.ProductsListActivity;
import com.appspot.smartshop.ui.product.SelectTwoProductActivity;
import com.appspot.smartshop.utils.CategoriesDialog;
import com.appspot.smartshop.utils.Global;
import com.appspot.smartshop.utils.CategoriesDialog.CategoriesDialogListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class DirectionOnMapActivity extends MapActivity {
private static MapView mapView;
private static MapController mapController;
private static DirectionOverlay directionOverlay;
public static DirectionResult directionResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.direction);
// setup view
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// overlay
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
if (directionOverlay == null) {
directionOverlay = new DirectionOverlay();
}
directionOverlay.points = directionResult.points;
listOfOverlays.add(directionOverlay);
// calculate lat, lng span
int lattitude;
int longtitude;
int maxLat = Integer.MIN_VALUE;
int minLat = Integer.MAX_VALUE;
int maxLong = Integer.MIN_VALUE;
int minLong = Integer.MAX_VALUE;
for (GeoPoint p: directionOverlay.points) {
lattitude = p.getLatitudeE6();
longtitude = p.getLongitudeE6();
if (minLat > lattitude) {
minLat = lattitude;
}
if (maxLat < lattitude) {
maxLat = lattitude;
}
if (minLong > longtitude) {
minLong = longtitude;
}
if (maxLong < longtitude) {
maxLong = longtitude;
}
}
// controller
mapController = mapView.getController();
GeoPoint center = new GeoPoint((maxLat + minLat) / 2, (maxLong + minLong) / 2);
mapController.animateTo(center);
mapController.zoomToSpan(maxLat - minLat, maxLong - minLong);
// redraw map
mapView.invalidate();
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
public static final int MENU_VIEW_DIRECTION_DETAIL = 1;
public static final int MENU_VIEW_ROAD_DETAIL = 2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_VIEW_DIRECTION_DETAIL, 0,
getString(R.string.view_direction_detail));
menu.add(0, MENU_VIEW_ROAD_DETAIL, 0,
getString(R.string.view_road_detail));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_VIEW_ROAD_DETAIL:
if (directionResult.points.size() >= 2) {
int lat1 = directionResult.points.get(0).getLatitudeE6();
int lng1 = directionResult.points.get(0).getLongitudeE6();
int lat2 = directionResult.points.get(1).getLatitudeE6();
int lng2 = directionResult.points.get(1).getLongitudeE6();
mapController.animateTo(new GeoPoint((lat1 + lat2) / 2, (lng1 + lng2) / 2) );
mapController.zoomToSpan(Math.abs(lat1 - lat2), Math.abs(lng1 - lng2));
}
break;
case MENU_VIEW_DIRECTION_DETAIL:
Intent intent = new Intent(getApplicationContext(), DirectionListActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
|
public class CalculadoraDePrecoDeVendas {
private double totalDeProdutosEmEstoque=0;
public void acumulaValorDosProdutos(Produto p){
this.totalDeProdutosEmEstoque += p.getValorEmMercadoria();
}
public double getTotalDeProdutosEmEstoque() {
return totalDeProdutosEmEstoque;
}
}
|
package com.alura.exception;
public class CursoNotFoundException extends RuntimeException{
public CursoNotFoundException(String message){
super(message);
}
}
|
package data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class QueryFileDAO implements QueryDAO {
private static final String url = "jdbc:mysql://localhost:3306/sdvid";
private static final String user = "student";
private static final String pword = "student";
@Override
public List<List<String>> getQueryInfo(String info) {
List<List<String>> statement = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pword);
Statement stmt = conn.createStatement();
int count = 0;
if (info.trim().toUpperCase().startsWith("SELECT")) {
ResultSet rs = stmt.executeQuery(info);
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
List<String> queries = new ArrayList<>();
for (int c = 1; c <= cols; c++) {
queries.add(rsmd.getColumnName(c));
}
statement.add(queries);
while (rs.next())
{
queries = new ArrayList<>();
for (int c = 0; c < cols; c++)
{
queries.add(rs.getString(c + 1));
}
statement.add(queries);
}
}
else
{
count = stmt.executeUpdate(info);
List<String> queries = new ArrayList<>();
queries.add(""+ count);
statement.add(queries);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
catch (ClassNotFoundException cnf)
{
cnf.printStackTrace();
}
return statement;
}
}
|
package msip.go.kr.message.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import com.ibm.icu.text.SimpleDateFormat;
import msip.go.kr.message.NuriMsgData;
/**
* 본부 조직도 데이터 처리를 위한 DAO 클래스 정의
*
* @author 정승철
* @since 2015.07.09
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.09 정승철 최초생성
*
* </pre>
*/
@Repository("nuriMsgDAO")
public class NuriMsgDAO {
/**
* @PersistenceContext 어노테이션을 이용하여 컨테이너로부터 EntityManger DI
* @param EntityManager em
*/
@PersistenceContext
private EntityManager em;
public int insertMsgData(NuriMsgData vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("INSERT INTO nuri_msg_data (REQ_DATE, CUR_STATE, CALL_TO, CALL_FROM, SMS_TXT, MSG_TYPE) ").append(ls);
hql.append("VALUES (:reqDate, :curState, :callTo, :callFrom, :smsTxt, :msgType) ").append(ls);
Query query = em.createNativeQuery(hql.toString());
query.setParameter("reqDate", vo.getReqDate());
query.setParameter("curState", vo.getCurState());
query.setParameter("callTo", vo.getCallTo());
query.setParameter("callFrom", vo.getCallFrom());
query.setParameter("smsTxt", vo.getSmsTxt());
query.setParameter("msgType", vo.getMsgType());
int result = query.executeUpdate();
return result;
}
@SuppressWarnings("unchecked")
public List<NuriMsgData> findAll(String status) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
String curDate = new SimpleDateFormat("yyyyMM").format(new java.util.Date());
if (curDate.equals(status)) {
hql.append("SELECT MSG_SEQ, REQ_DATE, CUR_STATE, CALL_TO, CALL_FROM, SMS_TXT, MSG_TYPE, RSLT_CODE, RSLT_CODE2 ").append(ls);
hql.append("FROM ").append(ls);
hql.append("( ").append(ls);
hql.append("SELECT MSG_SEQ, REQ_DATE, CUR_STATE, CALL_TO, CALL_FROM, SMS_TXT, MSG_TYPE, RSLT_CODE, RSLT_CODE2 ").append(ls);
hql.append("FROM nuri_msg_data").append(ls);
hql.append("UNION ").append(ls);
hql.append("SELECT MSG_SEQ, REQ_DATE, CUR_STATE, CALL_TO, CALL_FROM, SMS_TXT, MSG_TYPE, RSLT_CODE, RSLT_CODE2 ").append(ls);
hql.append("FROM nuri_msg_log_"+ status).append(ls);
hql.append(") ").append(ls);
hql.append("ORDER BY REQ_DATE ").append(ls);
} else {
hql.append("SELECT MSG_SEQ, REQ_DATE, CUR_STATE, CALL_TO, CALL_FROM, SMS_TXT, MSG_TYPE, RSLT_CODE, RSLT_CODE2 ").append(ls);
hql.append("FROM nuri_msg_log_"+ status).append(ls);
hql.append("ORDER BY REQ_DATE ").append(ls);
}
Query query = em.createNativeQuery(hql.toString());
List<NuriMsgData> list = new ArrayList<NuriMsgData>();
List<Object[]> result = query.getResultList();
for(Object[] row : result) {
BigDecimal msgSeq = (BigDecimal) row[0];
Date reqDate = (Date) row[1];
BigDecimal curState = (BigDecimal) row[2];
String callTo = (String) row[3];
String callFrom = (String) row[4];
String smsTxt = (String) row[5];
BigDecimal msgType = (BigDecimal) row[6];
BigDecimal rsltCode = (BigDecimal) row[7];
Character rsltCode2 = (Character) row[8];
NuriMsgData entity = new NuriMsgData();
entity.setMsgSeq(msgSeq.longValue());
entity.setReqDate(reqDate);
if (curState != null)
entity.setCurState(curState.longValue());
entity.setCallTo(callTo);
entity.setCallFrom(callFrom);
entity.setSmsTxt(smsTxt);
if (msgType != null)
entity.setMsgType(msgType.longValue());
if (rsltCode != null)
entity.setRsltCode(rsltCode.longValue());
if (rsltCode2 != null)
entity.setRsltCode2(rsltCode2.toString());
list.add(entity);
}
return list;
}
}
|
package org.systemsbiology.gaggle.cereopsis.core;
import org.apache.activemq.spring.ActiveMQConnectionFactory;
import org.systemsbiology.gaggle.core.datatypes.Namelist;
import org.systemsbiology.gaggle.core.datatypes.Network;
import org.systemsbiology.gaggle.core.datatypes.Cluster;
import org.systemsbiology.gaggle.core.datatypes.DataMatrix;
import org.systemsbiology.gaggle.cereopsis.serialization.GaggleNetworkToCompactNetworkConverter;
import org.systemsbiology.gaggle.cereopsis.serialization.CompactNetwork;
import org.systemsbiology.gaggle.cereopsis.serialization.CompactNetworkSerializer;
import org.systemsbiology.gaggle.cereopsis.serialization.SerializableDataMatrix;
import javax.jms.*;
import net.sf.json.JSONObject;
import java.util.Map;
import java.util.HashMap;
/*
* Copyright (C) 2009 by Institute for Systems Biology,
* Seattle, Washington, USA. All rights reserved.
*
* This source code is distributed under the GNU Lesser
* General Public License, the text of which is available at:
* http://www.gnu.org/copyleft/lesser.html
*/
public class GaggleProducer {
Connection connection;
Destination destination;
Session session;
MessageProducer producer;
public GaggleProducer() {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic("Broadcast");
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // for now
System.out.println("Ready for Gaggle broadcasts");
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendNamelist(Namelist namelist, String source) {
JSONObject jsonObject = JSONObject.fromObject(namelist);
String json = jsonObject.toString();
sendMessage("Namelist", json, source);
}
protected void sendMessage(String messageType, String messageBody, String source) {
try {
TextMessage message = session.createTextMessage(messageBody);
message.setStringProperty("MessageType",messageType);
message.setStringProperty("Source", source);
producer.send(message);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendNetwork(Network network, String source) {
GaggleNetworkToCompactNetworkConverter converter = new GaggleNetworkToCompactNetworkConverter(network);
CompactNetwork cn = converter.toCompactNetwork();
String json = CompactNetworkSerializer.serializeToJSON(cn);
sendMessage("Network", json, source);
}
public void sendCluster(Cluster cluster, String source) {
sendMessage("Cluster", JSONObject.fromObject(cluster).toString(), source);
}
public void sendMatrix(DataMatrix matrix, String source) {
SerializableDataMatrix sdm = new SerializableDataMatrix(matrix);
JSONObject jsonObject = JSONObject.fromObject(sdm);
sendMessage("DataMatrix", jsonObject.toString(), source);
}
public void sendGooseList(String[] gooseNames) {
Map<String,String[]> map = new HashMap<String, String[]>();
map.put("GooseList", gooseNames);
sendMessage("GooseList", JSONObject.fromObject(map).toString(), null);
}
public void sendGooseName(String gooseName, String[] gooseNames) {
if (gooseNames != null)sendGooseList(gooseNames);
Map<String,String> map = new HashMap<String,String>();
map.put("GooseName", gooseName);
sendMessage("GooseName", JSONObject.fromObject(map).toString(), null);
}
}
|
package ca.kitamura.simpleaddressbook.networking;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Darren on 2016-12-13.
*/
//Retrofit creation is costly, make it static and do it once...
public final class NetworkingService {
private NetworkingService(){
}
static RandomUserApi randomUserApi;
private static String BASE_URL = "https://randomuser.me/api/";
private static RandomUserApi getRandomUserApi() {
RandomUserApi retrofit = new Retrofit.Builder()
.client(getClient())
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(RandomUserApi.class);
return retrofit;
}
private static OkHttpClient getClient () {
OkHttpClient client = new OkHttpClient.Builder()
.build();
return client;
}
public static RandomUserApi getRandomUserService() {
if(randomUserApi == null) {
randomUserApi = getRandomUserApi();
}
return randomUserApi;
}
}
|
package com.tqb.service.question;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tqb.interfaces.question.QuestionService;
import com.tqb.mapper.ContenMapper;
import com.tqb.mapper.ContentAnswerMapper;
import com.tqb.mapper.QuestionnaireMapper;
import com.tqb.pojo.Conten;
import com.tqb.pojo.ContenExample;
import com.tqb.pojo.ContentAndAnswer;
import com.tqb.pojo.ContentAnswer;
import com.tqb.pojo.ContentAnswerExample;
import com.tqb.pojo.QuesAndContentAndAnswer;
import com.tqb.pojo.Questionnaire;
import com.tqb.pojo.QuestionnaireExample;
import com.tqb.pojo.QuestionnaireExample.Criteria;
import com.tqb.utils.CommonUtils;
import com.tqb.utils.PageBean;
@Service
public class QuestionServiceImpl implements QuestionService {
@Autowired
private QuestionnaireMapper mapper;
@Autowired
private ContenMapper contentMapper;
@Autowired
private ContentAnswerMapper answerMapper;
@Override
public PageBean<Questionnaire> list(String uid, int currentPage, int pageSize) {
// 分页
PageBean<Questionnaire> pagebean = new PageBean<Questionnaire>();
// 使用分页工具进行分页
PageHelper.startPage(currentPage, pageSize);
QuestionnaireExample example = new QuestionnaireExample();
Criteria criteria = example.createCriteria();
criteria.andUIdEqualTo(uid);
List<Questionnaire> list = mapper.selectByExample(example);
PageInfo<Questionnaire> pageinfo = new PageInfo<Questionnaire>(list);
pagebean.setRecordCount((int) pageinfo.getTotal());// 总记录数
pagebean.setCurrentPage(currentPage);// 当前页
pagebean.setPageSize(pageinfo.getSize());// 当前页大小
pagebean.setRecordList(pageinfo.getList());// 每页数据
pagebean.setPageCount(pageinfo.getPages());// 总页数
return pagebean;
}
/**
* 一定要加入主键返回,这里是操作了三张表
*/
@Override
public void add(Questionnaire ques, List<Conten> contentList, List<List<ContentAnswer>> answerList) {
// 生成uuid
String qid = CommonUtils.uuid();
ques.setqId(qid);
// 添加问卷信息
mapper.insert(ques);
// 添加问题信息 主键返回
int count = 0;// 用于判断题目与答案的对应关系
for (Conten c : contentList) {
c.setqId(qid);
contentMapper.insert(c);
Integer c_id = c.getcId();
List<ContentAnswer> list = answerList.get(count);
for (ContentAnswer ca : list) {
ca.setcId(c_id);
answerMapper.insert(ca);
}
count++;
}
}
@Override
public QuesAndContentAndAnswer papermakeing(String qid) {
// 自定义的试卷POJO
QuesAndContentAndAnswer qca = new QuesAndContentAndAnswer();
// 通过qid查询问卷标题和题目
qca.setQid(qid);
Questionnaire questionnaire = mapper.selectByPrimaryKey(qid);
String qName = questionnaire.getqName();// 试卷标题
qca.setQuesname(qName);
ContenExample example = new ContenExample();
example.createCriteria().andQIdEqualTo(qid);
List<Conten> contentList = contentMapper.selectByExample(example);
List<ContentAndAnswer> answerList = new ArrayList<>();
for (Conten conten : contentList) {
ContentAnswerExample example1 = new ContentAnswerExample();
example1.createCriteria().andCIdEqualTo(conten.getcId());
List<ContentAnswer> answer = answerMapper.selectByExample(example1 );
ContentAndAnswer ca = new ContentAndAnswer();
ca.setName(conten.getcTitle());// 问题题目
ca.setAnswerList(answer);// 问题答案
answerList.add(ca);
}
qca.setAnswerList(answerList);
return qca;
}
@Override
public void closeOropen(String qid, Boolean state) {
Questionnaire ques = mapper.selectByPrimaryKey(qid);
if (state)// 若服务打开则关闭
ques.setqState(false);
else// 若服务关闭则打开
ques.setqState(true);
mapper.updateByPrimaryKey(ques);
}
@Override
public boolean isOpen(String qid) {
Questionnaire q = mapper.selectByPrimaryKey(qid);
return q.getqState();
}
@Override
public String getNameById(String qid) {
Questionnaire q = mapper.selectByPrimaryKey(qid);
return q.getqName();
}
// TODO 删除功能有问题
@Override
public boolean delete(String qid) {
/*ContenExample example = new ContenExample();
example.createCriteria().andQIdEqualTo(qid);
// 查询问卷是否存在级联信息
List<Conten> list = contentMapper.selectByExample(example);*/
int key = mapper.deleteByPrimaryKey(qid);
if(key == 0)
return false;
else
return true;
}
@Override
public void update(String qid, String type, String value) {
Questionnaire ques = mapper.selectByPrimaryKey(qid);
if (type.equals("qName")){
ques.setqName(value);
}else if (type.equals("qCount")){
ques.setqCount(Integer.valueOf(value));
}else{// if (type.equals("qRemark"))
ques.setqRemark(value);
}
mapper.updateByPrimaryKey(ques);
}
}
|
package com.noobs2d.superawesomejetgame;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
public class SuperAwesomeJetGame extends Game {
@Override
public void create() {
setScreen(new StageScreen(this));
}
@Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
super.render();
}
}
|
package Roman;
import java.util.Scanner;
public class RomanNumeralCalculator
{
private Scanner keyboard = new Scanner(System.in);
/**
* Asks the user if they want to add, subtract, multiply, or divide.
* Prompts the user to enter two Roman Numbers, does the arithmetic
* and creates a new Roman Numeral with the value then displays the
* answer in both additive and subtractive form.
*/
public void doCalculation()
{
while(true)
{
char operator = getOperator();
RomanNumeral Answer;
RomanNumeral operand1 = new RomanNumeral();
RomanNumeral operand2 = new RomanNumeral();
if (Character.toLowerCase(operator) == 'q')
{
System.out.println("Exiting...");
return;
}
operand1.getRomanNumeral();
System.out.print(operator + "\n");
operand2.getRomanNumeral();
switch(operator)
{
case '+':
{
Answer = new RomanNumeral(operand1.toInt() + operand2.toInt());
break;
}
case '-':
{
Answer = new RomanNumeral(operand1.toInt() - operand2.toInt());
break;
}
case '*':
{
Answer = new RomanNumeral(operand1.toInt() * operand2.toInt());
break;
}
case '/':
{
Answer = new RomanNumeral(operand1.toInt() / operand2.toInt());
break;
}
default:
{
System.out.println("Fatal Error! (THIS SHOULD NEVER HAPPEN)");
Answer = new RomanNumeral(-1);
}
}
if(Answer.InBounds())
{
Answer.setFormatSubtractive();
System.out.println(Answer + " : " + Answer.toInt());
Answer.setFormatAdditive();
System.out.println(Answer + " : " + Answer.toInt() + "\n");
}
}
}
/**
* Prompts the user to enter a character representing which type of arithmetic
* operation that they want to perform.
*
* @return returns only a valid operation character to be read by the {@link #doCalculation()}
* method. Keeps prompting the user until they make a valid choice.
*/
private char getOperator()
{
String temp = "";
while (true)
{
System.out.print("Enter + - * / or (q to quit)>");
temp = keyboard.nextLine();
switch(temp.charAt(0))
{
case '+': case '-': case '*': case '/': case 'q':
return temp.charAt(0);
default:
System.out.println("Invalid Choice");
}
}
}
/**
* Creates a Roman Numeral Calculator and does calculations
* until the user quits the program.
* @param args
*/
public static void main(String[] args)
{
RomanNumeralCalculator Calculator = new RomanNumeralCalculator();
Calculator.doCalculation();
}
}
|
public class BalanceIsNotEnoughException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public BalanceIsNotEnoughException() {
super("The balance is not enough to complete the payment!");
}
}
|
package com.binfan.davantitest.model.asset;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Bin on 2016/3/30.
*/
public class Link implements Parcelable {
private String url;
private String urlName;
protected Link(Parcel in) {
url = in.readString();
urlName = in.readString();
}
public static final Creator<Link> CREATOR = new Creator<Link>() {
@Override
public Link createFromParcel(Parcel in) {
return new Link(in);
}
@Override
public Link[] newArray(int size) {
return new Link[size];
}
};
public String getUrl() {
return url;
}
public String getUrlName() {
return urlName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(url);
dest.writeString(urlName);
}
}
|
/*
* (C) Copyright 2010 Marvell International Ltd.
* All Rights Reserved
*
* MARVELL CONFIDENTIAL
* Copyright 2008 ~ 2010 Marvell International Ltd All Rights Reserved.
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell International Ltd
* or its suppliers and licensors. The Material contains trade secrets and
* proprietary and confidential information of Marvell or its suppliers and
* licensors. The Material is protected by worldwide copyright and trade secret
* laws and treaty provisions. No part of the Material may be used, copied,
* reproduced, modified, published, uploaded, posted, transmitted, distributed,
* or disclosed in any way without Marvell's prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
package com.marvell.fmmanager;
import android.content.Context;
import android.os.Binder;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.IBinder;
import android.os.ServiceManager;
import android.util.Log;
import android.os.Handler;
import android.os.Message;
import java.io.File;
import android.os.ParcelFileDescriptor;
public class FMRadioManager {
private IFMRadioService mFMRadioService;
private static final String TAG = "FMRadioManager";
private FMRadioListener mFMRadioListener = null;
public FMRadioManager(){
mFMRadioService = IFMRadioService.Stub.asInterface(
ServiceManager.getService("FMRadioService"));
if (mFMRadioService == null){
Log.d(FMRadioManager.TAG, "mFMRadioService == NULL");
return;
}else{
Log.d(FMRadioManager.TAG, "Got FMRadioervice instance.");
}
}
public boolean isFMTx(){
boolean res = true;
try {
res = mFMRadioService.isFMTx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "isFMTx() failed with: " + e);
e.printStackTrace();
}
return res;
}
public boolean isFMRx(){
boolean res = true;
try {
res = mFMRadioService.isFMRx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "isFMRx() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int powerOn(){
int res = 0;
try {
res = mFMRadioService.powerOn();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "powerOn() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int powerOff(){
int res = 0;
try {
res = mFMRadioService.powerOff();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "powerOff() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int enableTx(){
int res = 0;
try {
res = mFMRadioService.enableTx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "enableTx() failed with: " + e);
e.printStackTrace();
}
// enable failed
if (res < 0){
return res;
}
// enable success, register the callbacks.
try {
Log.d(FMRadioManager.TAG, "mFMRadioService.registerCallback(mCallback)");
mFMRadioService.registerCallback(mCallback);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "Got exception when registerCallback.");
}
return res;
}
public int disableTx(){
int res = 0;
try {
Log.d(FMRadioManager.TAG, "mFMRadioService.unregisterCallback(mCallback)");
mFMRadioService.unregisterCallback(mCallback);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "Got exception when unregisterCallback.");
}
try {
res = mFMRadioService.disableTx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "disableTx() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int enableRx(){
int res = 0;
try {
res = mFMRadioService.enableRx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "enableRx() failed with: " + e);
e.printStackTrace();
}
// enable failed
if (res < 0){
return res;
}
// enable success, register the callbacks.
try {
Log.d(FMRadioManager.TAG, "mFMRadioService.registerCallback(mCallback)");
mFMRadioService.registerCallback(mCallback);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "Got exception when registerCallback.");
}
return res;
}
public int disableRx(){
int res = 0;
try {
Log.d(FMRadioManager.TAG, "mFMRadioService.unregisterCallback(mCallback)");
mFMRadioService.unregisterCallback(mCallback);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "Got exception when unregisterCallback.");
}
try {
res = mFMRadioService.disableRx();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "disableRx() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int suspend(){
int res = 0;
try {
res = mFMRadioService.suspend();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "suspend() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int resume(){
int res = 0;
try {
res = mFMRadioService.resume();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "resume() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int scanAll(){
int res = 0;
try {
res = mFMRadioService.scan_all();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "scan_all() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int stopScan(){
int res = 0;
try {
res = mFMRadioService.stop_scan();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "stop_scan() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int setChannel(int freq){
int res = 0;
try {
res = mFMRadioService.set_channel(freq);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_channel() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int getChannel(){
int res = 0;
try {
res = mFMRadioService.get_channel();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "get_channel() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int getRssi(){
int res = 0;
try {
res = mFMRadioService.get_rssi();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "get_rssi() failed with: " + e);
e.printStackTrace();
}
return res;
}
public float getVolume(){
float res = 0;
try {
res = mFMRadioService.get_volume();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "get_volume() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int setVolume(int volume){
int res = 0;
try {
res = mFMRadioService.set_volume(volume);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_volume() failed with: " + e);
e.printStackTrace();
}
return res;
}
public boolean setMute(boolean flag){
boolean res = true;
try {
res = mFMRadioService.set_mute(flag);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_mute() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int setBand(int band){
int res = 0;
try {
res = mFMRadioService.set_band(band);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_band() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int scanNext(){
int res = 0;
try {
res = mFMRadioService.scan_next();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "enable() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int scanPrev(){
int res = 0;
try {
res = mFMRadioService.scan_prev();
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "enable() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int setSpeakerOn(boolean on){
int res = 0;
try {
res = mFMRadioService.setSpeakerOn(on);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "enable() failed with: " + e);
e.printStackTrace();
}
return res;
}
public boolean setTxMute(boolean flag){
boolean res = true;
try {
res = mFMRadioService.set_tx_mute(flag);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_tx_mute() failed with: " + e);
e.printStackTrace();
}
return res;
}
public boolean setPowerMode(boolean flag){
boolean res = true;
try {
res = mFMRadioService.set_power_mode(flag);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_power_mode() failed with: " + e);
e.printStackTrace();
}
return res;
}
public boolean setTxMonoStereo(boolean flag){
boolean res = true;
try {
res = mFMRadioService.set_tx_mono_stereo(flag);
} catch (RemoteException e) {
Log.d(FMRadioManager.TAG, "set_tx_mono_stereo() failed with: " + e);
e.printStackTrace();
}
return res;
}
public int startRecording(String path){
ParcelFileDescriptor pfd = null;
int ret = 0;
try {
File file = new File(path);
pfd = ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
Log.d(FMRadioManager.TAG, "startRecording(), pfd = " + pfd + ", FilePath = " + path);
} catch (Exception e) {
Log.e(FMRadioManager.TAG, "startRecording() failed when opening " + path +" with exception: " + e);
return -2;
}
try {
boolean ret_val = mFMRadioService.start_recording(pfd);
if (!ret_val){
Log.e(FMRadioManager.TAG, "startRecording() failed when starting record");
ret = -1;
}
} catch (Exception e) {
Log.e(FMRadioManager.TAG, "startRecording() failed when starting record with exception:" + e);
ret = -1;
}
try {
pfd.close();
} catch (Exception e){
Log.e(FMRadioManager.TAG, "startRecording() failed when closing fd." + pfd);
}
return ret;
}
public int stopRecording(){
try {
boolean ret = mFMRadioService.stop_recording();
if (!ret){
Log.e(FMRadioManager.TAG, "stopRecording() failed.");
return -1;
}
} catch (RemoteException e) {
Log.e(FMRadioManager.TAG, "startRecording() failed with exception:" + e);
return -1;
}
return 0;
}
public byte[] getRecordFormat(){
byte[] format = null;
try {
format = mFMRadioService.get_record_format();
} catch (RemoteException e) {
Log.e(FMRadioManager.TAG, "getRecordFormat() failed with exception:" + e);
}
return format;
}
public boolean registerListener(FMRadioListener listener){
mFMRadioListener = listener;
return true;
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg){
if (mFMRadioListener == null){
return;
}
switch (msg.what) {
case M_SCAN_FINISHED:
mFMRadioListener.onScanFinished();
break;
case M_FOUND_CHANNEL:
mFMRadioListener.onFoundChannel(msg.arg1);
break;
case M_MONO_CHANGED:
mFMRadioListener.onMonoStereoChanged(msg.arg1);
break;
case M_GET_RDSPS_NAME:
mFMRadioListener.onGetRdsPs((byte [])msg.obj);
break;
case M_GET_CUR_RSSI:
mFMRadioListener.onGetRssi(msg.arg1);
break;
case M_STATE_CHANGED:
mFMRadioListener.onStateChanged(msg.arg1);
break;
case M_RECORDING_STOP:
mFMRadioListener.onRecordingStop(msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
};
private static final int M_SCAN_FINISHED = 1;
private static final int M_FOUND_CHANNEL = 2;
private static final int M_MONO_CHANGED = 3;
private static final int M_GET_CUR_RSSI = 4;
private static final int M_GET_RDSPS_NAME = 5;
private static final int M_STATE_CHANGED = 6;
private static final int M_RECORDING_STOP = 7;
private IFMRadioCallback mCallback = new IFMRadioCallback.Stub() {
/**
* This is called by the remote service regularly to tell us about
* new values. Note that IPC calls are dispatched through a thread
* pool running in each process, so the code executing here will
* NOT be running in our main thread like most other things -- so,
* to update the UI, we need to use a Handler to hop over there.
*/
public void scan_finished(){
mHandler.sendMessage(mHandler.obtainMessage(M_SCAN_FINISHED));
return;
}
public void found_channel(int channel){
mHandler.sendMessage(mHandler.obtainMessage(M_FOUND_CHANNEL, channel, 0));
return;
}
public void mono_changed(int mono){
mHandler.sendMessage(mHandler.obtainMessage(M_MONO_CHANGED, mono, 0));
return;
}
public void get_cur_rssi(int rssi){
mHandler.sendMessage(mHandler.obtainMessage(M_GET_CUR_RSSI, rssi, 0));
return;
}
public void get_rdsps_name(byte[] name){
mHandler.sendMessage(mHandler.obtainMessage(M_GET_RDSPS_NAME, name));
return;
}
public void state_changed(int mode){
mHandler.sendMessage(mHandler.obtainMessage(M_STATE_CHANGED, mode, 0));
return;
}
public void recording_stop(int reason){
mHandler.sendMessage(mHandler.obtainMessage(M_RECORDING_STOP, reason, 0));
return;
}
};
}
|
package com.mabang.android.entity.vo;
/**
* 手机验证码信息
*
* @author xiong
*
*/
public class MobileValidateCodeInfo extends VoBase {
/**
* 序列ID
*/
private static final long serialVersionUID = 4942334939895083795L;
private String mobile; // 手机号码
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
return;
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS.dnssec;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Rcode;
class TestUnsigned extends TestBase {
@Test
void testUnsignedBelowSignedZoneBind() throws IOException {
Message response = resolver.send(createMessage("www.unsigned.ingotronic.ch./A"));
assertFalse(response.getHeader().getFlag(Flags.AD), "AD flag must not be set");
assertEquals(Rcode.NOERROR, response.getRcode());
assertEquals(localhost, firstA(response));
assertEquals("insecure.ds.nsec", getReason(response));
assertEde(-1, response);
}
@Test
void testUnsignedBelowSignedTldNsec3NoOptOut() throws IOException {
Message response = resolver.send(createMessage("20min.ch./A"));
assertFalse(response.getHeader().getFlag(Flags.AD), "AD flag must not be set");
assertEquals(Rcode.NOERROR, response.getRcode());
assertEquals("insecure.ds.nsec3", getReason(response));
assertEde(-1, response);
}
@Test
void testUnsignedBelowSignedTldNsec3OptOut() throws IOException {
Message response = resolver.send(createMessage("yahoo.com./A"));
assertFalse(response.getHeader().getFlag(Flags.AD), "AD flag must not be set");
assertEquals(Rcode.NOERROR, response.getRcode());
assertEquals("insecure.ds.nsec3", getReason(response));
assertEde(-1, response);
}
@Test
void testUnsignedBelowUnsignedZone() throws IOException {
Message response = resolver.send(createMessage("www.sub.unsigned.ingotronic.ch./A"));
assertFalse(response.getHeader().getFlag(Flags.AD), "AD flag must not be set");
assertEquals(Rcode.NOERROR, response.getRcode());
assertEquals(localhost, firstA(response));
assertEquals("insecure.ds.nsec", getReason(response));
assertEde(-1, response);
}
}
|
/*
* Test11
*
* Testiamo la chiamata a un metodo definito in questo file (non di sistema).
*/
class HelloWorld
{
static void MyMethod()
{
System.out.println("Sto in MyMethod");
}
static public void main(String[] a)
{
MyMethod();
}
}
|
package enshud.syntaxtree;
import java.util.Map;
import enshud.s3.checker.TypeExpressionMap;
import enshud.symboltable.SymbolTable;
import enshud.symboltable.SymbolTableStack;
public abstract class AbstractVisitor {
public void preorder(
TypeExpressionMap typeExpressions,
Map<AbstractSyntaxNode, SymbolTable> symbolTables,
SyntaxNodeStack syntaxNodeStack,
SymbolTableStack symbolTableStack) throws Exception {
return;
}
// nodeIndex(:0-オリジンで1~Nの範囲)番目の子ノードを訪問する前に呼び出される
public void inorder(
int nodeIndex,
TypeExpressionMap typeExpressions,
Map<AbstractSyntaxNode, SymbolTable> symbolTables,
SyntaxNodeStack syntaxNodeStack,
SymbolTableStack symbolTableStack) throws Exception {
return;
}
public void postorder(
TypeExpressionMap typeExpressions,
Map<AbstractSyntaxNode, SymbolTable> symbolTables,
SyntaxNodeStack syntaxNodeStack,
SymbolTableStack symbolTableStack) throws Exception {
return;
}
}
|
package io.github.jitinsharma.insplore.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatDelegate;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import io.github.jitinsharma.insplore.R;
import io.github.jitinsharma.insplore.activities.SearchActivity;
import io.github.jitinsharma.insplore.adapter.TopDestinationAdapter;
import io.github.jitinsharma.insplore.model.Constants;
import io.github.jitinsharma.insplore.model.OnPlacesClick;
import io.github.jitinsharma.insplore.model.TopDestinationObject;
import io.github.jitinsharma.insplore.service.TdService;
import io.github.jitinsharma.insplore.utilities.Utils;
/**
* A placeholder fragment containing a simple view.
*/
public class TopDestinationFragment extends Fragment{
RecyclerView topDestinationList;
TopDestinationAdapter topDestinationAdapter;
String month;
String airportCode;
ArrayList<TopDestinationObject> topDestinationObjects;
ProgressBar progressBar;
AutoCompleteTextView cityListName;
Intent tdService;
TdBroadcastReceiver tdBroadcastReceiver;
LinearLayout topDestInput;
TextView topDestDate;
SearchActivity searchActivity;
String savedMonthString;
String cityName;
boolean placeClicked = false;
static{
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
if (getArguments()!=null){
month = getArguments().getString(Constants.TD_MONTH);
airportCode = getArguments().getString(Constants.SAVED_AIRPORT_CODE);
}
super.onCreate(savedInstanceState);
}
public TopDestinationFragment() {
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(Constants.TOP_DEST_OBJ, topDestinationObjects);
//outState.putString(Constants.ENTERED_VALUE, cityListName.getText().toString());
outState.putBoolean(Constants.PLACE_CLICKED, placeClicked);
super.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
if (tdBroadcastReceiver!=null) {
getContext().unregisterReceiver(tdBroadcastReceiver);
}
super.onDestroy();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_top_destination, container, false);
searchActivity = (SearchActivity)getActivity();
searchActivity.updateImage(ContextCompat.getDrawable(getContext(), R.drawable.top_dest_image));
searchActivity.getSupportActionBar().setTitle(getContext().getString(R.string.top_destination));
if (savedInstanceState != null){
topDestinationObjects = savedInstanceState.getParcelableArrayList(Constants.TOP_DEST_OBJ);
savedMonthString = savedInstanceState.getString(Constants.DATE_VALUE);
cityName = savedInstanceState.getString(Constants.ENTERED_VALUE);
placeClicked = savedInstanceState.getBoolean(Constants.PLACE_CLICKED);
}
topDestInput = (LinearLayout)root.findViewById(R.id.top_dest_input);
topDestDate = (TextView)root.findViewById(R.id.top_dest_date_text);
topDestinationList = (RecyclerView)root.findViewById(R.id.top_dest_list);
progressBar = (ProgressBar)root.findViewById(R.id.top_dest_progress);
cityListName = (AutoCompleteTextView)root.findViewById(R.id.top_dest_search);
topDestinationList.setLayoutManager(new LinearLayoutManager(getContext()));
topDestinationList.setNestedScrollingEnabled(false);
initializeReceiver();
if (placeClicked){
displayPlacesOfInterest(cityName);
}
if (airportCode!=null){
topDestInput.setVisibility(View.GONE);
if (topDestinationObjects==null) {
initializeService(airportCode, month);
}
else{
setAdapterWithData();
progressBar.setVisibility(View.GONE);
}
}
else{
topDestInput.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
String airports[] = getContext().getResources().getStringArray(R.array.airport_cities);
ArrayAdapter<String> airportArrayAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_dropdown_item_1line, airports);
cityListName.setAdapter(airportArrayAdapter);
if (cityName!=null){
cityListName.postDelayed(new Runnable() {
@Override
public void run() {
cityListName.showDropDown();
}
},500);
cityListName.setText(cityName);
cityListName.setSelection(cityListName.getText().length());
}
if (savedMonthString==null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int month = calendar.get(Calendar.MONTH) - 1;
String monthString = String.format(Locale.ENGLISH, "%02d", month);
topDestDate.setText(calendar.get(Calendar.YEAR) + "-" + monthString);
}
else{
topDestDate.setText(savedMonthString);
}
topDestDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogFragment datePickerFragment = DatePickerFragment.newInstance(1, new DatePickerFragment.OnDatePickedListener() {
@Override
public void onDatePicked(int year, int month, int day, int requestCode) {
String monthString;
//Toast.makeText(MainActivity.this, ""+year+month+day, Toast.LENGTH_SHORT).show();
monthString = String.format("%02d",month);
topDestDate.setText(year + "-" + monthString);
}
});
datePickerFragment.show(getFragmentManager(), "datepicker");
}
});
cityListName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Utils.hideKeyBoard(getContext(), view);
progressBar.setVisibility(View.VISIBLE);
String[] data = ((String)adapterView.getItemAtPosition(i)).split(",");
initializeService(data[0], topDestDate.getText().toString());
}
});
}
return root;
}
class TdBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
if (intent.getStringExtra(Constants.NETWORK_ERROR)!=null){
Snackbar.make(getView(), getContext().getString(R.string.server_error), Snackbar.LENGTH_LONG).show();
}
else {
topDestinationObjects = intent.getParcelableArrayListExtra(Constants.RECEIVE_LIST);
if (topDestinationObjects!=null && topDestinationObjects.size()>0) {
setAdapterWithData();
}
else{
Snackbar.make(getView(), getContext().getString(R.string.no_result_error), Snackbar.LENGTH_LONG).show();
}
}
}
}
public void setAdapterWithData(){
topDestinationAdapter = new TopDestinationAdapter(getContext(), topDestinationObjects, new OnPlacesClick() {
@Override
public void onClick(int position) {
searchActivity.updateImage(getContext().getResources().getDrawable(R.drawable.places));
displayPlacesOfInterest(topDestinationObjects.get(position).getCityName());
}
});
topDestinationList.setAdapter(topDestinationAdapter);
}
public void displayPlacesOfInterest(String city){
placeClicked = true;
PlaceOfInterestFragment fragment = PlaceOfInterestFragment.newInstance(city);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
public void initializeReceiver(){
tdBroadcastReceiver = new TdBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(TdService.ACTION_TdService);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
getContext().registerReceiver(tdBroadcastReceiver, intentFilter);
}
public void initializeService(String code, String month){
tdService = new Intent(getActivity(), TdService.class);
tdService.putExtra(Constants.DEP_AIRPORT, code);
tdService.putExtra(Constants.TD_MONTH, month);
getActivity().startService(tdService);
}
}
|
/**
* Created by Гамзат on 04.06.2017.
*/
public class Happiness {
}
|
package cttd.admin.dao;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import common.bean.PaginationList;
import cttd.admin.dao.UserDAO;
import cttd.admin.model.User;
import lombok.extern.slf4j.Slf4j;
import common.util.DBUtil;
@Slf4j
public class UserDAOTests {
private UserDAO userDAO = new UserDAO();
@After
public void closeConnection() {
DBUtil.commitTransaction();
DBUtil.closeSession();
}
@Before
public void openConnection() {
DBUtil.openThreadSession();
DBUtil.beginTransaction();
}
@Test
public void searchTest() {
PaginationList pl = userDAO.search("", 0);
List<User> list = pl.getItems();
for (User u : list) {
log.info(u.toString());
}
}
}
|
package multiplayer;
import game.GameHandler;
import game.Player;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import main_app.LampPanel;
public class RemotePlayer {
MultiplayerGameHandler handler;
int id;
double x, y, xvel, yvel;
BufferedImage spritesheet1;
BufferedImage spritesheet2;
BufferedImage currImage;
int ticksTillNextFrame;
int facing;
public RemotePlayer(MultiplayerGameHandler handler, int id) {
this.handler = handler;
this.id = id;
this.spritesheet1 = handler.loadImage("/player.png");
this.spritesheet2 = handler.loadImage("/player2.png");
ticksTillNextFrame = 9;
currImage = spritesheet1;
}
public void updateFromRemote(String s) {
String[] arr = s.split(" ");
//System.out.println(Arrays.toString(arr));
double[] darr = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
darr[i] = Double.parseDouble(arr[i]);
}
x = darr[0];
y = darr[1];
xvel = darr[2];
yvel = darr[3];
facing = (int) darr[4];
}
public void update() {
if (ticksTillNextFrame == 0) {
if (currImage.equals(spritesheet1)) {
currImage = spritesheet2;
} else {
currImage = spritesheet1;
}
ticksTillNextFrame = 9;
} else {
ticksTillNextFrame--;
}
}
public void draw(Graphics g) {
g.setColor(new Color(0, 255, 255, 50));
if (facing == Player.RIGHT) {
((Graphics2D) g).drawImage(currImage, LampPanel.PWIDTH / 2 - (int) (((GameHandler) handler).player.getX() - this.x) - 16, LampPanel.PHEIGHT / 2 - (int) (((GameHandler) handler).player.getY() - this.y) - 27, LampPanel.PWIDTH / 2 - (int) (((GameHandler) handler).player.getX() - this.x) + 16, LampPanel.PHEIGHT / 2 - (int) (((GameHandler) handler).player.getY() - this.y) + 27, 0, 0, 14, 27, null);
} else {
((Graphics2D) g).drawImage(currImage, LampPanel.PWIDTH / 2 - (int) (((GameHandler) handler).player.getX() - this.x) - 16, LampPanel.PHEIGHT / 2 - (int) (((GameHandler) handler).player.getY() - this.y) - 27, LampPanel.PWIDTH / 2 - (int) (((GameHandler) handler).player.getX() - this.x) + 16, LampPanel.PHEIGHT / 2 - (int) (((GameHandler) handler).player.getY() - this.y) + 27, 14, 0, 0, 27, null);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
/**
*
* @author Tomek
*/
public class jtextpane {
public static void main(String[] args) {
JTextPane t = new JTextPane();
t.setSelectionColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));
Highlighter hilite = new MyHighlighter();
t.setHighlighter(hilite);
t.setText("L\nL\nL\nL\nL\n");
DefaultHighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.WHITE);
DefaultHighlightPainter grayPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GRAY);
try {
Document doc = t.getDocument();
String text = doc.getText(0, doc.getLength());
int start = 0;
int end = 0 ;
boolean even = true;
//look for newline char, and then toggle between white and gray painters.
while ((end = text.indexOf('\n', start)) >= 0) {
System.out.println("indexOf = "+text.indexOf('\n', start)+" "+start+" "+end);
even = !even;
DefaultHighlightPainter painter = even ? grayPainter : whitePainter;
hilite.addHighlight(start, end+1, painter);
start = end+1;
}
} catch (BadLocationException e) {
e.printStackTrace();
}
JPanel p = new JPanel(new BorderLayout());
p.add(t, BorderLayout.CENTER);
JFrame f = new JFrame();
f.add(p);
f.setSize(100, 100);
f.setVisible(true);
}
}
|
package ejemplomerge;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
/**
*
* @author rgonzaleza_ex
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer;
File file = new File("test.xml");
FileInputStream fis = null;
fis = new FileInputStream(file);
try {
transformer = tFactory.newTransformer(new StreamSource("merge.xslt"));
transformer.transform(new StreamSource(fis), new StreamResult(new File("simple.xml")));
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package com.yu.hu.roomtest.activity;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.yu.hu.roomtest.R;
import com.yu.hu.roomtest.adapter.StudentItemDecoration;
import com.yu.hu.roomtest.adapter.StudentListAdapter;
import com.yu.hu.roomtest.entity.Student;
import com.yu.hu.roomtest.repository.StudentRepository2;
import java.util.List;
public class MainActivity extends BaseActivity {
protected static final String TAG = "MainActivity";
private StudentRepository2 mStudentRepository;
private StudentListAdapter mStudentAdapter;
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void init() {
Log.d(TAG, "init: ");
TextView title = findViewById(R.id.tv_title);
title.setText(getString(R.string.str_stu_list));
ImageView optionIcon = findViewById(R.id.img_right);
optionIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onOptionBtnClicked();
}
});
this.mStudentRepository = new StudentRepository2(getApplication());
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new StudentItemDecoration(this, 3));
this.mStudentAdapter = new StudentListAdapter(this, mStudentRepository);
recyclerView.setAdapter(mStudentAdapter);
mStudentRepository.getAllStudents().observe(this, new Observer<List<Student>>() {
@Override
public void onChanged(List<Student> students) {
mStudentAdapter.submitList(students);
}
});
}
//添加学生
private void onOptionBtnClicked() {
Intent intent = new Intent(this, AddStudentActivity.class);
intent.putExtra(AddStudentActivity.KEY_START_TYPE, AddStudentActivity.START_TYPE_ADD);
startActivityForResult(intent, AddStudentActivity.REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != AddStudentActivity.REQUEST_CODE) {
return;
}
// if (resultCode == AddStudentActivity.RESULT_CODE_Add) {
// Student student = null;
// if (data != null) {
// student = data.getParcelableExtra(AddStudentActivity.KEY_STUDENT);
// }
//
// if (student == null) {
// mStudentAdapter.setStudentList(mStudentRepository.getAllStudents());
// } else {
// mStudentAdapter.addStudent(student);
// }
// } else if (resultCode == AddStudentActivity.RESULT_CODE_MODIFY) {
// mStudentAdapter.setStudentList(mStudentRepository.getAllStudents());
// }
}
}
|
package com.edu.realestate.yelp;
public abstract class YelpElement {
protected String name;
protected String url;
protected String address;
public YelpElement(String name, String url, String address) {
super();
this.name = name;
this.url = url;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "YelpElement [name=" + name + ", url=" + url + ", address=" + address + "]";
}
}
|
package am.bizis.stspr.fo;
public enum Zpusobilost {
PLNA, OMEZENA, ODNATA;
private String rozsah;
private ISEOOsoba zastupce;
public void setRozsah(String s){
if(this.equals(OMEZENA)) this.rozsah=s;
}
public String getRozsah(){
if(this.equals(OMEZENA)) return this.rozsah;
else return null;
}
public void setZastupce(ISEOOsoba z){
if(!this.equals(PLNA)) zastupce=z;
}
public ISEOOsoba getZastupce(){
if(this.equals(PLNA)) return null;
else return zastupce;
}
}
|
/*
* Copyright 2020 WeBank
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.wedatasphere.schedulis.common.distributelock;
/**
* @author georgeqiao
* @Title: DistributeLockAdapter
* @date 2019/11/1220:02
* @Description: TODO
*/
public interface DistributeLockAdapter {
/**
* 获取锁
*
* @param lock_key 锁key
* @param locktimeout(毫秒) 持有锁的有效时间,防止死锁
* @param gettimeout(毫秒) 获取锁的超时时间,这个时间内获取不到将重试
* @return
*/
boolean lock(String lock_key, long locktimeout, long gettimeout);
/**
* 释放锁
*
* @param lock_key
*/
void unlock(String lock_key);
/**
* 重置锁
*
* @param distributeLock
* @return
*/
int resetLock(DistributeLock distributeLock);
/**
* 更新lockModel信息,内部采用乐观锁来更新
*
* @param distributeLock
* @return
*/
int updateLock(DistributeLock distributeLock);
}
|
package myGame.entity.enemy;
public class TankerEnemy {
}
|
package startGame;
import controller.MenuController;
import model.*;
import net.Connection;
public class Game {
private Player player1;
private Player player2;
private Map mapGame;
public Game() {
mapGame = new Map();
if (MenuController.gameWithAI) {
player1 = new Human('X');
player2 = new AI('O', 'X');
}
if (Connection.modeReady){
player1 = new Human('X');
player2 = new NetPlayer('O');
}
if(Connection.isServer){
player1 = new Human('X');
player2 = new NetPlayer('O');
}
}
public Player getPlayer1() {
return player1;
}
public Player getPlayer2() {
return player2;
}
public Map getMapGame() {
return mapGame;
}
}
|
package falcons.plugin;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
*
* @author Julius
*
* An annotation that contains the ID and versionID of the plugin.
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Plugin {
String pluginID() default "No pluginID";
String versionID() default "No versionID";
}
|
package com.podraza.android.spotifystreamer;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.List;
import kaaes.spotify.webapi.android.models.Artist;
/**
* Created by adampodraza on 6/20/15.
*/
public class ParcelableArtist implements Parcelable, Serializable{
private String name;
private String id;
private String imageUrl;
public ParcelableArtist(String name, String id, String imageUrl) {
this.name = name;
this.id = id;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(id);
dest.writeString(imageUrl);
}
}
|
package com.crossenagetask.utils;
/**
* Created by NrapendraKumar on 14-03-2016.
*/
public class AppUtil {
public static final String DATE_FORMAT = "YYYYMMDD";
public static final String COMMA = ",";
public static final String APPLICATION_PROPERTY = "/application.properties";
public static final String CSV_FILE_PATH = "/files/crengage.csv";
}
|
package com.crypto.document;
import java.math.BigDecimal;
import java.sql.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Crypto {
Date date;
@JsonProperty("txVolume(USD)")
String txVolume;
BigDecimal txCount;
@JsonProperty("marketcap(USD)")
BigDecimal marketcap;
@JsonProperty("price(USD)")
BigDecimal price;
@JsonProperty("exchangeVolume(USD)")
BigDecimal exchangeVolume;
BigDecimal generatedCoins;
BigDecimal fees;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTxVolume() {
return txVolume;
}
public void setTxVolume(String txVolume) {
this.txVolume = txVolume;
}
public BigDecimal getTxCount() {
return txCount;
}
public void setTxCount(BigDecimal txCount) {
this.txCount = txCount;
}
public BigDecimal getMarketcap() {
return marketcap;
}
public void setMarketcap(BigDecimal marketcap) {
this.marketcap = marketcap;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getExchangeVolume() {
return exchangeVolume;
}
public void setExchangeVolume(BigDecimal exchangeVolume) {
this.exchangeVolume = exchangeVolume;
}
public BigDecimal getGeneratedCoins() {
return generatedCoins;
}
public void setGeneratedCoins(BigDecimal generatedCoins) {
this.generatedCoins = generatedCoins;
}
public BigDecimal getFees() {
return fees;
}
public void setFees(BigDecimal fees) {
this.fees = fees;
}
}
|
package juez.david.transportbcn.provider.metro;
import juez.david.transportbcn.provider.base.BaseModel;
import java.util.Date;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* Data model for the {@code metro} table.
*/
public interface MetroModel extends BaseModel {
/**
* Get the {@code idmetro} value.
* Can be {@code null}.
*/
@Nullable
Integer getIdmetro();
/**
* Get the {@code line} value.
* Can be {@code null}.
*/
@Nullable
String getLine();
/**
* Get the {@code name} value.
* Can be {@code null}.
*/
@Nullable
String getName();
/**
* Get the {@code accessibility} value.
* Can be {@code null}.
*/
@Nullable
String getAccessibility();
/**
* Get the {@code zone} value.
* Can be {@code null}.
*/
@Nullable
String getZone();
/**
* Get the {@code connections} value.
* Can be {@code null}.
*/
@Nullable
String getConnections();
/**
* Get the {@code lat} value.
* Can be {@code null}.
*/
@Nullable
Double getLat();
/**
* Get the {@code lon} value.
* Can be {@code null}.
*/
@Nullable
Double getLon();
/**
* Get the {@code synctime} value.
* Can be {@code null}.
*/
@Nullable
Date getSynctime();
}
|
package com.model.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.dao.BaseDao;
import com.model.dao.UserDao;
import com.model.pojo.Friend;
import com.model.pojo.User;
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private BaseDao basedao;
private final static String GET_USERS = " from User ";
//private final static String DELETE_USER="delete from User where id=? ";
//@Transactional
/**
* 实现用户注册
*/
public void saveUser(User user) {
//getHibernateTemplate().save(user);
basedao.saveOrUpdateObject(user);
}
/**
* 实现用户登录
*/
public User login(String name,String password){
String hql=" from User u where "
+ "u.loginName= '"+name+"' and u.password='"+password+"'";
//List list = getHibernateTemplate().find(hql);
List list = basedao.getObjectListByHql(hql);
User user = new User();
user = (User) list.get(0);
return user;
}
/**
* 用户总数
*/
public int getTotalUser() {
// int totalNum = getTotalNum(GET_USERS);
return basedao.getTotalNum(GET_USERS);
}
/**
* 查询用户列表(后台管理)
*/
@Override
public List getUserList(String pageNo) {
//List list = getPageDataByHql(GET_USERS, 5, Integer.parseInt(pageNo)-1);
List list = basedao.getPageDataByHql(GET_USERS, 5, Integer.parseInt(pageNo)-1);
return list;
}
@Override
public void deleteUser(User user) {
//getHibernateTemplate().delete(user);
basedao.deleteObject(user);
}
@Override
public void addFriend(Friend friend) {
//getHibernateTemplate().save(friend);
basedao.deleteObject(friend);
}
@Override
public List getFriendList(String myname) {
String hql = "from Friend f where f.myname='"+myname+"'";
//List list = getHibernateTemplate().find(hql);
List list = basedao.getObjectListByHql(hql);
return list;
}
@Override
public List getAllUsers() {
String hql = "from User";
//List list = getHibernateTemplate().find(hql);
List list = basedao.getObjectListByHql(hql);
return list;
}
}
|
package com.lenovohit.hwe.treat.service;
import java.util.Map;
import com.lenovohit.hwe.treat.model.Activity;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
public interface HisActivityService {
public RestEntityResponse<Activity> getInfo(Activity request, Map<String, ?> variables);
public RestListResponse<Activity> findList(Activity request, Map<String, ?> variables);
}
|
package com.yusys.warrantManager;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yusys.Utils.JsonUtils;
import com.yusys.Utils.ResponseUtils;
import com.yusys.warrantManager.IWarrantOutService;
import com.yusys.web.BaseController;
@Controller
@RequestMapping("/WarrantOut")
public class WarrantOutController extends BaseController{
@Resource
private IWarrantOutService warrantOutService;
//查询所有权证出库信息
@RequestMapping("/queryListWarrantOut")
public void queryListWarrantOut(HttpServletRequest req,HttpServletResponse res) {
ResponseUtils.jsonMessage(res,JsonUtils.beanToJson(warrantOutService.queryListWarrantOut(req)));
}
//保存权证信息
@RequestMapping("/editWarrantOut")
public void editWarrantOut(HttpServletRequest req,HttpServletResponse res) {
ResponseUtils.jsonMessage(res,JsonUtils.beanToJson(warrantOutService.editWarrantOut(req,getUserId(req))));
}
//打回
@RequestMapping("/beatWarrantOut")
public void beatWarrantOut(HttpServletRequest req,HttpServletResponse res) {
ResponseUtils.jsonMessage(res,JsonUtils.beanToJson(warrantOutService.beatWarrantOut(req,getUserId(req))));
}
}
|
package exam4;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolEx13 {
public static void main(String[] args) {
// 단일 스레드에서 실행되는 ExecutorService를 생성
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 태스크를 실행
executorService.execute(new TestThread());
executorService.execute(new TestThread());
// 모든 작업이 종료되면 ExecutorService를 셧다운함
executorService.shutdown();
}
}
class TestThread extends Thread {
@Override
public void run() {
// 스레드 시작 시에 이름을 표시
System.out.println(Thread.currentThread().getName() + ": Start");
try {
// 5초 대기
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 스리드 종료 시에 스레드명을 표시
System.out.println(Thread.currentThread().getName() + ": End");
}
}
|
package tree.splay;
public interface Tree<T extends Comparable<T>> {
void insert(T data);
Node<T> find(T data);
T getMin();
T getMax();
void inOrderTraversal();
}
|
import Body.Payload;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import util.ReusabaleMethods;
import static io.restassured.RestAssured.given;
public class DynamicJson {
@Test (dataProvider = "BooksData")
public void addBook(String isbn, String aisle){
RestAssured.baseURI="http://216.10.245.166";
String response = given().log().all().header("Content-Type","application/json").
body(Payload.AddBook(isbn,aisle)).when().
post("Library/Addbook.php").
then().log().all().assertThat().statusCode(200).extract().response().asString();
JsonPath js= ReusabaleMethods.rawToString(response);
String id=js.getString("ID");
System.out.println("Book ID is: "+id);
}
@DataProvider(name="BooksData")
public Object[][] getData() {
return new Object[][] {{"aaadadha","00001"},{"bbjfdbbb","00002"},{"cmgfcccc","00003"}};
}
//@Test(dataProvider = "DeleteBooksData")
//public void deletebook(String id){
// RestAssured.baseURI="http://216.10.245.166";
// String delresponse= given().log().all().header("Content-Type","application/json").
// body(Payload.DeleteBook(id)).when().
// post("/Library/DeleteBook.php").
// then().log().all().assertThat().statusCode(200).extract().response().asString();
//
// JsonPath js1= ReusabaleMethods.rawToString(delresponse);
//// String id1=js1.getString("ID");
//// System.out.println("Deleted Book ID: "+id);
//
//}
//@DataProvider(name="DeleteBooksData")
// public Object[] getID(){
//
// return new Object[] {"00001","00002", "00003"};
//}
}
|
package com.ziaan.library;
import java.sql.PreparedStatement;
import java.util.ArrayList;
/**
* <p> 제목: Mail 관련 라이브러리</p>
* <p> 설명: 메일환경세팅</p>
* <p> Copyright: Copyright (c) 2004</p>
* <p> Company: </p>
*@author 이정한
*@date 2003. 12
*@version 1.0
*/
public class MailSet {
private ConfigSet conf;
private String v_host_ip;
private String v_mailServer;
private boolean v_singleSender;
private String v_fromEmail;
private String v_fromName;
private String v_comptel;
private String v_fromCono;
private Mailing domail;
private SmsSendBean sms;
private String v_tempPath;
// private MemoBean memo;
private int sendOk = 0;
private int sendFail = 0;
private LogMailWriter mail = Log.mail;
/**
* 메일환경관련 세팅을 한다
@param box 중요 session 정보를 얻는다.
*/
public MailSet(RequestBox box) throws Exception{
try {
conf = new ConfigSet();
v_mailServer = conf.getProperty("mail.server");
// v_singleSender = conf.getBoolean("mail.admin.singlesender");
v_tempPath = conf.getProperty("mail.hhioffice.temp");
v_singleSender = false;
// Box에 발신자 메일주소가 있으면 사용함
if ( !box.getStringDefault("p_fromEmail","").equals("") ) {
v_fromEmail = box.getString("p_fromEmail");
v_fromName = box.getStringDefault("p_fromName","");
v_comptel = box.getStringDefault("p_comptel","");
} else {
if ( v_singleSender) { // 보내는 사람 이메일, 성명, 회사전화번호를 동일하게 할때
v_fromEmail = conf.getProperty("mail.admin.email");
v_fromName = conf.getProperty("mail.admin.name");
v_comptel = conf.getProperty("mail.admin.comptel");
}
else {
v_fromEmail = box.getSession("email");
v_fromName = box.getSession("name");
v_comptel = box.getSession("comptel");
}
}
v_fromCono = box.getSession("userid"); // 사번안 씀 userid 로 대체
// v_fromCono = "lee1"; // test
domail = Mailing.getInstance();
sms = new SmsSendBean();
// memo = new MemoBean(); // 쪽지 발송
} catch ( Exception ex ) {
Log.sys.println(this, ex, "Happen to MailSet(RequestBox box)");
}
}
/**
* 운영자 정보를 세팅 한다
@param fmail FormMail 에 메일을 발송하는 운영자 정보를 세팅한다.
*/
public void setSender(FormMail fmail) throws Exception {
fmail.setVariable("fromname", v_fromName);
fmail.setVariable("fromemail", v_fromEmail);
fmail.setVariable("comptel", v_comptel);
}
/**
* 메일발송
@param p_toCono 메일발송자 사번
@param p_toEmail 학습자 이메일
@param p_mailTitle 메일 제목
@param p_mailContent 메일 내용
@param p_isMailing 메일 형식
@param p_sendHtml Html 파일명
@return isMailed 메일전송 성공여부
*/
public boolean sendMail(String p_toCono, String p_toEmail, String p_mailTitle, String p_mailContent, String p_isMailing, String p_sendHtml) throws Exception {
boolean isMailed = false;
int isEnd = 0;
try {
if ( p_isMailing.equals("1") ) { // 일반 메일로 받기 원할경우
domail.send(v_mailServer, v_fromEmail, v_fromName, p_toEmail, p_mailTitle, p_mailContent); // 서버IP, from 이메일,
isMailed =true;
}
else if ( p_isMailing.equals("2") ) { // SMS 메일발송
// sms.sendSMSMsg(p_toCono,p_toEmail,p_mailTitle);
isMailed =false;
} else if ( p_isMailing.equals("3") ) { // 쪽지로 받기 원할경우
// isMailed = memo.insertMemoByMail(v_fromCono, p_toCono, p_mailTitle, p_mailContent); // 쪽지에 넣어야된다
// isMailed = memo.insertMemoByMail(p_toCono, p_toEmail, p_mailTitle, p_mailContent); // 쪽지에 넣어야된다
// isMailed = memo.insertMemoByMail(p_toCono, p_toEmail, p_mailTitle, p_mailContent); // 쪽지에 넣어야된다
}
} catch ( Exception ex ) {
isMailed = false;
Log.sys.println(this, ex, "Happen to MailSet.sendMail(), from " + v_fromCono + " to " + p_toCono);
}
return isMailed;
}
public int insertMailData(ArrayList list) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String sql = "";
String sql1 = "";
String maxseq = "";
int isOk = 0;
int a = 0;
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
//// seq 생성
sql1 =" select nvl(ltrim(rtrim(to_char(to_number(max(seq)) +1,'0000000'))),'0000001') MSTCD " ;
sql1 += "From tz_humantouch ";
ls = connMgr.executeQuery(sql1);
if ( ls.next() ) {
maxseq = ls.getString("MSTCD");
}
else{
maxseq = "0000001";
}
sql = "insert into tz_humantouch(subj, year, subjseq, userid, touch, seq, ismail, edustart, eduend, title, sdesc, isok, reason, ismailopen, luserid, ldate)";
sql += " values (?, ?, ?, ?, ?, '" +maxseq + "', ?, ?, ?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'))";
pstmt = connMgr.prepareStatement(sql);
for ( int i = 0; i < list.size(); i++ ) {
DataBox dbox = (DataBox)list.get(i);
pstmt.setString(1, dbox.getString("d_subj") );
pstmt.setString(2, dbox.getString("d_year") );
pstmt.setString(3, dbox.getString("d_subjseq") );
pstmt.setString(4, dbox.getString("d_userid") );
pstmt.setString(5, dbox.getString("d_touch") );
pstmt.setString(6, dbox.getString("d_ismail") );
pstmt.setString(7, dbox.getString("d_edustart") );
pstmt.setString(8, dbox.getString("d_eduend") );
pstmt.setString(9, dbox.getString("d_title") );
pstmt.setString(10, dbox.getString("d_sdesc") );
pstmt.setString(11, dbox.getString("d_isok") );
pstmt.setString(12, dbox.getString("d_reason") );
pstmt.setString(13, dbox.getString("d_ismailopen") );
pstmt.setString(14, v_fromCono);
pstmt.setString(15, dbox.getString("d_subjnm") );
pstmt.setString(16, dbox.getString("d_seqgrnm") );
a += pstmt.executeUpdate(); System.out.println(a);
}
if ( list.size() == a) {
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
isOk = 1;
} else {
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
}
} catch ( Exception ex ) { ex.printStackTrace();
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
public int insertHumanTouch(DataBox dbox) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
String sql = "";
String sql1 = "";
int isOk = 0;
int a = 0;
String seq = "";
ListSet ls1 = null;
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql1 =" select nvl(ltrim(rtrim(to_char(to_number(max(SEQ)) +1,'0000000'))),'0000001') MSTCD " ;
sql1 += "From TZ_HUMANTOUCH ";
ls1 = connMgr.executeQuery(sql1);
if ( ls1.next() ) {
seq = ls1.getString("MSTCD");
}
else{
seq = "0000001";
}
sql = "insert into tz_humantouch(subj, year, subjseq, userid, touch, seq, ismail, edustart, eduend, title, sdesc, isok, reason, ismailopen, luserid, ldate, subjnm, seqgrnm)";
sql += " values (?, ?, ?, ?, ?, '" +seq + "', ?, ?, ?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?)";
System.out.println(sql);
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, dbox.getString("d_subj") );
pstmt.setString(2, dbox.getString("d_year") );
pstmt.setString(3, dbox.getString("d_subjseq") );
pstmt.setString(4, dbox.getString("d_userid") );
pstmt.setString(5, dbox.getString("d_touch") );
pstmt.setString(6, dbox.getString("d_ismail") );
pstmt.setString(7, dbox.getString("d_edustart") );
pstmt.setString(8, dbox.getString("d_eduend") );
pstmt.setString(9, dbox.getString("d_title") );
pstmt.setString(10, dbox.getString("d_sdesc") );
pstmt.setString(11, dbox.getString("d_isok") );
pstmt.setString(12, dbox.getString("d_reason") );
pstmt.setString(13, dbox.getString("d_ismailopen") );
pstmt.setString(14, v_fromCono);
pstmt.setString(15, dbox.getString("d_subjnm") );
pstmt.setString(16, dbox.getString("d_seqgrnm") );
System.out.println("1, " +dbox.getString("d_subj") );
System.out.println("2, " +dbox.getString("d_year") );
System.out.println("3, " +dbox.getString("d_subjseq") );
System.out.println("4, " +dbox.getString("d_userid") );
System.out.println("5, " +dbox.getString("d_touch") );
System.out.println("6, " +dbox.getString("d_ismail") );
System.out.println("7, " +dbox.getString("d_edustart") );
System.out.println("8, " +dbox.getString("d_eduend") );
System.out.println("9, " +dbox.getString("d_title") );
System.out.println("10," +dbox.getString("d_sdesc") );
System.out.println("11," +dbox.getString("d_isok") );
System.out.println("12," +dbox.getString("d_reason") );
System.out.println("13," +dbox.getString("d_ismailopen") );
System.out.println("14," +v_fromCono);
System.out.println("15," +dbox.getString("d_subjnm") );
System.out.println("16," +dbox.getString("d_seqgrnm") );
isOk = pstmt.executeUpdate();
if ( isOk > 0 ) {
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
} else {
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
}
} catch ( Exception ex ) { ex.printStackTrace();
if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } }
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
}
|
package com.interestcalc;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
public class Transactions {
public static ArrayList<Transaction> transactions=new ArrayList<Transaction>();
private static Transaction addEntry(Transaction transaction) {
Date entryDate=transaction.transactionDate;
for(int i=0;i<transactions.size();i++) {
if(entryDate.equals(transactions.get(i).transactionDate))
{
transactions.remove(i);
transactions.add(i, transaction);
return transaction;
}
if(entryDate.before(transactions.get(i).transactionDate))
{
transactions.add(i, transaction);
return transaction;
}
}
transactions.add(transaction);
return transaction;
}
public static Transaction addPartDisbursement(String transactionDate, long amount) {
Transaction transaction=new Transaction(transactionDate, amount, "PartDisbursement");
transaction.roi=ROITrend.getRate(transactionDate);
return addEntry(transaction);
}
public static Transaction addPartPayment(String transactionDate, long amount) {
Transaction transaction=new Transaction(transactionDate, amount, "PartPayment");
transaction.roi=ROITrend.getRate(transactionDate);
return addEntry(transaction);
}
public static Transaction addPreEmi(Transaction transaction) {
transaction.transactionType="PreEMI";
transaction.roi=ROITrend.getRate(transaction.transactionDateStr);
return addEntry(transaction);
}
public static Transaction addEmi(Transaction transaction) {
transaction.transactionType="EMI";
transaction.roi=ROITrend.getRate(transaction.transactionDateStr);
return addEntry(transaction);
}
public static Transaction addPreEMIInterestCorrection(String transactionDate, long interest) {
Transaction transaction=new Transaction(transactionDate, 0, "PreEMIInterestCorrection");
transaction.interestComponent=interest;
transaction.roi=ROITrend.getRate(transactionDate);
return addEntry(transaction);
}
public static Transaction addEMIInterestCorrection(String transactionDate, long interest) {
Transaction transaction=new Transaction(transactionDate, 0, "EMIInterestCorrection");
transaction.interestComponent=interest;
transaction.roi=ROITrend.getRate(transactionDate);
return addEntry(transaction);
}
public static Transaction addGeneralCorrection(Transaction transaction) {
transaction.transactionType="GeneralCorrection";
return addEntry(transaction);
}
public static Transaction getTransaction(String transactionDate) {
Date entryDate=null;
try {
entryDate = InterestCalculator.sdf.parse(transactionDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<transactions.size();i++) {
if(entryDate.equals(transactions.get(i).transactionDate))
{
return transactions.get(i);
}
}
return null;
}
}
|
package com.davivienda.utilidades.ws.cliente.notaCredito;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ProductoCorrienteResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ProductoCorrienteResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="oficinaCredito" type="{http://www.w3.org/2001/XMLSchema}short"/>
* <element name="talonCredito" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="motivoCredito" type="{http://www.w3.org/2001/XMLSchema}short"/>
* <element name="fechaAplicacionCredito" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="valorNotaCredito" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* <element name="cuentaCorriente" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="referencia1" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProductoCorrienteResponseType", propOrder = {
"oficinaCredito",
"talonCredito",
"motivoCredito",
"fechaAplicacionCredito",
"valorNotaCredito",
"cuentaCorriente",
"referencia1"
})
public class ProductoCorrienteResponseType {
protected short oficinaCredito;
@XmlElement(required = true)
protected String talonCredito;
protected short motivoCredito;
protected int fechaAplicacionCredito;
@XmlElement(required = true)
protected BigDecimal valorNotaCredito;
protected long cuentaCorriente;
@XmlElement(required = true)
protected String referencia1;
/**
* Gets the value of the oficinaCredito property.
*
*/
public short getOficinaCredito() {
return oficinaCredito;
}
/**
* Sets the value of the oficinaCredito property.
*
*/
public void setOficinaCredito(short value) {
this.oficinaCredito = value;
}
/**
* Gets the value of the talonCredito property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTalonCredito() {
return talonCredito;
}
/**
* Sets the value of the talonCredito property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTalonCredito(String value) {
this.talonCredito = value;
}
/**
* Gets the value of the motivoCredito property.
*
*/
public short getMotivoCredito() {
return motivoCredito;
}
/**
* Sets the value of the motivoCredito property.
*
*/
public void setMotivoCredito(short value) {
this.motivoCredito = value;
}
/**
* Gets the value of the fechaAplicacionCredito property.
*
*/
public int getFechaAplicacionCredito() {
return fechaAplicacionCredito;
}
/**
* Sets the value of the fechaAplicacionCredito property.
*
*/
public void setFechaAplicacionCredito(int value) {
this.fechaAplicacionCredito = value;
}
/**
* Gets the value of the valorNotaCredito property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValorNotaCredito() {
return valorNotaCredito;
}
/**
* Sets the value of the valorNotaCredito property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValorNotaCredito(BigDecimal value) {
this.valorNotaCredito = value;
}
/**
* Gets the value of the cuentaCorriente property.
*
*/
public long getCuentaCorriente() {
return cuentaCorriente;
}
/**
* Sets the value of the cuentaCorriente property.
*
*/
public void setCuentaCorriente(long value) {
this.cuentaCorriente = value;
}
/**
* Gets the value of the referencia1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferencia1() {
return referencia1;
}
/**
* Sets the value of the referencia1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferencia1(String value) {
this.referencia1 = value;
}
}
|
package com.turios.activities.listeners;
import javax.inject.Inject;
import android.location.Location;
public class TuriosLocationListener implements
com.google.android.gms.location.LocationListener {
@Inject public TuriosLocationListener() {
}
@Override public void onLocationChanged(Location location) {
// ModulesAggregator.getLocationsCoreModule().setLastLocation(location);
//
// AddressHolder addressHolder =
// activity.get().getSelectedAddressHolder();
//
// final HydrantsModule hydrantsModule =
// ModulesAggregator.getHydrantsModule();
//
// if (Device.isMultiPane(activity.get()) && addressHolder != null
// && addressHolder.position != null
// &&
// !ModulesAggregator.getHydrantsModule().isNearbyHydrantsAdded()) {
// int loadRadius = ModulesAggregator.getHydrantsModule()
// .getHydrantsLoadradius();
// float distanceToDistination = MapUtils.distBetween(new LatLng(
// location.getLatitude(), location.getLongitude()),
// addressHolder.position);
// if (distanceToDistination <= loadRadius) {
// final GoogleMapsModule googleMapsModule =
// ModulesAggregator.getGoogleMapsModule();
// final DisplayCoreModule displayCoreModule =
// ModulesAggregator.getDisplayCoreModule();
// final AddressHolder addressHolder =
// displayCoreModule.getAddressHolder(mPageid);
// final Location lastlocation =
// ModulesAggregator.getLocationsCoreModule().getLastLocation();
// hydrantsModule.addHydrantsNearAddress(googleMapsModule,
// addressHolder, lastlocation, true,
// activity.get().getSupportFragmentManager());
// }
// }
}
}
|
package billing_system;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
public class billing_system implements ActionListener{
private JFrame frame;
private JTextField txt_name;
private JTextField txt_contact;
private JTextField txt_email;
private JTextField txt_address;
private JTextField product_id;
private JTextField Product_name;
private JTextField Rate;
private JTextField Quantity;
private JTextField Description;
private final JSeparator separator_3 = new JSeparator();
private JTable table;
private JTextField Total_txt;
private JTextField Pamount_txt;
private JTextField Ramount_txt;
JButton btnsave;
private int final_Total =0;
/////////////////////////// LAUNCHING THE APPLICATION /////////////////////////////////////////////////////////////////////////
public static void BillingScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
billing_system window = new billing_system();
window.frame.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// CREATING THE APPLICATION /////////////////////////////////////////////////////////////////////
public billing_system() {
initialize();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// BILLING SYSTEM FRAME ///////////////////////////////////////////////////////////////////////
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1175, 607);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// MAIN FRAME LABELS //////////////////////////////////////////////////////////////////////////
// DATE LABEL
JLabel lblDate = new JLabel("Date:");
lblDate.setFont(new Font("Tahoma", Font.BOLD, 16));
lblDate.setBounds(893, 10, 61, 25);
frame.getContentPane().add(lblDate);
JLabel dateShow = new JLabel("Dateshow");
dateShow.setFont(new Font("Tahoma", Font.BOLD, 16));
dateShow.setBounds(980, 10, 118, 25);
SimpleDateFormat dFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date = new Date();
dateShow.setText(dFormat.format(date));
frame.getContentPane().add(dateShow);
// TIME LABEL
JLabel lblTime = new JLabel("Time:");
lblTime.setFont(new Font("Tahoma", Font.BOLD, 16));
lblTime.setBounds(893, 45, 61, 25);
frame.getContentPane().add(lblTime);
JLabel time_show = new JLabel("Time_show");
time_show.setFont(new Font("Tahoma", Font.BOLD, 16));
time_show.setBounds(980, 45, 89, 25);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm:ss");
LocalDateTime now = LocalDateTime.now();
time_show.setText(dtf.format(now));
frame.getContentPane().add(time_show);
// SEPARATOR
JSeparator separator = new JSeparator();
separator.setBackground(Color.BLACK);
separator.setBounds(0, 104, 1162, 10);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(10, 239, 683, -17);
frame.getContentPane().add(separator_1);
JSeparator separator_2 = new JSeparator();
separator_2.setBackground(Color.BLACK);
separator_2.setBounds(-15, 213, 1174, 10);
frame.getContentPane().add(separator_2);
separator_3.setBackground(Color.BLACK);
separator_3.setBounds(0, 351, 1162, 10);
frame.getContentPane().add(separator_3);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// BUYER LABELS /////////////////////////////////////////////////////////////////////////////////////////////
// BUYER DETAIL TITLE
JLabel lblByer_detail = new JLabel("Buyer Details:");
lblByer_detail.setFont(new Font("Tahoma", Font.BOLD, 16));
lblByer_detail.setBounds(10, 108, 132, 35);
frame.getContentPane().add(lblByer_detail);
// BUYER NAME
JLabel lblName = new JLabel("Name\r\n");
lblName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblName.setBounds(10, 165, 61, 25);
frame.getContentPane().add(lblName);
// BUYER CONTACT LABEL
JLabel lblContact = new JLabel("Contact No");
lblContact.setFont(new Font("Tahoma", Font.BOLD, 14));
lblContact.setBounds(266, 167, 124, 21);
frame.getContentPane().add(lblContact);
// BUYER EMAIL LABEL
JLabel lblEmail = new JLabel("Email");
lblEmail.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEmail.setBounds(593, 167, 89, 21);
frame.getContentPane().add(lblEmail);
// BUYER ADDRESS LABEL
JLabel lblAddress = new JLabel("Address");
lblAddress.setFont(new Font("Tahoma", Font.BOLD, 14));
lblAddress.setBounds(856, 166, 82, 22);
frame.getContentPane().add(lblAddress);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// BUYER TEXT FIELD ////////////////////////////////////////
// BUYER NAME
txt_name = new JTextField();
txt_name.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Name = txt_name.getText();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/billing_system","root","karma16502@");
Statement myStmt = myConn.createStatement();
ResultSet rs = myStmt.executeQuery("select name,contact_no,email,address from tbl_buyer where name like '"+Name+"%' ");
if(rs.next()) {
txt_name.setText(rs.getString(1));
txt_contact.setText(rs.getString(2));
txt_email.setText(rs.getString(3));
txt_address.setText(rs.getString(4));
}
else {
txt_contact.setText("");
txt_email.setText("");
txt_address.setText("");
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e);
}
}
});
txt_name.setFont(new Font("Tahoma", Font.PLAIN, 14));
txt_name.setBounds(81, 165, 146, 25);
frame.getContentPane().add(txt_name);
txt_name.setColumns(10);
// BUYER CONTACT
txt_contact = new JTextField();
txt_contact.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Contact = txt_contact.getText();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/billing_system","root","karma16502@");
Statement myStmt = myConn.createStatement();
ResultSet rs = myStmt.executeQuery("select name,contact_no,email,address from tbl_buyer where contact_no like '"+Contact+"%' ");
if(rs.next()) {
txt_name.setText(rs.getString(1));
txt_contact.setText(rs.getString(2));
txt_email.setText(rs.getString(3));
txt_address.setText(rs.getString(4));
}
else {
txt_contact.setText("");
txt_email.setText("");
txt_address.setText("");
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e);
}
}
});
txt_contact.setFont(new Font("Tahoma", Font.PLAIN, 14));
txt_contact.setBounds(368, 165, 160, 25);
frame.getContentPane().add(txt_contact);
txt_contact.setColumns(10);
// BUYER EMAIL
txt_email = new JTextField();
txt_email.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Email = txt_email.getText();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/billing_system","root","karma16502@");
Statement myStmt = myConn.createStatement();
ResultSet rs = myStmt.executeQuery("select name,contact_no,email,address from tbl_buyer where email like '"+Email+"%' ");
if(rs.next()) {
txt_name.setText(rs.getString(1));
txt_contact.setText(rs.getString(2));
txt_email.setText(rs.getString(3));
txt_address.setText(rs.getString(4));
}
else {
txt_contact.setText("");
txt_email.setText("");
txt_address.setText("");
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e);
}
}
});
txt_email.setFont(new Font("Tahoma", Font.PLAIN, 14));
txt_email.setBounds(666, 165, 141, 25);
frame.getContentPane().add(txt_email);
txt_email.setColumns(10);
// BUYER ADDRESS
txt_address = new JTextField();
txt_address.setFont(new Font("Tahoma", Font.PLAIN, 14));
txt_address.setBounds(960, 165, 170, 25);
frame.getContentPane().add(txt_address);
txt_address.setColumns(10);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// PRODUCTS LABELS /////////////////////////////////////////////
// PRODUCT TITLE LABEL
JLabel LblProduct_Detail = new JLabel("Product Details:");
LblProduct_Detail.setFont(new Font("Tahoma", Font.BOLD, 16));
LblProduct_Detail.setBounds(10, 224, 160, 38);
frame.getContentPane().add(LblProduct_Detail);
// PRODUCT ID LABEL
JLabel lblProductID = new JLabel("Product ID");
lblProductID.setFont(new Font("Tahoma", Font.BOLD, 14));
lblProductID.setBounds(10, 272, 101, 21);
frame.getContentPane().add(lblProductID);
// PRODUCT NAME LABEL
JLabel lblPName = new JLabel("Product Name");
lblPName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblPName.setBounds(177, 274, 124, 17);
frame.getContentPane().add(lblPName);
// PRODUCT RATE LABEL
JLabel lblRate = new JLabel("Rate");
lblRate.setFont(new Font("Tahoma", Font.BOLD, 14));
lblRate.setBounds(487, 274, 72, 17);
frame.getContentPane().add(lblRate);
// PRODUCT QUANTITY LABEL
JLabel lblQuantity = new JLabel("Quantity");
lblQuantity.setFont(new Font("Tahoma", Font.BOLD, 14));
lblQuantity.setBounds(697, 274, 72, 17);
frame.getContentPane().add(lblQuantity);
// PRODUCT DESCRIPTION LABEL
JLabel lblDescription = new JLabel("Description");
lblDescription.setFont(new Font("Tahoma", Font.BOLD, 14));
lblDescription.setBounds(856, 274, 87, 17);
frame.getContentPane().add(lblDescription);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////// PRODUCT TEXT FIELD //////////////////////////////////////////
// PRODUCT ID
product_id = new JTextField();
product_id.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Product_ID = product_id.getText();
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/billing_system","root","karma16502@");
Statement myStmt = myConn.createStatement();
ResultSet rs = myStmt.executeQuery("select * from tbl_product where product_id like '"+Product_ID+"%' ");
if(rs.next()) {
product_id.setText(rs.getString(1));
Product_name.setText(rs.getString(2));
Rate.setText(rs.getString(3));
Quantity.setText(rs.getString(4));
Description.setText(rs.getString(5));
}
else {
Product_name.setText(" ");
Rate.setText(" ");
Quantity.setText(" ");
Description.setText(" ");
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e);
}
}
}); product_id.setFont(new Font("Tahoma", Font.PLAIN, 14));
product_id.setBounds(92, 270, 61, 25);
frame.getContentPane().add(product_id);
product_id.setColumns(10);
// PRODUCT NAME
Product_name = new JTextField();
Product_name.setFont(new Font("Tahoma", Font.PLAIN, 14));
Product_name.setBounds(303, 270, 141, 25);
frame.getContentPane().add(Product_name);
Product_name.setColumns(10);
// PRODUCT RATE
Rate = new JTextField();
Rate.setFont(new Font("Tahoma", Font.PLAIN, 14));
Rate.setBounds(553, 270, 89, 25);
frame.getContentPane().add(Rate);
Rate.setColumns(10);
// PRODUCT QUANTITY
Quantity = new JTextField();
Quantity.setBounds(774, 272, 72, 25);
frame.getContentPane().add(Quantity);
Quantity.setColumns(10);
// PRODUCT DESCRIPTION
Description = new JTextField();
Description.setBounds(960, 272, 170, 25);
frame.getContentPane().add(Description);
Description.setColumns(10);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////// SCROLL PANEL && TABLE /////////////////////////////////////
// SCROLL PANEL
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 362, 533, 201);
frame.getContentPane().add(scrollPane);
// TABLE
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Name", "Product ID", "Description", "Rate", "Quantity", "Total"
}
));
table.getColumnModel().getColumn(0).setPreferredWidth(80);
table.getColumnModel().getColumn(2).setPreferredWidth(90);
table.getColumnModel().getColumn(3).setPreferredWidth(70);
table.getColumnModel().getColumn(4).setPreferredWidth(70);
table.getColumnModel().getColumn(5).setPreferredWidth(80);
table.setFillsViewportHeight(true);
table.setFont(new Font("Tahoma", Font.PLAIN, 14));
scrollPane.setViewportView(table);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// FINAL CALCULATION LABEL ////////////////////////////////////////////////
// CALCULATION TITLE
JLabel lblCalculation = new JLabel("Calculation Details:");
lblCalculation.setFont(new Font("Tahoma", Font.BOLD, 16));
lblCalculation.setBounds(553, 361, 167, 25);
frame.getContentPane().add(lblCalculation);
// TOTAL LABEL
JLabel lblTotal = new JLabel("Total");
lblTotal.setFont(new Font("Tahoma", Font.BOLD, 14));
lblTotal.setBounds(553, 398, 80, 35);
frame.getContentPane().add(lblTotal);
// PAID AMOUNT LABEL
JLabel lblPAmount = new JLabel("Paid Amount");
lblPAmount.setFont(new Font("Tahoma", Font.BOLD, 14));
lblPAmount.setBounds(553, 447, 96, 35);
frame.getContentPane().add(lblPAmount);
// RETURN AMOUT LABEL
JLabel lblRamount = new JLabel("Return Amount");
lblRamount.setFont(new Font("Tahoma", Font.BOLD, 14));
lblRamount.setBounds(553, 502, 111, 35);
frame.getContentPane().add(lblRamount);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// FINALE CALCULATION TEXT FIELD //////////////////////////////////////////////////
// TOTAL
Total_txt = new JTextField();
Total_txt.setFont(new Font("Tahoma", Font.PLAIN, 14));
Total_txt.setBounds(682, 403, 302, 30);
frame.getContentPane().add(Total_txt);
Total_txt.setColumns(10);
// PAID AMOUNT
Pamount_txt = new JTextField();
Pamount_txt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String paidAmount = Pamount_txt.getText();
int z = Integer.parseInt(paidAmount);
final_Total = z - final_Total;
String final_Total1 = String.valueOf(final_Total);
Ramount_txt.setText(final_Total1);
Ramount_txt.setEditable(false);
}
});
Pamount_txt.setFont(new Font("Tahoma", Font.PLAIN, 14));
Pamount_txt.setBounds(682, 450, 302, 30);
frame.getContentPane().add(Pamount_txt);
Pamount_txt.setColumns(10);
// RETURN AMOUNT
Ramount_txt = new JTextField();
Ramount_txt.setFont(new Font("Tahoma", Font.PLAIN, 14));
Ramount_txt.setBounds(682, 505, 302, 30);
frame.getContentPane().add(Ramount_txt);
Ramount_txt.setColumns(10);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// BUTTONS /////////////////////////////////////////////////////////////////////////////////
// ADD BUTTON
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int price = Integer.parseInt(Rate.getText());
int quantity = Integer.parseInt(Quantity.getText());
int total = price*quantity;
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object [] {Product_name.getText(),product_id.getText(), Description.getText(),price,quantity,total});
final_Total = final_Total + total;
String finalTotal1=String.valueOf(final_Total);
Total_txt.setText(finalTotal1);
}
});
btnAdd.setIcon(new ImageIcon("C:\\java_folder\\OOP_project\\src\\billing_system\\add.png"));
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 14));
btnAdd.setBounds(1012, 304, 118, 41);
frame.getContentPane().add(btnAdd);
// CLEAR BUTTON
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txt_name.setText("");
txt_contact.setText("");
txt_email.setText("");
txt_address.setText("");
Product_name.setText(" ");
product_id.setText(" ");
Rate.setText(" ");
Quantity.setText(" ");
Description.setText(" ");
Total_txt.setText("");
Pamount_txt.setText("");
Ramount_txt.setText("");
((DefaultTableModel)table.getModel()).setNumRows(0);
final_Total=0;
}
});
btnClear.setIcon(new ImageIcon("C:\\java_folder\\OOP_project\\src\\billing_system\\clear1.png"));
btnClear.setFont(new Font("Tahoma", Font.BOLD, 14));
btnClear.setBounds(1012, 442, 118, 45);
frame.getContentPane().add(btnClear);
// EXIT
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int opt=JOptionPane.showConfirmDialog(null,"Are you sure to Exit?","Exit",JOptionPane.YES_NO_OPTION);
if (opt==0) {
dispose_frame();
}
}
private void dispose_frame() {
// TODO Auto-generated method stub
frame.dispose();
}
});
btnExit.setIcon(new ImageIcon("C:\\java_folder\\OOP_project\\src\\billing_system\\exit1.png"));
btnExit.setFont(new Font("Tahoma", Font.BOLD, 14));
btnExit.setBounds(1012, 502, 118, 45);
frame.getContentPane().add(btnExit);
// SAVE BUTTON
JButton btnsave = new JButton("Save");
btnsave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String Name =txt_name.getText();
String contact =txt_contact.getText();
String Pname = Product_name.getText();
String Pid = product_id.getText();
String Total =Total_txt.getText();
String paid_amount = Pamount_txt.getText();
String return_amount= Ramount_txt.getText();
if (e.getSource() == btnsave) {
database_connector dc= new database_connector();
String query = "insert into final_data"
+ "(customer_name,contact_no, product_name,product_id,total,paid_amount,return_amount) "
+ "values('" +Name + "','" + contact + "','" + Pname + "','" + Pid+ "','" +Total + "','" + paid_amount + "','" + return_amount + "')";
int val= dc.insert(query);
if (val>0) {
JOptionPane.showMessageDialog(frame,"Data Save Successflly");
}
else {
JOptionPane.showMessageDialog(frame, "Failed to save the data");
}
}
}
});
btnsave.setFont(new Font("Tahoma", Font.BOLD, 14));
btnsave.setIcon(new ImageIcon("C:\\java_folder\\OOP_project\\src\\billing_system\\save.png"));
btnsave.setBounds(1012, 382, 118, 45);
frame.add(btnsave);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// BACKGROUND IMAGE && PROJECT TITLE ////////////////////////////////////////////////////////
// TITLE LABEL
JLabel lblTitle = new JLabel("Billing System");
lblTitle.setFont(new Font("Times New Roman", Font.BOLD, 63));
lblTitle.setBounds(67, 6, 436, 84);
frame.getContentPane().add(lblTitle);
// BACKGROUND IMAGE LABEL
JLabel lblBackground = new JLabel(" ");
lblBackground.setIcon(new ImageIcon("C:\\java_folder\\OOP_project\\src\\billing_system\\bg2.png"));
lblBackground.setBounds(4, 0, 1158, 611);
frame.getContentPane().add(lblBackground);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
protected void setVisible(boolean b) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
|
package com.zju.courier.service.impl;
import com.zju.courier.dao.ApInfoDao;
import com.zju.courier.dao.CriteriaDao;
import com.zju.courier.dao.RankDao;
import com.zju.courier.entity.APInfo;
import com.zju.courier.entity.Criteria;
import com.zju.courier.entity.Rank;
import com.zju.courier.pojo.Score;
import com.zju.courier.service.MonthRankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class MonthRankServiceImpl implements MonthRankService {
@Autowired
private ApInfoDao apInfoDao;
@Autowired
private RankDao rankDao;
@Autowired
private CriteriaDao criteriaDao;
private static float NUM = 0.1201f;
private static float TIMES = 0.1609f;
private static float TOTAL = 0.2343f;
private static float AVG = 0.4536f;
private static float DISTANCE= 0.0499f;
@Override
public List<Score> rank(String year, String month) {
Map<Integer, Score> map = new HashMap<>(32);
List<APInfo> apInfoList = apInfoDao.list();
for (APInfo apInfo : apInfoList) {
Score score = new Score();
score.setApInfo(apInfo);
score.setApId(apInfo.getAp_id());
score.setDistance(apInfo.getDistance());
map.put(apInfo.getAp_id(), score);
}
List<Rank> ranks = rankDao.queryByMonth(year,month);
for (Rank rank : ranks) {
Score score = map.get(rank.getAp_id());
score.setNum(score.getNum() + rank.getNum_pre());
score.setTimes(score.getTimes() + rank.getTimes_pre());
score.setTotal(score.getTotal() + rank.getTotal_time());
score.setDays(score.getDays() + 1);
}
for (Score score : map.values()) {
score.setAvg(score.getTotal()/score.getNum());
}
Criteria criteria = criteriaDao.query(1);
int days = map.get(1).getDays();
float MAX_NUM = criteria.getNum_pre() * days;
float MAX_TIMES = criteria.getTimes_pre() * days;
float MAX_TOTAL = criteria.getTotal_time() * days;
float MAX_AVG = MAX_TOTAL/MAX_NUM;
float MAX_DIS = criteria.getDistance();
for (Score score : map.values()) {
float num = (score.getNum() > MAX_NUM ? 1f : score.getNum() / MAX_NUM) * NUM;
float times = (score.getTimes() > MAX_TIMES ? 1f : score.getTimes() / MAX_TIMES) * TIMES;
float total = (score.getTotal() > MAX_TOTAL ? 1f : score.getTotal() / MAX_TOTAL) * TOTAL;
float avg = (score.getAvg() > MAX_AVG ? 1f : score.getAvg() / MAX_AVG) * AVG;
float distance = (score.getDistance() > MAX_DIS ? 1f : score.getDistance() / MAX_DIS) * DISTANCE;
float result = (num+times+total+avg+distance) *100;
score.setScore((float) Math.round(result*100)/100);
}
List<Score> values = new ArrayList<>(map.values());
values.sort(new Comparator<Score>() {
@Override
public int compare(Score o1, Score o2) {
return Float.compare(o2.getScore(), o1.getScore());
}
});
return values;
}
}
|
package com.upgrade.mvc.biz;
import java.util.List;
import com.upgrade.mvc.dto.EmpDto;
public interface EmpBiz {
public List<EmpDto> selectList();
public EmpDto selectOne(String id);
public int insert(EmpDto dto);
public int update(EmpDto dto);
public int delete(String id);
}
|
package com.kmdc.mdu.oaid;
import android.content.Context;
import com.bun.miitmdid.core.InfoCode;
import com.kmdc.mdu.BuildConfig;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import zizzy.zhao.bridgex.l.L;
class MsaSdkClient2 {
static String getOaid(Context context, long maxWaitTimeInMilli) {
final BlockingQueue<String> oaidHolder = new LinkedBlockingQueue<>(1);
try {
boolean msaInternalLogging = BuildConfig.DEBUG;
// int result = MdidSdkHelper.InitSdk(context, msaInternalLogging, idSupplier -> {
// try {
// if (idSupplier == null || idSupplier.getOAID() == null) {
// // so to avoid waiting for timeout
// oaidHolder.offer("");
// } else {
// oaidHolder.offer(idSupplier.getOAID());
// }
// } catch (Exception e) {
// L.e(+ "-" + SDK_CODE, "Fail to add " + e.getMessage());
// }
// });
int result = -1;
/* Implementation using reflection */
// Method initSdk = MdidSdkHelper.class.getDeclaredMethod("InitSdk",
// Context.class, boolean.class,
// IIdentifierListener.class);
// result = (int) initSdk.invoke(MdidSdkHelper.class, context, msaInternalLogging,
// (IIdentifierListener) idSupplier -> {
// try {
// if (idSupplier == null || idSupplier.getOAID() == null) {
// // so to avoid waiting for timeout
// oaidHolder.offer("");
// } else {
// oaidHolder.offer(idSupplier.getOAID());
// }
// } catch (Exception e) {
// L.e(+ "-" + SDK_CODE, "Fail to add " + e.getMessage());
// }
// });
Class iIdentifierListenerV23 = null;
Class iIdentifierListenerV13 = null;
boolean isMiitMdidAboveV23 = false;
boolean isMiitMdidOnV13 = false;
Class iIdentifierListener = null;
try {
iIdentifierListenerV23 = Reflection.forName(
"com.bun.miitmdid.interfaces.IIdentifierListener");
} catch (ClassNotFoundException e) {
L.e("call forName error: " + e);
try {
iIdentifierListenerV13 = Reflection.forName(
"com.bun.supplier.IIdentifierListener");
} catch (ClassNotFoundException e1) {
L.e("call forName error: " + e1);
}
}
isMiitMdidAboveV23 = iIdentifierListenerV23 != null;
if (isMiitMdidAboveV23) {
L.i("Using MIIT MID Above V1.0.23");
} else {
isMiitMdidOnV13 = iIdentifierListenerV13 != null;
if (isMiitMdidOnV13) {
L.i("Using MIIT MID V1.0.13");
}
}
if (isMiitMdidAboveV23) {
iIdentifierListener = iIdentifierListenerV23;
} else if (isMiitMdidOnV13) {
iIdentifierListener = iIdentifierListenerV13;
}
Object iIdentifierListenerProxy = Proxy.newProxyInstance(
iIdentifierListener.getClassLoader(),
new Class[]{iIdentifierListener},
new HookHandler(oaidHolder)
);
Class mdidSdkHelper = null;
try {
mdidSdkHelper = Reflection.forName("com.bun.miitmdid.core.MdidSdkHelper");
} catch (ClassNotFoundException e) {
L.e("call forName error: " + e);
}
try {
result = (int) Reflection.invokeMethod(
mdidSdkHelper,
"InitSdk",
null,
new Class[]{Context.class, boolean.class, iIdentifierListener},
context, msaInternalLogging, iIdentifierListenerProxy
);
} catch (Throwable t) {
L.e("call invokeMethod error: " + t);
}
if (!isError(result)) {
return oaidHolder.poll(maxWaitTimeInMilli, TimeUnit.MILLISECONDS);
}
} catch (NoClassDefFoundError ex) {
L.e("Couldn't find msa sdk: " + ex.getMessage());
} catch (InterruptedException e) {
L.e("Waiting to read oaid from callback interrupted: " + e.getMessage());
} catch (Throwable t) {
L.e("Oaid reading process failed: " + t.getMessage());
}
return null;
}
private static boolean isError(int result) {
switch (result) {
case InfoCode.INIT_ERROR_CERT_ERROR: // 证书未初始化或证书无效,SDK 内部不会回调 onSupport
L.e("msa sdk error - INIT_ERROR_CERT_ERROR");
return true;
case InfoCode.INIT_ERROR_DEVICE_NOSUPPORT: // 不支持的设备, SDK 内部不会回调 onSupport
L.e("msa sdk error - INIT_ERROR_DEVICE_NOSUPPORT");
return true;
case InfoCode.INIT_ERROR_LOAD_CONFIGFILE: // 加载配置文件出错, SDK 内部不会回调 onSupport
L.e("msa sdk error - INIT_ERROR_LOAD_CONFIGFILE");
return true;
case InfoCode.INIT_ERROR_MANUFACTURER_NOSUPPORT: // 不支持的设备厂商, SDK 内部不会回调 onSupport
L.e("msa sdk error - INIT_ERROR_MANUFACTURER_NOSUPPORT");
return true;
case InfoCode.INIT_ERROR_SDK_CALL_ERROR: // SDK 调用出错, SDK 内部不会回调 onSupport
L.e("msa sdk error - INIT_ERROR_SDK_CALL_ERROR");
return true;
case InfoCode.INIT_INFO_RESULT_DELAY: // 获取接口是异步的, SDK 内部会回调 onSupport
L.w("msa sdk success - INIT_INFO_RESULT_DELAY");
return false;
case InfoCode.INIT_INFO_RESULT_OK: // 获取接口是同步的, SDK 内部会回调 onSupport
L.i("msa sdk success - INIT_INFO_RESULT_OK");
return false;
default:
L.e("MdidSdkHelper.InitSdk result: " + result);
return true;
}
}
static class HookHandler implements InvocationHandler {
private BlockingQueue<String> oaidHolder;
public HookHandler(BlockingQueue<String> oaidHolder) {
this.oaidHolder = oaidHolder;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
L.v("--- [" + method + "] called with args "
+ Arrays.toString(args));
Object idSupplier = null;
// com.bun.miitmdid.interfaces.IIdentifierListener.onSupport(com.bun.miitmdid.interfaces.IdSupplier)
if ("onSupport".equals(method.getName())) {
idSupplier = args[0];
}
// com.bun.miitmdid.interfaces.IIdentifierListener.OnSupport(boolean, com.bun.miitmdid.interfaces.IdSupplier)
else if ("OnSupport".equals(method.getName())) {
idSupplier = args[1];
}
try {
boolean isSupported = (boolean) Reflection.invokeInstanceMethod(
idSupplier,
"isSupported",
new Class[]{}
);
L.d("isSupported: " + isSupported);
} catch (Throwable t) {
L.e("Failed to invoke method: " + t);
}
try {
boolean isLimited = (boolean) Reflection.invokeInstanceMethod(
idSupplier,
"isLimited",
new Class[]{}
);
L.d("isLimited: " + isLimited);
} catch (Throwable t) {
L.e("Failed to invoke method: " + t);
}
try {
String vaid = (String) Reflection.invokeInstanceMethod(
idSupplier,
"getVAID",
new Class[]{}
);
L.d("vaid: " + vaid);
} catch (Throwable t) {
L.e("Failed to invoke method: " + t);
}
try {
String aaid = (String) Reflection.invokeInstanceMethod(
idSupplier,
"getAAID",
new Class[]{}
);
L.d("aaid: " + aaid);
} catch (Throwable t) {
L.e("Failed to invoke method: " + t);
}
try {
String oaid = (String) Reflection.invokeInstanceMethod(
idSupplier,
"getOAID",
new Class[]{}
);
L.d("oaid: " + oaid);
if (oaid == null) {
// so to avoid waiting for timeout
oaidHolder.offer("");
} else {
oaidHolder.offer(oaid);
}
} catch (Throwable t) {
L.e("Failed to invoke method: " + t);
}
return null;
}
}
}
|
package screen;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import bakery.*;
/**
* Screen for exporting store data
* @author rcj, anhtran9
* @version 06/17/14
*
*/
public class ExportData extends Screen {
/**
* Constructor to set the screen title
*/
public ExportData() {
this.title = "*** export data ***";
}
/**
* Export store data to files
*/
@SuppressWarnings("unused")
void run() {
System.out.println(this.toString());
try {
File file = new File("bakeryItems1.txt");
PrintStream output = new PrintStream(file);
output.println("BakeryItemID\tBakeryItemName\t"
+ "Category\tPrice\tQuantity");
for (Entry<Integer, Item> i :
Screen.state.getInventories().entrySet()) {
output.println(i.getValue().getId().toString() + "\t" +
i.getValue().getName() + "\t" +
i.getValue().getCategory() + "\t" +
i.getValue().getPrice().toString() + "\t" +
i.getValue().getQuantity().toString());
}
output.close();
file = new File("orders1.txt");
output = new PrintStream(file);
output.println("CustomerID\tLastName\tAddress\tCity\tState\t"
+ "ZipCode\tOrderID\tPaid?\tOrderDate\tPickupDate\t"
+ "BakeryItemID\tBakeryItemName\tBakeryItemCategory\t"
+ "Quantity\tPrice\tTotal\tDiscountUsedOnOrder\t"
+ "TotalDue\tAvailableDiscount\tCurrentLoyalty");
for (Entry<Integer, Order> ie : Screen.state.getOrders()
.entrySet()) {
Order order = ie.getValue();
Client client = order.getClient();
for (Entry<Item, Integer> allItems : order.getItems()
.entrySet()) {
Item item = allItems.getKey();
output.println(client.getId().toString()
+ "\t"
+ client.getLastName()
+ "\t"
+ client.getAddress()
+ "\t"
+ client.getCity()
+ "\t"
+ client.getState()
+ "\t"
+ client.getZipcode()
+ "\t"
+ order.getId().toString()
+ "\t"
+ Store.convertToString(order.getPaid())
+ "\t"
+ order.getOrderDate()
+ "\t"
+ order.getPickupDate()
+ "\t"
+ item.getId().toString()
+ "\t"
+ item.getName()
+ "\t"
+ item.getCategory()
+ "\t"
+ allItems.getValue()
+ "\t"
+ item.getPrice().toString()
+ "\t"
+ order.total().toString()
+ "\t"
+ ((Double) (order.total() -
order.totalDue())).toString()
+ "\t"
+ order.totalDue().toString()
+ "\t"
+ order.rewardToString()
+ "\t"
+ order.pointsToString());
}
}
}
catch (IOException io) {
System.out.println("error");
}
System.out.println("Press any key to go back ");
Scanner scan = new Scanner(System.in);
String input = scan.next();
this.prev.run();
}
}
|
package org.shujito.cartonbox.view.adapter;
import java.util.ArrayList;
import java.util.List;
import org.shujito.cartonbox.R;
import org.shujito.cartonbox.controller.listener.OnErrorListener;
import org.shujito.cartonbox.controller.task.ImageDownloader;
import org.shujito.cartonbox.controller.task.listener.OnImageFetchedListener;
import org.shujito.cartonbox.controller.task.listener.OnXmlResponseReceivedListener;
import org.shujito.cartonbox.model.BlogEntry;
import org.shujito.cartonbox.model.parser.XmlParser;
import org.shujito.cartonbox.util.ConcurrentTask;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class BlogListAdapter extends BaseAdapter implements OnXmlResponseReceivedListener, OnErrorListener
{
Context context = null;
List<BlogEntry> entries = null;
public BlogListAdapter(Context context)
{
this.context = context;
}
@Override
public int getCount()
{
if(this.entries != null)
return entries.size();
return 0;
}
@Override
public Object getItem(int pos)
{
if(this.entries != null)
return this.entries.get(pos);
return null;
}
@Override
public long getItemId(int pos)
{
return 0;
}
@Override
public View getView(int pos, View v, ViewGroup dad)
{
if(v == null)
{
LayoutInflater inf = LayoutInflater.from(this.context);
v = inf.inflate(R.layout.item_blog, dad, false);
}
BlogEntry entry = this.entries.get(pos);
final TextView title = ((TextView)v.findViewById(R.id.tvTitle));
final TextView content = ((TextView)v.findViewById(R.id.tvContent));
final TextView date = ((TextView)v.findViewById(R.id.tvDate));
if(entry != null)
{
String blogContent = entry.getContent();
final SpannableString spannedContent = new SpannableString(Html.fromHtml(blogContent));
//SpannableString spstr = new SpannableString(blogContent);
//String dur = spannedContent.toString().trim();
ImageSpan[] imageSpans = spannedContent.getSpans(0, spannedContent.length() - 1, ImageSpan.class);
title.setText(entry.getTitle());
content.setText(spannedContent);
date.setText(entry.getDate());
for(ImageSpan imgSpan : imageSpans)
{
String source = imgSpan.getSource();
final int spanStart = spannedContent.getSpanStart(imgSpan);
final int spanEnd = spannedContent.getSpanEnd(imgSpan);
spannedContent.removeSpan(imgSpan);
ImageDownloader downloader = new ImageDownloader(this.context, source);
downloader.setWidth(256);
downloader.setHeight(256);
downloader.setOnImageFetchedListener(new OnImageFetchedListener()
{
@Override
public void onImageFetched(Bitmap b)
{
if(b != null)
{
ImageSpan newSpan = new ImageSpan(context, b);
spannedContent.setSpan(newSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
content.setText(spannedContent);
}
}
});
ConcurrentTask.execute(downloader);
}
//((TextView)v.findViewById(R.id.tvTitle)).setText(entry.getTitle());
//((TextView)v.findViewById(R.id.tvContent)).setText(spannedContent);
//((TextView)v.findViewById(R.id.tvDate)).setText(entry.getDate());
//((TextView)v.findViewById(R.id.blogitem_tvdate)).setText(Locale.getDefault().getDisplayLanguage());
}
else
{
//String datefmt = DateFormat.getDateTimeInstance().format(new Date());
title.setText(R.string.couldnotblog);
content.setText(R.string.trylater);
//((TextView)v.findViewById(R.id.blogitem_tvdate)).setText(datefmt);
date.setText(null);
}
return v;
}
@Override
@SuppressWarnings("unchecked")
public void onResponseReceived(XmlParser<?> xp)
{
// can be done in one line, it gives a warning
this.entries = (List<BlogEntry>)xp.get();
/* can be done with the following code, no warnings
this.entries = new ArrayList<BlogEntry>();
BlogEntry b = null;
int index = 0;
List<?> everything = xp.get();
// (b = (BlogEntry)xp.get().get(++index)) != null
while(everything.size() > index && (b = (BlogEntry)everything.get(index++)) != null)
{
if(b.getCategories() != null)
{
for(String cat : b.getCategories())
{
if(cat.contains("cartonbox"))
{
this.entries.add(b);
break;
}
}
}
}
//*/
this.notifyDataSetChanged();
}
@Override
public void onError(int code, String result)
{
this.entries = new ArrayList<BlogEntry>();
// add some dummy
this.entries.add(null);
this.notifyDataSetChanged();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.