repo_name
stringlengths 5
108
| path
stringlengths 6
333
| size
stringlengths 1
6
| content
stringlengths 4
977k
| license
stringclasses 15
values |
---|---|---|---|---|
TealCube/strife | src/main/java/land/face/strife/managers/CombatStatusManager.java | 2828 | /**
* The MIT License Copyright (c) 2015 Teal Cube Games
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package land.face.strife.managers;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import land.face.strife.StrifePlugin;
import land.face.strife.data.champion.Champion;
import land.face.strife.data.champion.LifeSkillType;
import org.bukkit.entity.Player;
public class CombatStatusManager {
private final StrifePlugin plugin;
private final Map<Player, Integer> tickMap = new ConcurrentHashMap<>();
private static final int SECONDS_TILL_EXPIRY = 8;
public CombatStatusManager(StrifePlugin plugin) {
this.plugin = plugin;
}
public boolean isInCombat(Player player) {
return tickMap.containsKey(player);
}
public void addPlayer(Player player) {
tickMap.put(player, SECONDS_TILL_EXPIRY);
}
public void tickCombat() {
for (Player player : tickMap.keySet()) {
if (!player.isOnline() || !player.isValid()) {
tickMap.remove(player);
continue;
}
int ticksLeft = tickMap.get(player);
if (ticksLeft < 1) {
doExitCombat(player);
tickMap.remove(player);
continue;
}
tickMap.put(player, ticksLeft - 1);
}
}
public void doExitCombat(Player player) {
if (!tickMap.containsKey(player)) {
return;
}
Champion champion = plugin.getChampionManager().getChampion(player);
if (champion.getDetailsContainer().getExpValues() == null) {
return;
}
for (LifeSkillType type : champion.getDetailsContainer().getExpValues().keySet()) {
plugin.getSkillExperienceManager().addExperience(player, type,
champion.getDetailsContainer().getExpValues().get(type), false, false);
}
champion.getDetailsContainer().clearAll();
}
}
| isc |
xiongmaoshouzha/test | jeecg-p3-biz-qywx/src/main/java/com/jeecg/qywx/core/service/TextDealInterfaceService.java | 326 | package com.jeecg.qywx.core.service;
import com.jeecg.qywx.base.entity.QywxReceivetext;
/**
* 文本处理接口
* @author 付明星
*
*/
public interface TextDealInterfaceService {
/**
* 文本消息处理接口
* @param receiveText 文本消息实体类
*/
void dealTextMessage(QywxReceivetext receiveText);
}
| mit |
selvasingh/azure-sdk-for-java | sdk/datafactory/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/datafactory/v2018_06_01/GoogleCloudStorageLocation.java | 2402 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datafactory.v2018_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* The location of Google Cloud Storage dataset.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class)
@JsonTypeName("GoogleCloudStorageLocation")
public class GoogleCloudStorageLocation extends DatasetLocation {
/**
* Specify the bucketName of Google Cloud Storage. Type: string (or
* Expression with resultType string).
*/
@JsonProperty(value = "bucketName")
private Object bucketName;
/**
* Specify the version of Google Cloud Storage. Type: string (or Expression
* with resultType string).
*/
@JsonProperty(value = "version")
private Object version;
/**
* Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @return the bucketName value
*/
public Object bucketName() {
return this.bucketName;
}
/**
* Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @param bucketName the bucketName value to set
* @return the GoogleCloudStorageLocation object itself.
*/
public GoogleCloudStorageLocation withBucketName(Object bucketName) {
this.bucketName = bucketName;
return this;
}
/**
* Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @return the version value
*/
public Object version() {
return this.version;
}
/**
* Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @param version the version value to set
* @return the GoogleCloudStorageLocation object itself.
*/
public GoogleCloudStorageLocation withVersion(Object version) {
this.version = version;
return this;
}
}
| mit |
dushantSW/ip-mobile | 7.3.1/DeviceInternetInformation/app/src/main/java/se/dsv/waora/deviceinternetinformation/ConnectionActivity.java | 2212 | package se.dsv.waora.deviceinternetinformation;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* <code>ConnectionActivity</code> presents UI for showing if the device
* is connected to internet.
*
* @author Dushant Singh
*/
public class ConnectionActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiate view
TextView connectivityStatus = (TextView) findViewById(R.id.textViewDeviceConnectivity);
// Get connectivity service.
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Get active network information
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
// Check if active network is connected.
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
// Set status connected
connectivityStatus.setText(getString(R.string.online));
connectivityStatus.setTextColor(getResources().getColor(R.color.color_on));
// Check if connected with wifi
boolean isWifiOn = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if (isWifiOn) {
// Set wifi status on
TextView wifiTextView = (TextView) findViewById(R.id.textViewWifi);
wifiTextView.setText(getString(R.string.on));
wifiTextView.setTextColor(getResources().getColor(R.color.color_on));
} else {
// Set mobile data status on.
TextView mobileDataTextView = (TextView) findViewById(R.id.textViewMobileData);
mobileDataTextView.setText(getString(R.string.on));
mobileDataTextView.setTextColor(getResources().getColor(R.color.color_on));
}
}
}
}
| mit |
Kwoin/KGate | kgate-core/src/main/java/com/github/kwoin/kgate/core/sequencer/AbstractSequencer.java | 3496 | package com.github.kwoin.kgate.core.sequencer;
import com.github.kwoin.kgate.core.message.Message;
import com.github.kwoin.kgate.core.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;
/**
* @author P. WILLEMET
*/
public abstract class AbstractSequencer<T extends Message> implements Iterator<T> {
private final Logger logger = LoggerFactory.getLogger(AbstractSequencer.class);
protected Session<T> session;
protected boolean hasNext;
protected final ByteArrayOutputStream baos = new ByteArrayOutputStream();
protected @Nullable CountDownLatch oppositeSessionSignal;
public void setSession(Session<T> session) {
this.session = session;
hasNext = !session.getInput().isInputShutdown();
}
@Override
public boolean hasNext() {
hasNext &= !session.getInput().isClosed();
return hasNext;
}
@Override
@Nullable
public T next() {
if(!hasNext())
throw new NoSuchElementException();
baos.reset();
if(oppositeSessionSignal != null) {
try {
oppositeSessionSignal.await();
} catch (InterruptedException e) {
logger.warn("Waiting for opposite session signal interrupted");
oppositeSessionSignal = null;
}
}
try {
return readNextMessage();
} catch (SocketException e) {
logger.debug("Input read() interrupted because socket has been closed");
hasNext = false;
return null;
} catch (IOException e) {
logger.error("Unexpected error while reading next message", e);
return null;
} finally {
resetState();
}
}
protected abstract T readNextMessage() throws IOException;
protected abstract void resetState();
protected void waitForOppositeSessionSignal() {
if(oppositeSessionSignal == null) {
logger.debug("Wait for opposite session...");
oppositeSessionSignal = new CountDownLatch(1);
}
}
public void oppositeSessionSignal() {
if(oppositeSessionSignal != null) {
logger.debug("wait for opposite session RELEASED");
oppositeSessionSignal.countDown();
}
}
protected byte readByte() throws IOException {
int read = session.getInput().getInputStream().read();
baos.write(read);
return (byte) read;
}
protected byte[] readBytes(int n) throws IOException {
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++)
bytes[i] = readByte();
return bytes;
}
protected byte[] readUntil(byte[] end, boolean withEnd) throws IOException {
int read;
int cursor = 0;
ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream();
while(cursor < end.length) {
read = readByte();
cursor = read == end[cursor] ? cursor + 1 : 0;
tmpBaos.write(read);
}
byte[] bytes = tmpBaos.toByteArray();
return withEnd ? bytes : Arrays.copyOf(bytes, bytes.length - end.length);
}
}
| mit |
kmokili/formation-dta | pizzeria-admin-app/src/main/java/fr/pizzeria/admin/web/LoginController.java | 1588 | package fr.pizzeria.admin.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
@WebServlet("/login")
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp");
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
if (StringUtils.isBlank(email) || StringUtils.isBlank(password))
{
resp.sendError(400, "Non non non ! Zone interdite");
}
else if ( StringUtils.equals(email, "admin@pizzeria.fr")
&& StringUtils.equals(password, "admin"))
{
HttpSession session = req.getSession();
session.setAttribute("email", email);
resp.sendRedirect(req.getContextPath() + "/pizzas/list");
}
else
{
resp.setStatus(403);
req.setAttribute("msgerr", "Ooppps noooo");
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp");
rd.forward(req, resp);
}
}
}
| mit |
jvasileff/aos-xp | src.java/org/anodyneos/xp/tag/core/DebugTag.java | 679 | package org.anodyneos.xp.tag.core;
import javax.servlet.jsp.el.ELException;
import org.anodyneos.xp.XpException;
import org.anodyneos.xp.XpOutput;
import org.anodyneos.xp.tagext.XpTagSupport;
import org.xml.sax.SAXException;
/**
* @author jvas
*/
public class DebugTag extends XpTagSupport {
public DebugTag() {
super();
}
/* (non-Javadoc)
* @see org.anodyneos.xp.tagext.XpTag#doTag(org.anodyneos.xp.XpContentHandler)
*/
public void doTag(XpOutput out) throws XpException, ELException, SAXException {
XpOutput newOut = new XpOutput(new DebugCH(System.err, out.getXpContentHandler()));
getXpBody().invoke(newOut);
}
}
| mit |
code-not-found/jaxws-cxf | jaxws-cxf-digital-signature/src/main/java/com/codenotfound/endpoint/TicketAgentImpl.java | 588 | package com.codenotfound.endpoint;
import java.math.BigInteger;
import org.example.ticketagent.ObjectFactory;
import org.example.ticketagent.TFlightsResponse;
import org.example.ticketagent.TListFlights;
import org.example.ticketagent_wsdl11.TicketAgent;
public class TicketAgentImpl implements TicketAgent {
@Override
public TFlightsResponse listFlights(TListFlights body) {
ObjectFactory factory = new ObjectFactory();
TFlightsResponse response = factory.createTFlightsResponse();
response.getFlightNumber().add(BigInteger.valueOf(101));
return response;
}
}
| mit |
EaW1805/data | src/main/java/com/eaw1805/data/model/map/Region.java | 7717 | package com.eaw1805.data.model.map;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.model.Game;
import java.io.Serializable;
/**
* Represents a region of the world.
*/
public class Region implements Serializable {
/**
* Required by Serializable interface.
*/
static final long serialVersionUID = 42L; //NOPMD
/**
* Region's identification number.
*/
private int id; // NOPMD
/**
* Region's code.
*/
private char code;
/**
* The name of the region.
*/
private String name;
/**
* The game this region belongs to.
*/
private Game game;
/**
* Default constructor.
*/
public Region() {
// Empty constructor
}
/**
* Get the Identification number of the region.
*
* @return the identification number of the region.
*/
public int getId() {
return id;
}
/**
* Set the Identification number of the region.
*
* @param identity the identification number of the region.
*/
public void setId(final int identity) {
this.id = identity;
}
/**
* Get the name of the region.
*
* @return the name of the region.
*/
public String getName() {
return name;
}
/**
* Set the thisName of the region.
*
* @param thisName the name of the region.
*/
public void setName(final String thisName) {
this.name = thisName;
}
/**
* Get the Single-char code of the region.
*
* @return the Single-char code of the region.
*/
public char getCode() {
return code;
}
/**
* Set the single-char code of the region.
*
* @param thisCode the single-char code of the region.
*/
public void setCode(final char thisCode) {
this.code = thisCode;
}
/**
* Get the game this region belongs to.
*
* @return The game of the region.
*/
public Game getGame() {
return game;
}
/**
* Set the game this region belongs to.
*
* @param value The game.
*/
public void setGame(final Game value) {
this.game = value;
}
/**
* Indicates whether some other object is "equal to" this one.
* The <code>equals</code> method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* <code>x</code>, <code>x.equals(x)</code> should return
* <code>true</code>.
* <li>It is <i>symmetric</i>: for any non-null reference values
* <code>x</code> and <code>y</code>, <code>x.equals(y)</code>
* should return <code>true</code> if and only if
* <code>y.equals(x)</code> returns <code>true</code>.
* <li>It is <i>transitive</i>: for any non-null reference values
* <code>x</code>, <code>y</code>, and <code>z</code>, if
* <code>x.equals(y)</code> returns <code>true</code> and
* <code>y.equals(z)</code> returns <code>true</code>, then
* <code>x.equals(z)</code> should return <code>true</code>.
* <li>It is <i>consistent</i>: for any non-null reference values
* <code>x</code> and <code>y</code>, multiple invocations of
* <tt>x.equals(y)</tt> consistently return <code>true</code>
* or consistently return <code>false</code>, provided no
* information used in <code>equals</code> comparisons on the
* objects is modified.
* <li>For any non-null reference value <code>x</code>,
* <code>x.equals(null)</code> should return <code>false</code>.
* </ul>
* The <tt>equals</tt> method for class <code>Object</code> implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values <code>x</code> and
* <code>y</code>, this method returns <code>true</code> if and only
* if <code>x</code> and <code>y</code> refer to the same object
* (<code>x == y</code> has the value <code>true</code>).
* Note that it is generally necessary to override the <tt>hashCode</tt>
* method whenever this method is overridden, so as to maintain the
* general contract for the <tt>hashCode</tt> method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj
* argument; <code>false</code> otherwise.
* @see #hashCode()
* @see java.util.Hashtable
*/
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Region)) {
return false;
}
final Region region = (Region) obj;
if (code != region.code) {
return false;
}
if (id != region.id) {
return false;
}
if (name != null ? !name.equals(region.name) : region.name != null) {
return false;
}
return true;
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.Hashtable</code>.
* The general contract of <code>hashCode</code> is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the <tt>hashCode</tt> method
* must consistently return the same integer, provided no information
* used in <tt>equals</tt> comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the <tt>equals(Object)</tt>
* method, then calling the <code>hashCode</code> method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the <tt>hashCode</tt> method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hashtables.
* </ul>
* As much as is reasonably practical, the hashCode method defined by
* class <tt>Object</tt> does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java<font size="-2"><sup>TM</sup></font> programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.util.Hashtable
*/
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
final StringBuilder sbld = new StringBuilder();
switch (id) {
case RegionConstants.EUROPE:
sbld.append("E");
break;
case RegionConstants.CARIBBEAN:
sbld.append("C");
break;
case RegionConstants.INDIES:
sbld.append("I");
break;
case RegionConstants.AFRICA:
sbld.append("A");
break;
default:
break;
}
return sbld.toString();
}
}
| mit |
malaonline/Android | app/src/main/java/com/malalaoshi/android/ui/dialogs/CommentDialog.java | 10909 | package com.malalaoshi.android.ui.dialogs;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.malalaoshi.android.R;
import com.malalaoshi.android.core.network.api.ApiExecutor;
import com.malalaoshi.android.core.network.api.BaseApiContext;
import com.malalaoshi.android.core.stat.StatReporter;
import com.malalaoshi.android.core.utils.MiscUtil;
import com.malalaoshi.android.entity.Comment;
import com.malalaoshi.android.network.Constants;
import com.malalaoshi.android.network.api.PostCommentApi;
import com.malalaoshi.android.ui.widgets.DoubleImageView;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by donald on 2017/6/29.
*/
public class CommentDialog extends BaseDialog {
private static String ARGS_DIALOG_COMMENT_TYPE = "comment type";
private static String ARGS_DIALOG_TEACHER_NAME = "teacher name";
private static String ARGS_DIALOG_TEACHER_AVATAR = "teacher avatar";
private static String ARGS_DIALOG_LECTURER_NAME = "lecturer name";
private static String ARGS_DIALOG_LECTURER_AVATAR = "lecturer avatar";
private static String ARGS_DIALOG_ASSIST_NAME = "assist name";
private static String ARGS_DIALOG_ASSIST_AVATAR = "assist avatar";
private static String ARGS_DIALOG_COURSE_NAME = "course name";
private static String ARGS_DIALOG_COMMENT = "comment";
private static String ARGS_DIALOG_TIMESLOT = "timeslot";
@Bind(R.id.div_comment_dialog_avatar)
DoubleImageView mDivCommentDialogAvatar;
@Bind(R.id.tv_comment_dialog_teacher_course)
TextView mTvCommentDialogTeacherCourse;
@Bind(R.id.rb_comment_dialog_score)
RatingBar mRbCommentDialogScore;
@Bind(R.id.et_comment_dialog_input)
EditText mEtCommentDialogInput;
@Bind(R.id.tv_comment_dialog_commit)
TextView mTvCommentDialogCommit;
@Bind(R.id.iv_comment_dialog_close)
ImageView mIvCommentDialogClose;
private int mCommentType;
private String mTeacherName;
private String mTeacherAvatar;
private String mLeactureAvatar;
private String mLeactureName;
private String mAssistantAvatar;
private String mAssistantName;
private String mCourseName;
private Comment mComment;
private long mTimeslot;
private OnCommentResultListener mResultListener;
public CommentDialog(Context context) {
super(context);
}
public CommentDialog(Context context, Bundle bundle) {
super(context);
if (bundle != null) {
mCommentType = bundle.getInt(ARGS_DIALOG_COMMENT_TYPE);
if (mCommentType == 0) {
mTeacherName = bundle.getString(ARGS_DIALOG_TEACHER_NAME, "");
mTeacherAvatar = bundle.getString(ARGS_DIALOG_TEACHER_AVATAR, "");
} else if (mCommentType == 1) {
mLeactureAvatar = bundle.getString(ARGS_DIALOG_LECTURER_AVATAR, "");
mLeactureName = bundle.getString(ARGS_DIALOG_LECTURER_NAME, "");
mAssistantAvatar = bundle.getString(ARGS_DIALOG_ASSIST_AVATAR, "");
mAssistantName = bundle.getString(ARGS_DIALOG_ASSIST_NAME, "");
}
mCourseName = bundle.getString(ARGS_DIALOG_COURSE_NAME, "");
mComment = bundle.getParcelable(ARGS_DIALOG_COMMENT);
mTimeslot = bundle.getLong(ARGS_DIALOG_TIMESLOT, 0L);
}
initView();
}
private void initView() {
setCancelable(false);
if (mCommentType == 0)
mDivCommentDialogAvatar.loadImg(mTeacherAvatar, "", DoubleImageView.LOAD_SIGNLE_BIG);
else if (mCommentType == 1)
mDivCommentDialogAvatar.loadImg(mLeactureAvatar, mAssistantAvatar, DoubleImageView.LOAD_DOUBLE);
if (mComment != null) {
StatReporter.commentPage(true);
updateUI(mComment);
mRbCommentDialogScore.setIsIndicator(true);
mEtCommentDialogInput.setFocusableInTouchMode(false);
mEtCommentDialogInput.setCursorVisible(false);
mTvCommentDialogCommit.setText("查看评价");
} else {
StatReporter.commentPage(false);
mTvCommentDialogCommit.setText("提交");
mRbCommentDialogScore.setIsIndicator(false);
mEtCommentDialogInput.setFocusableInTouchMode(true);
mEtCommentDialogInput.setCursorVisible(true);
}
mTvCommentDialogTeacherCourse.setText(mCourseName);
mRbCommentDialogScore.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (mComment == null){
if (fromUser && rating > 0 && mEtCommentDialogInput.getText().length() > 0){
mTvCommentDialogCommit.setEnabled(true);
}else {
mTvCommentDialogCommit.setEnabled(false);
}
}
}
});
mEtCommentDialogInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mComment == null){
if (s.length() > 0 && mRbCommentDialogScore.getRating() > 0){
mTvCommentDialogCommit.setEnabled(true);
}else {
mTvCommentDialogCommit.setEnabled(false);
}
}
}
});
}
@Override
protected View getView() {
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment_v2, null);
ButterKnife.bind(this, view);
return view;
}
private void updateUI(Comment comment) {
if (comment != null) {
mRbCommentDialogScore.setRating(comment.getScore());
mEtCommentDialogInput.setText(comment.getContent());
} else {
mRbCommentDialogScore.setRating(0);
mEtCommentDialogInput.setText("");
}
}
@Override
protected int getDialogStyleId() {
return 0;
}
public static CommentDialog newInstance(Context context, String lecturerName, String lecturerAvatarUrl, String assistName, String assistAvatarUrl, String courseName,
Long timeslot, Comment comment) {
Bundle args = new Bundle();
args.putInt(ARGS_DIALOG_COMMENT_TYPE, 1);
args.putString(ARGS_DIALOG_LECTURER_NAME, lecturerName);
args.putString(ARGS_DIALOG_LECTURER_AVATAR, lecturerAvatarUrl);
args.putString(ARGS_DIALOG_ASSIST_NAME, assistName);
args.putString(ARGS_DIALOG_ASSIST_AVATAR, assistAvatarUrl);
args.putString(ARGS_DIALOG_COURSE_NAME, courseName);
args.putParcelable(ARGS_DIALOG_COMMENT, comment);
args.putLong(ARGS_DIALOG_TIMESLOT, timeslot);
// f.setArguments(args);
CommentDialog f = new CommentDialog(context, args);
return f;
}
public void setOnCommentResultListener(OnCommentResultListener listener) {
mResultListener = listener;
}
public static CommentDialog newInstance(Context context, String teacherName, String teacherAvatarUrl, String courseName,
Long timeslot, Comment comment) {
Bundle args = new Bundle();
args.putInt(ARGS_DIALOG_COMMENT_TYPE, 0);
args.putString(ARGS_DIALOG_TEACHER_NAME, teacherName);
args.putString(ARGS_DIALOG_TEACHER_AVATAR, teacherAvatarUrl);
args.putString(ARGS_DIALOG_COURSE_NAME, courseName);
args.putParcelable(ARGS_DIALOG_COMMENT, comment);
args.putLong(ARGS_DIALOG_TIMESLOT, timeslot);
// f.setArguments(args);
CommentDialog f = new CommentDialog(context, args);
return f;
}
@OnClick({R.id.tv_comment_dialog_commit, R.id.iv_comment_dialog_close})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.tv_comment_dialog_commit:
commit();
dismiss();
break;
case R.id.iv_comment_dialog_close:
dismiss();
break;
}
}
private void commit() {
StatReporter.commentSubmit();
if (mComment != null) {
dismiss();
return;
}
float score = mRbCommentDialogScore.getRating();
if (score == 0.0) {
MiscUtil.toast(R.string.rate_the_course);
return;
}
String content = mEtCommentDialogInput.getText().toString();
if (TextUtils.isEmpty(content)) {
MiscUtil.toast(R.string.write_few_reviews);
return;
}
JSONObject json = new JSONObject();
try {
json.put(Constants.TIMESLOT, mTimeslot);
json.put(Constants.SCORE, score);
json.put(Constants.CONTENT, content);
} catch (JSONException e) {
e.printStackTrace();
return;
}
ApiExecutor.exec(new PostCommentRequest(this, json.toString()));
}
public interface OnCommentResultListener {
void onSuccess(Comment comment);
}
private static final class PostCommentRequest extends BaseApiContext<CommentDialog, Comment> {
private String body;
public PostCommentRequest(CommentDialog commentDialog, String body) {
super(commentDialog);
this.body = body;
}
@Override
public Comment request() throws Exception {
return new PostCommentApi().post(body);
}
@Override
public void onApiSuccess(@NonNull Comment response) {
get().commentSucceed(response);
}
@Override
public void onApiFailure(Exception exception) {
get().commentFailed();
}
}
private void commentFailed() {
MiscUtil.toast(R.string.comment_failed);
}
private void commentSucceed(Comment response) {
MiscUtil.toast(R.string.comment_succeed);
if (mResultListener != null)
mResultListener.onSuccess(response);
dismiss();
}
}
| mit |
pegurnee/2013-03-211 | workspace/Lecture 09_18_13/src/ManageAccounts.java | 1595 | import java.text.NumberFormat;
// ****************************************************************
// ManageAccounts.java
// Use Account class to create and manage Sally and Joe's bank accounts
public class ManageAccounts
{
public static void main(String[] args)
{
Account acct1, acct2;
NumberFormat usMoney = NumberFormat.getCurrencyInstance();
//create account1 for Sally with $1000
acct1 = new Account(1000, "Sally", 1111);
//create account2 for Joe with $500
acct2 = new Account(500, "Joe", 1212);
//deposit $100 to Joe's account
acct2.deposit(100);
//print Joe's new balance (use getBalance())
System.out.println("Joe's new balance: " + usMoney.format(acct2.getBalance()));
//withdraw $50 from Sally's account
acct1.withdraw(50);
//print Sally's new balance (use getBalance())
System.out.println("Sally's new balance: " + usMoney.format(acct1.getBalance()));
//charge fees to both accounts
System.out.println("Sally's new balance after the fee is charged: " + usMoney.format(acct1.chargeFee()));
System.out.println("Joe's new balance after the fee is charged: " + usMoney.format(acct2.chargeFee()));
//change the name on Joe's account to Joseph
acct2.changeName("Joseph");
//print summary for both accounts
System.out.println(acct1);
System.out.println(acct2);
//close and display Sally's account
acct1.close();
System.out.println(acct1);
//consolidate account test (doesn't work as acct1
Account newAcct = Account.consolidate(acct1, acct2);
System.out.println(acct1);
}
}
| mit |
hammadirshad/dvare | src/main/java/org/dvare/annotations/Type.java | 1450 | /*The MIT License (MIT)
Copyright (c) 2016 Muhammad Hammad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Sogiftware.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
package org.dvare.annotations;
import org.dvare.expression.datatype.DataType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Type {
DataType dataType();
}
| mit |
Arrekusu/datamover | components/datamover-core/src/main/java/com/arekusu/datamover/model/jaxb/ModelType.java | 2303 |
package com.arekusu.datamover.model.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.arekusu.com}DefinitionType"/>
* </sequence>
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"definitionType"
})
@XmlRootElement(name = "ModelType", namespace = "http://www.arekusu.com")
public class ModelType {
@XmlElement(name = "DefinitionType", namespace = "http://www.arekusu.com", required = true)
protected DefinitionType definitionType;
@XmlAttribute(name = "version")
protected String version;
/**
* Gets the value of the definitionType property.
*
* @return
* possible object is
* {@link DefinitionType }
*
*/
public DefinitionType getDefinitionType() {
return definitionType;
}
/**
* Sets the value of the definitionType property.
*
* @param value
* allowed object is
* {@link DefinitionType }
*
*/
public void setDefinitionType(DefinitionType value) {
this.definitionType = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
| mit |
lmarinov/Exercise-repo | Java_OOP_2021/src/SOLID/Exercise/Logger/model/appenders/FileAppender.java | 670 | package SOLID.Exercise.Logger.model.appenders;
import SOLID.Exercise.Logger.api.File;
import SOLID.Exercise.Logger.api.Layout;
import SOLID.Exercise.Logger.model.files.LogFile;
public class FileAppender extends BaseAppender {
private File file;
public FileAppender(Layout layout) {
super(layout);
this.setFile(new LogFile());
}
public void setFile(File file) {
this.file = file;
}
@Override
public void append(String message) {
this.file.write(message);
}
@Override
public String toString() {
return String.format("%s, File size: %d", super.toString(), this.file.getSize());
}
}
| mit |
voostindie/sprox-json | src/test/java/nl/ulso/sprox/json/spotify/AlbumFactory.java | 972 | package nl.ulso.sprox.json.spotify;
import nl.ulso.sprox.Node;
import java.time.LocalDate;
import java.util.List;
/**
* Sprox processor for Spotify API album data. This is a very simple processor that ignores most data.
* <p>
* This implementation creates an Artist object for each and every artist in the response. But only the first one on
* album level is kept in the end.
* </p>
*/
public class AlbumFactory {
@Node("album")
public Album createAlbum(@Node("name") String name, @Node("release_date") LocalDate releaseDate, Artist artist,
List<Track> tracks) {
return new Album(name, releaseDate, artist, tracks);
}
@Node("artists")
public Artist createArtist(@Node("name") String name) {
return new Artist(name);
}
@Node("items")
public Track createTrack(@Node("track_number") Integer trackNumber, @Node("name") String name) {
return new Track(trackNumber, name);
}
}
| mit |
DankBots/GN4R | src/main/java/com/gmail/hexragon/gn4rBot/command/ai/PrivateCleverbotCommand.java | 1619 | package com.gmail.hexragon.gn4rBot.command.ai;
import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor;
import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command;
import com.gmail.hexragon.gn4rBot.util.GnarMessage;
import com.google.code.chatterbotapi.ChatterBot;
import com.google.code.chatterbotapi.ChatterBotFactory;
import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import net.dv8tion.jda.entities.User;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.WeakHashMap;
@Command(
aliases = {"cbot", "cleverbot"},
usage = "(query)",
description = "Talk to Clever-Bot."
)
public class PrivateCleverbotCommand extends CommandExecutor
{
private ChatterBotFactory factory = new ChatterBotFactory();
private ChatterBotSession session = null;
private Map<User, ChatterBotSession> sessionMap = new WeakHashMap<>();
@Override
public void execute(GnarMessage message, String[] args)
{
try
{
if (!sessionMap.containsKey(message.getAuthor()))
{
ChatterBot bot = factory.create(ChatterBotType.CLEVERBOT);
sessionMap.put(message.getAuthor(), bot.createSession());
}
message.replyRaw(sessionMap.get(message.getAuthor()).think(StringUtils.join(args, " ")));
}
catch (Exception e)
{
message.reply("Chat Bot encountered an exception. Restarting. `:[`");
sessionMap.remove(message.getAuthor());
}
}
}
| mit |
sanaehirotaka/logbook | main/logbook/data/ScriptLoader.java | 3288 | package logbook.data;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import logbook.config.AppConfig;
import org.apache.commons.io.FilenameUtils;
/**
* スクリプトを読み込みEventListenerの実装を取得する
*
*/
public final class ScriptLoader implements Closeable {
/** ClassLoader */
private final URLClassLoader classLoader;
/** ScriptEngineManager */
private final ScriptEngineManager manager;
/**
* コンストラクター
*/
public ScriptLoader() {
this.classLoader = URLClassLoader.newInstance(this.getLibraries());
this.manager = new ScriptEngineManager(this.classLoader);
}
/**
* スクリプトを読み込みEventListenerの実装を取得する<br>
*
* @param script スクリプト
* @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null
* @throws IOException
* @throws ScriptException
*/
@CheckForNull
public EventListener getEventListener(Path script) throws IOException, ScriptException {
try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
// 拡張子からScriptEngineを取得
String ext = FilenameUtils.getExtension(script.toString());
ScriptEngine engine = this.manager.getEngineByExtension(ext);
if (engine != null) {
// eval
engine.eval(reader);
// 実装を取得
EventListener listener = ((Invocable) engine).getInterface(EventListener.class);
if (listener != null) {
return new ScriptEventAdapter(listener, script);
}
}
return null;
}
}
/**
* ScriptEngineManagerで使用する追加のライブラリ
*
* @return ライブラリ
*/
public URL[] getLibraries() {
String[] engines = AppConfig.get().getScriptEngines();
List<URL> libs = new ArrayList<>();
for (String engine : engines) {
Path path = Paths.get(engine);
if (Files.isReadable(path)) {
try {
libs.add(path.toUri().toURL());
} catch (MalformedURLException e) {
// ここに入るパターンはないはず
e.printStackTrace();
}
}
}
return libs.toArray(new URL[libs.size()]);
}
@Override
public void close() throws IOException {
this.classLoader.close();
}
}
| mit |
Microsoft/vso-intellij | plugin/src/com/microsoft/alm/plugin/idea/tfvc/ui/ServerPathCellEditor.java | 4047 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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.microsoft.alm.plugin.idea.tfvc.ui;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.util.ui.AbstractTableCellEditor;
import com.intellij.util.ui.CellEditorComponentWithBrowseButton;
import com.microsoft.alm.plugin.context.ServerContext;
import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle;
import com.microsoft.alm.plugin.idea.common.utils.VcsHelper;
import com.microsoft.alm.plugin.idea.tfvc.ui.servertree.ServerBrowserDialog;
import org.apache.commons.lang.StringUtils;
import javax.swing.JTable;
import javax.swing.JTextField;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ServerPathCellEditor extends AbstractTableCellEditor {
private final String title;
private final Project project;
private final ServerContext serverContext;
private CellEditorComponentWithBrowseButton<JTextField> component;
public ServerPathCellEditor(final String title, final Project project, final ServerContext serverContext) {
this.title = title;
this.project = project;
this.serverContext = serverContext;
}
public Object getCellEditorValue() {
return component.getChildComponent().getText();
}
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
final ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
createBrowserDialog();
}
};
component = new CellEditorComponentWithBrowseButton<JTextField>(new TextFieldWithBrowseButton(listener), this);
component.getChildComponent().setText((String) value);
return component;
}
/**
* Creates the browser dialog for file selection
*/
@VisibleForTesting
protected void createBrowserDialog() {
final String serverPath = getServerPath();
if (StringUtils.isNotEmpty(serverPath)) {
final ServerBrowserDialog dialog = new ServerBrowserDialog(title, project, serverContext, serverPath, true, false);
if (dialog.showAndGet()) {
component.getChildComponent().setText(dialog.getSelectedPath());
}
} else {
Messages.showErrorDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG),
TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE));
}
}
/**
* Get a server path to pass into the dialog
*
* @return
*/
@VisibleForTesting
protected String getServerPath() {
String serverPath = (String) getCellEditorValue();
// if there is no entry in the cell to find the root server path with then find it from the server context
if (StringUtils.isEmpty(serverPath) && serverContext != null && serverContext.getTeamProjectReference() != null) {
serverPath = VcsHelper.TFVC_ROOT.concat(serverContext.getTeamProjectReference().getName());
}
return serverPath;
}
} | mit |
PeerWasp/PeerWasp | peerbox/src/main/java/org/peerbox/presenter/MainController.java | 467 | package org.peerbox.presenter;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class MainController implements INavigatable {
@FXML
private Pane mainPane;
/*
* (non-Javadoc)
*
* @see org.peerbox.presenter.INavigatable#setContent(javafx.scene.Node)
*/
@Override
public void setContent(Node content) {
mainPane.getChildren().clear();
mainPane.getChildren().add(content);
mainPane.requestLayout();
}
}
| mit |
arapaka/algorithms-datastructures | algorithms/src/main/java/tutorialHorizon/arrays/InsertionSort.java | 813 | package tutorialHorizon.arrays;
/**
* Created by archithrapaka on 7/4/17.
*/
public class InsertionSort {
public static void insertionSort(int[] items, int n) {
int i, j;
for (i = 1; i < n; i++) {
j = i;
while (j > 0 && (items[j] < items[j - 1])) {
swap(items, j, j - 1);
j--;
}
}
}
public static void swap(int[] items, int i, int j) {
int temp = items[i];
items[i] = items[j];
items[j] = temp;
}
public static void display(int[] a) {
for (int i : a) {
System.out.print(i + " ");
}
}
public static void main(String[] args) {
int[] a = {100, 4, 30, 15, 98, 3};
insertionSort(a, a.length);
display(a);
}
}
| mit |
SpongePowered/SpongeCommon | src/main/java/org/spongepowered/common/mixin/api/mcp/tileentity/TileEntityDropperMixin_API.java | 1688 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.api.mcp.tileentity;
import net.minecraft.tileentity.TileEntityDropper;
import org.spongepowered.api.block.tileentity.carrier.Dropper;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Mixin;
@NonnullByDefault
@Mixin(TileEntityDropper.class)
public abstract class TileEntityDropperMixin_API extends TileEntityDispenserMixin_API implements Dropper {
}
| mit |
bartoszgolek/whattodofordinner | app/src/main/java/biz/golek/whattodofordinner/business/contract/presenters/EditDinnerPresenter.java | 261 | package biz.golek.whattodofordinner.business.contract.presenters;
import biz.golek.whattodofordinner.business.contract.entities.Dinner;
/**
* Created by Bartosz Gołek on 2016-02-10.
*/
public interface EditDinnerPresenter {
void Show(Dinner dinner);
}
| mit |
CMPUT301F17T11/CupOfJava | app/src/main/java/com/cmput301f17t11/cupofjava/Controllers/SaveFileController.java | 8104 | /* SaveFileController
*
* Version 1.0
*
* November 13, 2017
*
* Copyright (c) 2017 Cup Of Java. All rights reserved.
*/
package com.cmput301f17t11.cupofjava.Controllers;
import android.content.Context;
import com.cmput301f17t11.cupofjava.Models.Habit;
import com.cmput301f17t11.cupofjava.Models.HabitEvent;
import com.cmput301f17t11.cupofjava.Models.HabitList;
import com.cmput301f17t11.cupofjava.Models.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* Implements the file to save data to.
*
* @version 1.0
*/
public class SaveFileController {
private ArrayList<User> allUsers;
//private String username;
private String saveFile = "test_save_file4.sav";
public SaveFileController(){
this.allUsers = new ArrayList<User>();
}
/**
* Loads data from file.
*
* @param context instance of Context
*/
private void loadFromFile(Context context){
try{
FileInputStream ifStream = context.openFileInput(saveFile);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ifStream));
Gson gson = new Gson();
Type userArrayListType = new TypeToken<ArrayList<User>>(){}.getType();
this.allUsers = gson.fromJson(bufferedReader, userArrayListType);
ifStream.close();
}
//create a new array list if a file does not already exist
catch (FileNotFoundException e){
this.allUsers = new ArrayList<User>();
saveToFile(context);
}
catch (IOException e){
throw new RuntimeException();
}
}
/**
* Saves current ArrayList contents in file.
*
* @param context instance of Context
*/
private void saveToFile(Context context){
try{
FileOutputStream ofStream = context.openFileOutput(saveFile, Context.MODE_PRIVATE);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(ofStream));
Gson gson = new Gson();
gson.toJson(this.allUsers, bufferedWriter);
bufferedWriter.flush();
ofStream.close();
}
catch (FileNotFoundException e){
//shouldn't really happen, since a file not found would create a new file.
throw new RuntimeException("Laws of nature defied!");
}
catch (IOException e){
throw new RuntimeException();
}
}
/**
* Adds new user and saves to file.
*
* @param context instance of Context
* @param user instance of User
* @see User
*/
public void addNewUser(Context context, User user){
loadFromFile(context);
this.allUsers.add(user);
saveToFile(context);
}
/**
* Deletes all user from file.
*
* @param context instance of Context
*/
public void deleteAllUsers(Context context){
this.allUsers = new ArrayList<>();
saveToFile(context);
}
/**
* Gets user index.
*
* @param context instance of Context
* @param username string username
* @return integer user index if username matches, -1 otherwise
*/
public int getUserIndex(Context context, String username){
loadFromFile(context);
for (int i = 0; i < this.allUsers.size(); i++){
if (this.allUsers.get(i).getUsername().equals(username)){
return i;
}
}
return -1;
}
/**
* Gets HabitList instance.
*
* @param context instance of Context
* @param userIndex integer user index
* @return HabitList
* @see HabitList
*/
public HabitList getHabitList(Context context, int userIndex){
loadFromFile(context);
return this.allUsers.get(userIndex).getHabitList();
}
/**
* Gets ArrayList of type Habit.
*
* @param context instance of Context
* @param userIndex integer user index
* @return list
*/
public ArrayList<Habit> getHabitListAsArray(Context context, int userIndex){
loadFromFile(context);
ArrayList<Habit> list = this.allUsers.get(userIndex).getHabitListAsArray();
return list;
}
/**
* Adds a habit to a particular user's habit list.
*
* @param context instance of Context
* @param userIndex integer user index
* @param habit instance of Habit
* @see Habit
*/
public void addHabit(Context context, int userIndex, Habit habit){
loadFromFile(context);
this.allUsers.get(userIndex).getHabitList().addHabit(habit);
saveToFile(context);
}
/**
* Gets habit from a particular user's habit list.
*
* @param context instance of Context
* @param userIndex integer user index
* @param habitIndex integer index of habit
* @return instance of Habit
* @see Habit
*/
public Habit getHabit(Context context, int userIndex, int habitIndex){
loadFromFile(context);
return this.allUsers.get(userIndex).getHabitListAsArray().get(habitIndex);
}
/**
* Deletes habit from a certain user's habit list.
*
* @param context instance of Context
* @param userIndex integer user index
* @param habitIndex integer index of habit
*/
public void deleteHabit(Context context, int userIndex, int habitIndex){
loadFromFile(context);
this.allUsers.get(userIndex).getHabitListAsArray().remove(habitIndex);
saveToFile(context);
}
/**
* Adds habit event to a particular user's habit event list.
*
* @param context instance of Context
* @param userIndex integer user index
* @param habitIndex integer index of habit
* @param habitEvent instance of HabitEvent
* @see HabitEvent
*/
public void addHabitEvent(Context context, int userIndex, int habitIndex, HabitEvent habitEvent){
loadFromFile(context);
this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex).addHabitEvent(habitEvent);
saveToFile(context);
}
/**
* Removes a habit event from a particular user's habit event list.
*
* @param context instance of Context
* @param userIndex integer user index
* @param habitIndex integer index of habit
* @param habitEventIndex integer index of habit event
*/
public void removeHabitEvent(Context context, int userIndex, int habitIndex, int habitEventIndex){
loadFromFile(context);
this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex)
.getHabitEventHistory().getHabitEvents().remove(habitEventIndex);
saveToFile(context);
}
/**
* For use in timeline view.
*
* @param context instance of Context
* @param userIndex integer user index
* @return ArrayList of HabitEvent type
* @see HabitEvent
*/
public ArrayList<HabitEvent> getAllHabitEvents(Context context, int userIndex){
loadFromFile(context);
ArrayList<HabitEvent> habitEvents = new ArrayList<>();
User user = this.allUsers.get(userIndex);
ArrayList<Habit> habitList = user.getHabitListAsArray();
Habit currentHabit;
ArrayList<HabitEvent> currentHabitEvents;
for (int i = 0; i < habitList.size(); i++){
currentHabit = habitList.get(i);
currentHabitEvents = currentHabit.getHabitEventHistory().getHabitEvents();
for (int j = 0; j < currentHabitEvents.size() ; j++){
habitEvents.add(user.getHabitListAsArray().get(i)
.getHabitEventHistory().getHabitEvents().get(j));
}
}
return habitEvents;
}
}
| mit |
JaeW/dodroid | app/src/main/java/doit/study/droid/fragments/DislikeDialogFragment.java | 3105 | package doit.study.droid.fragments;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import doit.study.droid.R;
public class DislikeDialogFragment extends DialogFragment {
public static final String EXTRA_CAUSE = "doit.study.droid.extra_cause";
private static final String QUESTION_TEXT_KEY = "doit.study.droid.question_text_key";
private Activity mHostActivity;
private View mView;
private int[] mCauseIds = {R.id.question_incorrect, R.id.answer_incorrect, R.id.documentation_irrelevant};
public static DislikeDialogFragment newInstance(String questionText) {
DislikeDialogFragment dislikeDialog = new DislikeDialogFragment();
Bundle arg = new Bundle();
arg.putString(QUESTION_TEXT_KEY, questionText);
dislikeDialog.setArguments(arg);
return dislikeDialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mHostActivity = getActivity();
LayoutInflater inflater = mHostActivity.getLayoutInflater();
mView = inflater.inflate(R.layout.fragment_dialog_dislike, null);
AlertDialog.Builder builder = new AlertDialog.Builder(mHostActivity);
builder.setMessage(getString(R.string.report_because))
.setView(mView)
.setPositiveButton(mHostActivity.getString(R.string.report), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Fragment fr = getTargetFragment();
if (fr != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_CAUSE, formReport());
fr.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
private String formReport() {
EditText editText = (EditText) mView.findViewById(R.id.comment);
StringBuilder result = new StringBuilder(" Cause:");
for (int id : mCauseIds) {
CheckBox checkBox = (CheckBox) mView.findViewById(id);
if (checkBox.isChecked())
result.append(checkBox.getText())
.append(",");
}
result.append(" Comment:");
result.append(editText.getText());
return result.toString();
}
} | mit |
jeanregisser/tcSlackBuildNotifier | tcslackbuildnotifier-core/src/main/java/slacknotifications/teamcity/payload/SlackNotificationPayloadManager.java | 7122 |
package slacknotifications.teamcity.payload;
import jetbrains.buildServer.messages.Status;
import jetbrains.buildServer.responsibility.ResponsibilityEntry;
import jetbrains.buildServer.responsibility.TestNameResponsibilityEntry;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.tests.TestName;
import slacknotifications.teamcity.BuildStateEnum;
import slacknotifications.teamcity.Loggers;
import slacknotifications.teamcity.payload.content.SlackNotificationPayloadContent;
import java.util.Collection;
public class SlackNotificationPayloadManager {
SBuildServer server;
public SlackNotificationPayloadManager(SBuildServer server){
this.server = server;
Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting");
}
public SlackNotificationPayloadContent beforeBuildFinish(SRunningBuild runningBuild, SFinishedBuild previousBuild) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BEFORE_BUILD_FINISHED);
return content;
}
public SlackNotificationPayloadContent buildFinished(SRunningBuild runningBuild, SFinishedBuild previousBuild) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_FINISHED);
return content;
}
public SlackNotificationPayloadContent buildInterrupted(SRunningBuild runningBuild, SFinishedBuild previousBuild) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_INTERRUPTED);
return content;
}
public SlackNotificationPayloadContent buildStarted(SRunningBuild runningBuild, SFinishedBuild previousBuild) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_STARTED);
return content;
}
/** Used by versions of TeamCity less than 7.0
*/
public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType,
ResponsibilityInfo responsibilityInfoOld,
ResponsibilityInfo responsibilityInfoNew, boolean isUserAction) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED);
String oldUser = "Nobody";
String newUser = "Nobody";
try {
oldUser = responsibilityInfoOld.getResponsibleUser().getDescriptiveName();
} catch (Exception e) {}
try {
newUser = responsibilityInfoNew.getResponsibleUser().getDescriptiveName();
} catch (Exception e) {}
content.setText(buildType.getFullName().toString()
+ " changed responsibility from "
+ oldUser
+ " to "
+ newUser
+ " with comment '"
+ responsibilityInfoNew.getComment().toString().trim()
+ "'"
);
return content;
}
/** Used by versions of TeamCity 7.0 and above
*/
public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType,
ResponsibilityEntry responsibilityEntryOld,
ResponsibilityEntry responsibilityEntryNew) {
SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED);
String oldUser = "Nobody";
String newUser = "Nobody";
if (responsibilityEntryOld.getState() != ResponsibilityEntry.State.NONE) {
oldUser = responsibilityEntryOld.getResponsibleUser().getDescriptiveName();
}
if (responsibilityEntryNew.getState() != ResponsibilityEntry.State.NONE) {
newUser = responsibilityEntryNew.getResponsibleUser().getDescriptiveName();
}
content.setText(buildType.getFullName().toString().toString().trim()
+ " changed responsibility from "
+ oldUser
+ " to "
+ newUser
+ " with comment '"
+ responsibilityEntryNew.getComment().toString().trim()
+ "'"
);
return content;
}
public SlackNotificationPayloadContent responsibleChanged(SProject project,
TestNameResponsibilityEntry oldTestNameResponsibilityEntry,
TestNameResponsibilityEntry newTestNameResponsibilityEntry,
boolean isUserAction) {
// TODO Auto-generated method stub
return null;
}
public SlackNotificationPayloadContent responsibleChanged(SProject project,
Collection<TestName> testNames, ResponsibilityEntry entry,
boolean isUserAction) {
// TODO Auto-generated method stub
return null;
}
/*
HashMap<String, SlackNotificationPayload> formats = new HashMap<String,SlackNotificationPayload>();
Comparator<SlackNotificationPayload> rankComparator = new SlackNotificationPayloadRankingComparator();
List<SlackNotificationPayload> orderedFormatCollection = new ArrayList<SlackNotificationPayload>();
SBuildServer server;
public SlackNotificationPayloadManager(SBuildServer server){
this.server = server;
Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting");
}
public void registerPayloadFormat(SlackNotificationPayload payloadFormat){
Loggers.SERVER.info(this.getClass().getSimpleName() + " :: Registering payload "
+ payloadFormat.getFormatShortName()
+ " with rank of " + payloadFormat.getRank());
formats.put(payloadFormat.getFormatShortName(),payloadFormat);
this.orderedFormatCollection.add(payloadFormat);
Collections.sort(this.orderedFormatCollection, rankComparator);
Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payloads list is " + this.orderedFormatCollection.size() + " items long. Payloads are ranked in the following order..");
for (SlackNotificationPayload pl : this.orderedFormatCollection){
Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payload Name: " + pl.getFormatShortName() + " Rank: " + pl.getRank());
}
}
public SlackNotificationPayload getFormat(String formatShortname){
if (formats.containsKey(formatShortname)){
return formats.get(formatShortname);
}
return null;
}
public Boolean isRegisteredFormat(String format){
return formats.containsKey(format);
}
public Set<String> getRegisteredFormats(){
return formats.keySet();
}
public Collection<SlackNotificationPayload> getRegisteredFormatsAsCollection(){
return orderedFormatCollection;
}
public SBuildServer getServer() {
return server;
}
*/
}
| mit |
allanfish/facetime | facetime-spring/src/main/java/com/facetime/spring/support/Page.java | 3885 | package com.facetime.spring.support;
import java.util.ArrayList;
import java.util.List;
import com.facetime.core.conf.ConfigUtils;
import com.facetime.core.utils.StringUtils;
/**
* 分页类
*
* @author yufei
* @param <T>
*/
public class Page<T> {
private static int BEGIN_PAGE_SIZE = 20;
/** 下拉分页列表的递增数量级 */
private static int ADD_PAGE_SIZE_RATIO = 10;
public static int DEFAULT_PAGE_SIZE = 10;
private static int MAX_PAGE_SIZE = 200;
private QueryInfo<T> queryInfo = null;
private List<T> queryResult = null;
public Page() {
this(new QueryInfo<T>());
}
public Page(QueryInfo<T> queryInfo) {
this.queryInfo = queryInfo;
this.queryResult = new ArrayList<T>(15);
}
/**
* @return 下拉分页列表的递增数量级
*/
public final static int getAddPageSize() {
String addPageSizeRatio = ConfigUtils.getProperty("add_page_size_ratio");
if (StringUtils.isValid(addPageSizeRatio))
ADD_PAGE_SIZE_RATIO = Integer.parseInt(addPageSizeRatio);
return ADD_PAGE_SIZE_RATIO;
}
/**
* @return 默认分页下拉列表的开始值
*/
public final static int getBeginPageSize() {
String beginPageSize = ConfigUtils.getProperty("begin_page_size");
if (StringUtils.isValid(beginPageSize))
BEGIN_PAGE_SIZE = Integer.parseInt(beginPageSize);
return BEGIN_PAGE_SIZE;
}
/**
* 默认列表记录显示条数
*/
public static final int getDefaultPageSize() {
String defaultPageSize = ConfigUtils.getProperty("default_page_size");
if (StringUtils.isValid(defaultPageSize))
DEFAULT_PAGE_SIZE = Integer.parseInt(defaultPageSize);
return DEFAULT_PAGE_SIZE;
}
/**
* 默认分页列表显示的最大记录条数
*/
public static final int getMaxPageSize() {
String maxPageSize = ConfigUtils.getProperty("max_page_size");
if (StringUtils.isValid(maxPageSize)) {
MAX_PAGE_SIZE = Integer.parseInt(maxPageSize);
}
return MAX_PAGE_SIZE;
}
public String getBeanName() {
return this.queryInfo.getBeanName();
}
public int getCurrentPageNo() {
return this.queryInfo.getCurrentPageNo();
}
public String getKey() {
return this.queryInfo.getKey();
}
public Integer getNeedRowNum() {
return this.getPageSize() - this.getQueryResult().size();
}
public long getNextPage() {
return this.queryInfo.getNextPage();
}
public int getPageCount() {
return this.queryInfo.getPageCount();
}
public int getPageSize() {
return this.queryInfo.getPageSize();
}
public List<T> getParams() {
return this.queryInfo.getParams();
}
public int getPreviousPage() {
return this.queryInfo.getPreviousPage();
}
public String[] getProperties() {
return this.queryInfo.getProperties();
}
public List<T> getQueryResult() {
return this.queryResult;
}
public int getRecordCount() {
return this.queryInfo.getRecordCount();
}
public String getSql() {
return this.queryInfo.getSql();
}
public boolean isHasResult() {
return this.queryResult != null && this.queryResult.size() > 0;
}
public void setBeanName(String beanNameValue) {
this.queryInfo.setBeanName(beanNameValue);
}
public void setCurrentPageNo(int currentPageNo) {
this.queryInfo.setCurrentPageNo(currentPageNo);
}
public void setKey(String keyValue) {
this.queryInfo.setKey(keyValue);
}
public void setPageCount(int pageCount) {
this.queryInfo.setPageCount(pageCount);
}
public void setPageSize(int pageSize) {
this.queryInfo.setPageSize(pageSize);
}
public void setParams(List<T> paramsValue) {
this.queryInfo.setParams(paramsValue);
}
public void setProperties(String[] propertiesValue) {
this.queryInfo.setProperties(propertiesValue);
}
public void setQueryResult(List<T> list) {
this.queryResult = list;
}
public void setRecordCount(int count) {
this.queryInfo.setRecordCount(count);
}
public void setSql(String sql) {
this.queryInfo.setSql(sql);
}
}
| mit |
Squama/Master | AdminEAP-framework/src/main/java/com/cnpc/framework/base/service/impl/DictServiceImpl.java | 4363 | package com.cnpc.framework.base.service.impl;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.cnpc.framework.base.entity.Dict;
import com.cnpc.framework.base.pojo.TreeNode;
import com.cnpc.framework.base.service.DictService;
import com.cnpc.framework.constant.RedisConstant;
import com.cnpc.framework.utils.StrUtil;
import com.cnpc.framework.utils.TreeUtil;
@Service("dictService")
public class DictServiceImpl extends BaseServiceImpl implements DictService {
@Override
public List<TreeNode> getTreeData() {
// 获取数据
String key = RedisConstant.DICT_PRE+"tree";
List<TreeNode> tnlist = null;
String tnStr = redisDao.get(key);
if(!StrUtil.isEmpty(key)) {
tnlist = JSON.parseArray(tnStr,TreeNode.class);
}
if (tnlist != null) {
return tnlist;
} else {
String hql = "from Dict order by levelCode asc";
List<Dict> dicts = this.find(hql);
Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>();
for (Dict dict : dicts) {
TreeNode node = new TreeNode();
node.setText(dict.getName());
node.setId(dict.getId());
node.setParentId(dict.getParentId());
node.setLevelCode(dict.getLevelCode());
nodelist.put(node.getId(), node);
}
// 构造树形结构
tnlist = TreeUtil.getNodeList(nodelist);
redisDao.save(key, tnlist);
return tnlist;
}
}
public List<Dict> getDictsByCode(String code) {
String key = RedisConstant.DICT_PRE+ code;
List dicts = redisDao.get(key, List.class);
if (dicts == null) {
String hql = "from Dict where code='" + code + "'";
Dict dict = this.get(hql);
dicts = this.find("from Dict where parentId='" + dict.getId() + "' order by levelCode");
redisDao.add(key, dicts);
return dicts;
} else {
return dicts;
}
}
@Override
public List<TreeNode> getTreeDataByCode(String code) {
// 获取数据
String key = RedisConstant.DICT_PRE + code + "s";
List<TreeNode> tnlist = null;
String tnStr = redisDao.get(key);
if(!StrUtil.isEmpty(key)) {
tnlist = JSON.parseArray(tnStr,TreeNode.class);
}
if (tnlist != null) {
return tnlist;
} else {
String hql = "from Dict where code='" + code + "' order by levelCode asc";
List<Dict> dicts = this.find(hql);
hql = "from Dict where code='" + code + "' or parent_id = '" +dicts.get(0).getId()+ "' order by levelCode asc";
dicts = this.find(hql);
Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>();
for (Dict dict : dicts) {
TreeNode node = new TreeNode();
node.setText(dict.getName());
node.setId(dict.getId());
node.setParentId(dict.getParentId());
node.setLevelCode(dict.getLevelCode());
nodelist.put(node.getId(), node);
}
// 构造树形结构
tnlist = TreeUtil.getNodeList(nodelist);
redisDao.save(key, tnlist);
return tnlist;
}
}
@Override
public List<TreeNode> getMeasureTreeData() {
// 获取数据
String hql = "from Dict WHERE (levelCode LIKE '000026%' OR levelCode LIKE '000027%') order by levelCode asc";
List<Dict> funcs = this.find(hql);
Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>();
for (Dict dict : funcs) {
TreeNode node = new TreeNode();
node.setText(dict.getName());
node.setId(dict.getId());
node.setParentId(dict.getParentId());
node.setLevelCode(dict.getLevelCode());
nodelist.put(node.getId(), node);
}
// 构造树形结构
return TreeUtil.getNodeList(nodelist);
}
}
| mit |
chadrosenquist/running-route | src/main/java/com/kromracing/runningroute/client/Utils.java | 1100 | package com.kromracing.runningroute.client;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Widget;
final public class Utils {
private Utils() {
}
/**
* Sets the HTML id for a widget.
* @param widget The widget to have the id set, ex: TextBox
* @param id ID in HTML, ex: textbox-location
*/
static void setId(final Widget widget, final String id) {
if (widget instanceof CheckBox) {
final Element checkBoxElement = widget.getElement();
// The first element is the actual box to check. That is the one we care about.
final Element inputElement = DOM.getChild(checkBoxElement, 0);
inputElement.setAttribute("id", id);
//DOM.setElementAttribute(inputElement, "id", id); deprecated!
}
else {
widget.getElement().setAttribute("id", id);
//DOM.setElementAttribute(widget.getElement(), "id", id); deprecated!
}
}
}
| mit |
jenkinsci/gatekeeper-plugin | src/test/java/org/paylogic/jenkins/advancedscm/MercurialRule.java | 5618 | /**
* This file was copied from https://github.com/jenkinsci/mercurial-plugin/raw/master/src/test/java/hudson/plugins/mercurial/MercurialRule.java
* so we as well have a MercurialRule to create test repos with.
* The file is licensed under the MIT License, which can by found at: http://www.opensource.org/licenses/mit-license.php
* More information about this file and it's authors can be found at: https://github.com/jenkinsci/mercurial-plugin/
*/
package org.paylogic.jenkins.advancedscm;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.TaskListener;
import hudson.plugins.mercurial.HgExe;
import hudson.plugins.mercurial.MercurialTagAction;
import hudson.scm.PollingResult;
import hudson.util.ArgumentListBuilder;
import hudson.util.StreamTaskListener;
import org.junit.Assume;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.ExternalResource;
import org.jvnet.hudson.test.JenkinsRule;
import org.paylogic.jenkins.ABuildCause;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Collections.sort;
import static org.junit.Assert.*;
public final class MercurialRule extends ExternalResource {
private TaskListener listener;
private final JenkinsRule j;
public MercurialRule(JenkinsRule j) {
this.j = j;
}
@Override protected void before() throws Exception {
listener = new StreamTaskListener(System.out, Charset.defaultCharset());
try {
if (new ProcessBuilder("hg", "--version").start().waitFor() != 0) {
throw new AssumptionViolatedException("hg --version signaled an error");
}
} catch(IOException ioe) {
String message = ioe.getMessage();
if(message.startsWith("Cannot run program \"hg\"") && message.endsWith("No such file or directory")) {
throw new AssumptionViolatedException("hg is not available; please check that your PATH environment variable is properly configured");
}
Assume.assumeNoException(ioe); // failed to check availability of hg
}
}
private Launcher launcher() {
return j.jenkins.createLauncher(listener);
}
private HgExe hgExe() throws Exception {
return new HgExe(null, null, launcher(), j.jenkins, listener, new EnvVars());
}
public void hg(String... args) throws Exception {
HgExe hg = hgExe();
assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).join());
}
public void hg(File repo, String... args) throws Exception {
HgExe hg = hgExe();
assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).pwd(repo).join());
}
private static ArgumentListBuilder nobody(ArgumentListBuilder args) {
return args.add("--config").add("ui.username=nobody@nowhere.net");
}
public void touchAndCommit(File repo, String... names) throws Exception {
for (String name : names) {
FilePath toTouch = new FilePath(repo).child(name);
if (!toTouch.exists()) {
toTouch.getParent().mkdirs();
toTouch.touch(0);
hg(repo, "add", name);
} else {
toTouch.write(toTouch.readToString() + "extra line\n", "UTF-8");
}
}
hg(repo, "commit", "--message", "added " + Arrays.toString(names));
}
public String buildAndCheck(FreeStyleProject p, String name,
Action... actions) throws Exception {
FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new ABuildCause(), actions).get()); // Somehow this needs a cause or it will fail
if (!b.getWorkspace().child(name).exists()) {
Set<String> children = new TreeSet<String>();
for (FilePath child : b.getWorkspace().list()) {
children.add(child.getName());
}
fail("Could not find " + name + " among " + children);
}
assertNotNull(b.getAction(MercurialTagAction.class));
@SuppressWarnings("deprecation")
String log = b.getLog();
return log;
}
public PollingResult pollSCMChanges(FreeStyleProject p) {
return p.poll(new StreamTaskListener(System.out, Charset
.defaultCharset()));
}
public String getLastChangesetId(File repo) throws Exception {
return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-l1", "--template", "{node}"));
}
public String[] getBranches(File repo) throws Exception {
String rawBranches = hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("branches"));
ArrayList<String> list = new ArrayList<String>();
for (String line: rawBranches.split("\n")) {
// line should contain: <branchName> <revision>:<hash> (yes, with lots of whitespace)
String[] seperatedByWhitespace = line.split("\\s+");
String branchName = seperatedByWhitespace[0];
list.add(branchName);
}
sort(list);
return list.toArray(new String[list.size()]);
}
public String searchLog(File repo, String query) throws Exception {
return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-k", query));
}
}
| mit |
ChinaKim/AdvanceAdapter | app/src/main/java/zhou/adapter/NormalAdapter.java | 1412 | package zhou.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by zzhoujay on 2015/7/22 0022.
*/
public class NormalAdapter extends RecyclerView.Adapter<NormalAdapter.Holder> {
private List<String> msg;
public NormalAdapter(List<String> msg) {
this.msg = msg;
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_normal, null);
Holder holder = new Holder(view);
return holder;
}
@Override
public void onBindViewHolder(Holder holder, int position) {
String m = msg.get(position);
holder.icon.setImageResource(R.mipmap.ic_launcher);
holder.text.setText(m);
}
@Override
public int getItemCount() {
return msg == null ? 0 : msg.size();
}
public static class Holder extends RecyclerView.ViewHolder {
public TextView text;
public ImageView icon;
public Holder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.item_text);
icon = (ImageView) itemView.findViewById(R.id.item_icon);
}
}
}
| mit |
Daskie/Crazy8-CPE-103 | src/UserInterface/Animation/SizeAnimation.java | 731 | package UserInterface.Animation;
/**
* Makes shit get big, makes shit get small.
*/
public class SizeAnimation extends Animation {
protected int iW, iH, fW, fH, cW, cH;
public SizeAnimation(long period, int paceType, boolean loop, int iW, int iH, int fW, int fH) {
super(period, paceType, loop);
this.iW = iW;
this.iH = iH;
this.fW = fW;
this.fH = fH;
this.cW = iW;
this.cH = iH;
}
@Override
protected void updateAnimation(double p) {
cW = (int)Math.round((fW - iW)*p) + iW;
cH = (int)Math.round((fH - iH)*p) + iH;
}
public int getWidth() {
return cW;
}
public int getHeight() {
return cH;
}
}
| mit |
mauriciotogneri/apply | src/main/java/com/mauriciotogneri/apply/compiler/syntactic/nodes/arithmetic/ArithmeticModuleNode.java | 603 | package com.mauriciotogneri.apply.compiler.syntactic.nodes.arithmetic;
import com.mauriciotogneri.apply.compiler.lexical.Token;
import com.mauriciotogneri.apply.compiler.syntactic.TreeNode;
import com.mauriciotogneri.apply.compiler.syntactic.nodes.ExpressionBinaryNode;
public class ArithmeticModuleNode extends ExpressionBinaryNode
{
public ArithmeticModuleNode(Token token, TreeNode left, TreeNode right)
{
super(token, left, right);
}
@Override
public String sourceCode()
{
return String.format("mod(%s, %s)", left.sourceCode(), right.sourceCode());
}
} | mit |
pine613/android-hm | android-hm/src/net/pinemz/hm/gui/SettingsActivity.java | 6222 | package net.pinemz.hm.gui;
import net.pinemz.hm.R;
import net.pinemz.hm.api.HmApi;
import net.pinemz.hm.api.Prefecture;
import net.pinemz.hm.api.PrefectureCollection;
import net.pinemz.hm.storage.CommonSettings;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.common.base.Optional;
public class SettingsActivity
extends BasicActivity
{
public static final String TAG = "SettingsActivity";
private RequestQueue requestQueue;
private HmApi hmApi;
private PrefectureCollection prefectures;
private CommonSettings settings;
private ListView listViewPrefectures;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_settings);
this.requestQueue = Volley.newRequestQueue(this.getApplicationContext());
this.hmApi = new HmApi(this.getApplicationContext(), this.requestQueue);
this.listViewPrefectures = (ListView)this.findViewById(R.id.listViewPrefectures);
assert this.listViewPrefectures != null;
// ÝèNXðõ
this.settings = new CommonSettings(this.getApplicationContext());
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
// s¹{§ðÇÝÞ
this.loadPrefectures();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
this.requestQueue = null;
this.hmApi = null;
// ÝèNXððú
this.settings = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "onCreateOptionsMenu");
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected");
return super.onOptionsItemSelected(item);
}
public void okButtonClicked(View view) {
Log.d(TAG, "okButtonClicked");
assert view instanceof Button;
// »ÝIð³êÄ¢éÚðæ¾
int checkedPosition = this.listViewPrefectures.getCheckedItemPosition();
Log.v(TAG, "onButtonClicked>getCheckedItemPosition = " + checkedPosition);
if (checkedPosition == ListView.INVALID_POSITION) { return; }
// Ið³êÄ¢és¹{§¼ðæ¾
String checkedPrefectureName =
(String)this.listViewPrefectures.getItemAtPosition(checkedPosition);
assert checkedPrefectureName != null;
// s¹{§Ìf[^ðæ¾
Optional<Prefecture> prefecture =
this.prefectures.getByName(checkedPrefectureName);
// f[^ª³íɶݷéê
if (prefecture.isPresent()) {
Log.i(TAG, "Prefecture.id = " + prefecture.get().getId());
Log.i(TAG, "Prefecture.name = " + prefecture.get().getName());
this.saveSettings(prefecture.get());
}
}
public void cancelButtonClicked(View view) {
Log.d(TAG, "cancelButtonClicked");
assert view instanceof Button;
this.cancelSettings();
}
private void setPrefectures(PrefectureCollection prefectures) {
Log.d(TAG, "setPrefectures");
this.prefectures = prefectures;
assert prefectures != null;
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this.getApplicationContext(),
android.R.layout.simple_list_item_single_choice,
prefectures.getNames()
);
this.listViewPrefectures.setAdapter(adapter);
this.listViewPrefectures.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// æªðúóÔÅIð
if (adapter.getCount() > 0) {
int prefectureId = this.settings.loadPrefectureId();
// f[^ªÛ¶³êÄÈ¢êÍAÅÌs¹{§ðIð
if (prefectureId < 0) {
prefectureId = prefectures.getIds()[0];
}
// s¹{§ ID Ìêðæ¾
Integer[] ids = prefectures.getIds();
// êvµ½êAIð
for (int i = 0; i < ids.length; ++i) {
if (ids[i] == prefectureId) {
this.listViewPrefectures.setItemChecked(i, true);
break;
}
}
}
}
/**
* ÝèðÛ¶·é
* @param prefecture Û¶·és¹{§
*/
private void saveSettings(Prefecture prefecture) {
Log.d(TAG, "saveSettings");
assert prefecture != null;
// lðÛ¶
this.settings.savePrefectureId(prefecture.getId());
// bZ[Wð\¦
Toast.makeText(
this.getApplicationContext(),
R.string.setting_save_toast,
Toast.LENGTH_SHORT
).show();
this.finish();
}
/**
* ÝèÌÛ¶ðLZ·é
*/
private void cancelSettings() {
Toast.makeText(
this.getApplicationContext(),
R.string.setting_cancel_toast,
Toast.LENGTH_SHORT
).show();
this.finish();
}
private void loadPrefectures() {
// [fBObZ[Wð\¦
this.showProgressDialog(R.string.loading_msg_prefectures);
// f[^ðÇÝÞ
this.hmApi.getPrefectures(new HmApi.Listener<PrefectureCollection>() {
@Override
public void onSuccess(HmApi api, PrefectureCollection data) {
Log.d(TAG, "HmApi.Listener#onSuccess");
SettingsActivity.this.closeDialog();
SettingsActivity.this.setPrefectures(data);
}
@Override
public void onFailure() {
Log.e(TAG, "HmApi.Listener#onFailure");
SettingsActivity.this.showFinishAlertDialog(
R.string.network_failed_title,
R.string.network_failed_msg_prefectures
);
}
@Override
public void onException(Exception exception) {
Log.e(TAG, "HmApi.Listener#onException", exception);
SettingsActivity.this.showFinishAlertDialog(
R.string.network_error_title,
R.string.network_error_msg_prefectures
);
}
});
}
}
| mit |
jamierocks/Zinc | Example/src/main/java/uk/jamierocks/zinc/example/ExampleCommands.java | 2269 | /*
* This file is part of Zinc, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2016, Jamie Mansfield <https://github.com/jamierocks>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package uk.jamierocks.zinc.example;
import com.google.common.collect.Lists;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandArgs;
import org.spongepowered.api.text.Text;
import uk.jamierocks.zinc.Command;
import uk.jamierocks.zinc.TabComplete;
import java.util.List;
public class ExampleCommands {
@Command(name = "example")
public CommandResult exampleCommand(CommandSource source, CommandArgs args) {
source.sendMessage(Text.of("This is the base command."));
return CommandResult.success();
}
@Command(parent = "example",
name = "sub")
public CommandResult exampleSubCommand(CommandSource source, CommandArgs args) {
source.sendMessage(Text.of("This is a sub command."));
return CommandResult.success();
}
@TabComplete(name = "example")
public List<String> tabComplete(CommandSource source, String args) {
return Lists.newArrayList();
}
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/TermsAndConditionsAcceptanceStatusCollectionPage.java | 2194 | // Template Source: BaseEntityCollectionPage.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.TermsAndConditionsAcceptanceStatus;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionRequestBuilder;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionResponse;
import com.microsoft.graph.http.BaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Terms And Conditions Acceptance Status Collection Page.
*/
public class TermsAndConditionsAcceptanceStatusCollectionPage extends BaseCollectionPage<TermsAndConditionsAcceptanceStatus, TermsAndConditionsAcceptanceStatusCollectionRequestBuilder> {
/**
* A collection page for TermsAndConditionsAcceptanceStatus
*
* @param response the serialized TermsAndConditionsAcceptanceStatusCollectionResponse from the service
* @param builder the request builder for the next collection page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final TermsAndConditionsAcceptanceStatusCollectionResponse response, @Nonnull final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder builder) {
super(response, builder);
}
/**
* Creates the collection page for TermsAndConditionsAcceptanceStatus
*
* @param pageContents the contents of this page
* @param nextRequestBuilder the request builder for the next page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final java.util.List<TermsAndConditionsAcceptanceStatus> pageContents, @Nullable final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder nextRequestBuilder) {
super(pageContents, nextRequestBuilder);
}
}
| mit |
AgeOfWar/Telejam | src/main/java/io/github/ageofwar/telejam/updates/UpdateReader.java | 4138 | package io.github.ageofwar.telejam.updates;
import io.github.ageofwar.telejam.Bot;
import io.github.ageofwar.telejam.TelegramException;
import io.github.ageofwar.telejam.methods.GetUpdates;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.LongUnaryOperator;
/**
* Utility class that reads new updates received from a bot.
*
* @author Michi Palazzo
*/
public final class UpdateReader implements AutoCloseable {
private final Bot bot;
private final ConcurrentLinkedQueue<Update> updates;
private final LongUnaryOperator backOff;
private long lastUpdateId;
/**
* Constructs an UpdateReader.
*
* @param bot the bot that receive updates
* @param backOff back off to be used when long polling fails
*/
public UpdateReader(Bot bot, LongUnaryOperator backOff) {
this.bot = Objects.requireNonNull(bot);
this.backOff = Objects.requireNonNull(backOff);
updates = new ConcurrentLinkedQueue<>();
lastUpdateId = -1;
}
/**
* Constructs an UpdateReader.
*
* @param bot the bot that receive updates
*/
public UpdateReader(Bot bot) {
this(bot, a -> 500L);
}
/**
* Returns the number of updates that can be read from this update reader without blocking by the
* next invocation read method for this update reader. The next invocation
* might be the same thread or another thread.
* If the available updates are more than {@code Integer.MAX_VALUE}, returns
* {@code Integer.MAX_VALUE}.
*
* @return the number of updates that can be read from this update reader
* without blocking by the next invocation read method
*/
public int available() {
return updates.size();
}
/**
* Tells whether this stream is ready to be read.
*
* @return <code>true</code> if the next read() is guaranteed not to block for input,
* <code>false</code> otherwise. Note that returning false does not guarantee that the
* next read will block.
*/
public boolean ready() {
return !updates.isEmpty();
}
/**
* Reads one update from the stream.
*
* @return the read update
* @throws IOException if an I/O Exception occurs
* @throws InterruptedException if any thread has interrupted the current
* thread while waiting for updates
*/
public Update read() throws IOException, InterruptedException {
if (!ready()) {
for (long attempts = 0; getUpdates() == 0; attempts++) {
Thread.sleep(backOff.applyAsLong(attempts));
}
}
return updates.remove();
}
/**
* Retrieves new updates received from the bot.
*
* @return number of updates received
* @throws IOException if an I/O Exception occurs
*/
public int getUpdates() throws IOException {
try {
Update[] newUpdates = getUpdates(lastUpdateId + 1);
Collections.addAll(updates, newUpdates);
if (newUpdates.length > 0) {
lastUpdateId = newUpdates[newUpdates.length - 1].getId();
}
return newUpdates.length;
} catch (Throwable e) {
if (!(e instanceof TelegramException)) {
lastUpdateId++;
}
throw e;
}
}
/**
* Discards buffered updates and all received updates.
*
* @throws IOException if an I/O Exception occurs
*/
public void discardAll() throws IOException {
Update[] newUpdate = getUpdates(-1);
if (newUpdate.length == 1) {
lastUpdateId = newUpdate[0].getId();
}
updates.clear();
}
private Update[] getUpdates(long offset) throws IOException {
GetUpdates getUpdates = new GetUpdates()
.offset(offset)
.allowedUpdates();
return bot.execute(getUpdates);
}
@Override
public void close() throws IOException {
try {
Update nextUpdate = updates.peek();
getUpdates(nextUpdate != null ? nextUpdate.getId() : lastUpdateId + 1);
lastUpdateId = -1;
updates.clear();
} catch (IOException e) {
throw new IOException("Unable to close update reader", e);
}
}
}
| mit |
quantumlaser/code2016 | LeetCode/Answers/Leetcode-java-solution/remove_duplicates_from_sorted_list/RemoveDuplicatesfromSortedList.java | 668 | package remove_duplicates_from_sorted_list;
import common.ListNode;
public class RemoveDuplicatesfromSortedList {
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head != null) {
ListNode pre = head;
ListNode p = pre.next;
while (p != null) {
if (p.val == pre.val) {
pre.next = p.next;
} else {
pre = p;
}
p = p.next;
}
}
return head;
}
}
public static class UnitTest {
}
}
| mit |
HSAR/Illume | src/main/java/illume/analysis/SimpleImageAnalyser.java | 852 | package illume.analysis;
import java.awt.image.BufferedImage;
/* This simple analyser example averages pixel values. */
public class SimpleImageAnalyser<T extends BufferedImage> extends AbstractImageAnalyser<T> {
@Override
public double analyse(T input) {
int sum_r = 0;
int sum_g = 0;
int sum_b = 0;
for (int y = 0; y < input.getHeight(); y++) {
for (int x = 0; x < input.getWidth(); x++) {
final int clr = input.getRGB(x, y);
sum_r += (clr & 0x00ff0000) >> 16;
sum_g += (clr & 0x0000ff00) >> 8;
sum_b += clr & 0x000000ff;
}
}
double sum_rgb = ((sum_r + sum_b + sum_g) / 3.0d);
double avg = sum_rgb / (input.getHeight() * input.getWidth());
// 8-bit RGB
return avg / 255;
}
}
| mit |
Covoex/Qarvox | src/main/java/com/covoex/qarvox/Main.java | 227 | package com.covoex.qarvox;
import com.covoex.qarvox.Application.BasicFunction;
/**
* @author Myeongjun Kim
*/
public class Main {
public static void main(String[] args) {
BasicFunction.programStart();
}
}
| mit |
borisbrodski/jmockit | main/src/mockit/external/asm4/Type.java | 25672 | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package mockit.external.asm4;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* A Java field or method type. This class can be used to make it easier to
* manipulate type and method descriptors.
*
* @author Eric Bruneton
* @author Chris Nokleberg
*/
public class Type {
/**
* The sort of the <tt>void</tt> type. See {@link #getSort getSort}.
*/
public static final int VOID = 0;
/**
* The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}.
*/
public static final int BOOLEAN = 1;
/**
* The sort of the <tt>char</tt> type. See {@link #getSort getSort}.
*/
public static final int CHAR = 2;
/**
* The sort of the <tt>byte</tt> type. See {@link #getSort getSort}.
*/
public static final int BYTE = 3;
/**
* The sort of the <tt>short</tt> type. See {@link #getSort getSort}.
*/
public static final int SHORT = 4;
/**
* The sort of the <tt>int</tt> type. See {@link #getSort getSort}.
*/
public static final int INT = 5;
/**
* The sort of the <tt>float</tt> type. See {@link #getSort getSort}.
*/
public static final int FLOAT = 6;
/**
* The sort of the <tt>long</tt> type. See {@link #getSort getSort}.
*/
public static final int LONG = 7;
/**
* The sort of the <tt>double</tt> type. See {@link #getSort getSort}.
*/
public static final int DOUBLE = 8;
/**
* The sort of array reference types. See {@link #getSort getSort}.
*/
public static final int ARRAY = 9;
/**
* The sort of object reference types. See {@link #getSort getSort}.
*/
public static final int OBJECT = 10;
/**
* The sort of method types. See {@link #getSort getSort}.
*/
public static final int METHOD = 11;
/**
* The <tt>void</tt> type.
*/
public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24)
| (5 << 16) | (0 << 8) | 0, 1);
/**
* The <tt>boolean</tt> type.
*/
public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24)
| (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>char</tt> type.
*/
public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24)
| (0 << 16) | (6 << 8) | 1, 1);
/**
* The <tt>byte</tt> type.
*/
public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24)
| (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>short</tt> type.
*/
public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24)
| (0 << 16) | (7 << 8) | 1, 1);
/**
* The <tt>int</tt> type.
*/
public static final Type INT_TYPE = new Type(INT, null, ('I' << 24)
| (0 << 16) | (0 << 8) | 1, 1);
/**
* The <tt>float</tt> type.
*/
public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24)
| (2 << 16) | (2 << 8) | 1, 1);
/**
* The <tt>long</tt> type.
*/
public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24)
| (1 << 16) | (1 << 8) | 2, 1);
/**
* The <tt>double</tt> type.
*/
public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24)
| (3 << 16) | (3 << 8) | 2, 1);
private static final Type[] NO_ARGS = new Type[0];
// ------------------------------------------------------------------------
// Fields
// ------------------------------------------------------------------------
/**
* The sort of this Java type.
*/
private final int sort;
/**
* A buffer containing the internal name of this Java type. This field is
* only used for reference types.
*/
private final char[] buf;
/**
* The offset of the internal name of this Java type in {@link #buf buf} or,
* for primitive types, the size, descriptor and getOpcode offsets for this
* type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset
* for IALOAD or IASTORE, byte 3 the offset for all other instructions).
*/
private final int off;
/**
* The length of the internal name of this Java type.
*/
private final int len;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructs a reference type.
*
* @param sort the sort of the reference type to be constructed.
* @param buf a buffer containing the descriptor of the previous type.
* @param off the offset of this descriptor in the previous buffer.
* @param len the length of this descriptor.
*/
private Type(int sort, char[] buf, int off, int len)
{
this.sort = sort;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param typeDescriptor a field or method type descriptor.
* @return the Java type corresponding to the given type descriptor.
*/
public static Type getType(String typeDescriptor) {
return getType(typeDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given internal name.
*
* @param internalName an internal name.
* @return the Java type corresponding to the given internal name.
*/
public static Type getObjectType(String internalName) {
char[] buf = internalName.toCharArray();
return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length);
}
/**
* Returns the Java type corresponding to the given method descriptor.
* Equivalent to <code>Type.getType(methodDescriptor)</code>.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the given method descriptor.
*/
public static Type getMethodType(String methodDescriptor) {
return getType(methodDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given class.
*
* @param c a class.
* @return the Java type corresponding to the given class.
*/
public static Type getType(Class<?> c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /* if (c == Long.TYPE) */{
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
}
/**
* Returns the Java method type corresponding to the given constructor.
*
* @param c a {@link Constructor Constructor} object.
* @return the Java method type corresponding to the given constructor.
*/
public static Type getType(Constructor<?> c) {
return getType(getConstructorDescriptor(c));
}
/**
* Returns the Java method type corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the Java method type corresponding to the given method.
*/
public static Type getType(Method m) {
return getType(getMethodDescriptor(m));
}
/**
* Returns the Java types corresponding to the argument types of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java types corresponding to the argument types of the given
* method descriptor.
*/
public static Type[] getArgumentTypes(String methodDescriptor) {
if (methodDescriptor.charAt(1) == ')') return NO_ARGS;
char[] buf = methodDescriptor.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while (buf[off++] != ';') {
}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].len + (args[size].sort == OBJECT ? 2 : 0);
size += 1;
}
return args;
}
/**
* Returns the Java type corresponding to the return type of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the return type of the given
* method descriptor.
*/
public static Type getReturnType(String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
}
/**
* Computes the size of the arguments and of the return value of a method.
*
* @param desc the descriptor of a method.
* @return the size of the arguments of the method (plus one for the
* implicit this argument), argSize, and the size of its return
* value, retSize, packed into a single int i =
* <tt>(argSize << 2) | retSize</tt> (argSize is therefore equal
* to <tt>i >> 2</tt>, and retSize to <tt>i & 0x03</tt>).
*/
public static int getArgumentsAndReturnSizes(String desc) {
int n = 1;
int c = 1;
while (true) {
char car = desc.charAt(c++);
if (car == ')') {
car = desc.charAt(c);
return n << 2
| (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1));
} else if (car == 'L') {
while (desc.charAt(c++) != ';') {
}
n += 1;
} else if (car == '[') {
while ((car = desc.charAt(c)) == '[') {
++c;
}
if (car == 'D' || car == 'J') {
n -= 1;
}
} else if (car == 'D' || car == 'J') {
n += 2;
} else {
n += 1;
}
}
}
/**
* Returns the Java type corresponding to the given type descriptor. For
* method descriptors, buf is supposed to contain nothing more than the
* descriptor itself.
*
* @param buf a buffer containing a type descriptor.
* @param off the offset of this descriptor in the previous buffer.
* @return the Java type corresponding to the given type descriptor.
*/
private static Type getType(char[] buf, int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
len = 1;
while (buf[off + len] == '[') {
++len;
}
if (buf[off + len] == 'L') {
++len;
while (buf[off + len] != ';') {
++len;
}
}
return new Type(ARRAY, buf, off, len + 1);
case 'L':
len = 1;
while (buf[off + len] != ';') {
++len;
}
return new Type(OBJECT, buf, off + 1, len - 1);
case '(':
return new Type(METHOD, buf, 0, buf.length);
default:
throw new IllegalArgumentException("Invalid type descriptor: " + new String(buf));
}
}
// ------------------------------------------------------------------------
// Accessors
// ------------------------------------------------------------------------
/**
* Returns the sort of this Java type.
*
* @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN},
* {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT},
* {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG},
* {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY},
* {@link #OBJECT OBJECT} or {@link #METHOD METHOD}.
*/
public int getSort() {
return sort;
}
/**
* Returns the number of dimensions of this array type. This method should
* only be used for an array type.
*
* @return the number of dimensions of this array type.
*/
public int getDimensions() {
int i = 1;
while (buf[off + i] == '[') {
++i;
}
return i;
}
/**
* Returns the type of the elements of this array type. This method should
* only be used for an array type.
*
* @return Returns the type of the elements of this array type.
*/
public Type getElementType() {
return getType(buf, off + getDimensions());
}
/**
* Returns the binary name of the class corresponding to this type. This
* method must not be used on method types.
*
* @return the binary name of the class corresponding to this type.
*/
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
case OBJECT:
return new String(buf, off, len).replace('/', '.');
default:
return null;
}
}
/**
* Returns the internal name of the class corresponding to this object or
* array type. The internal name of a class is its fully qualified name (as
* returned by Class.getName(), where '.' are replaced by '/'. This method
* should only be used for an object or array type.
*
* @return the internal name of the class corresponding to this object type.
*/
public String getInternalName() {
return new String(buf, off, len);
}
// ------------------------------------------------------------------------
// Conversion to type descriptors
// ------------------------------------------------------------------------
/**
* Returns the descriptor corresponding to this Java type.
*
* @return the descriptor corresponding to this Java type.
*/
public String getDescriptor() {
StringBuffer buf = new StringBuffer();
getDescriptor(buf);
return buf.toString();
}
/**
* Appends the descriptor corresponding to this Java type to the given
* string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
*/
private void getDescriptor(StringBuffer buf) {
if (this.buf == null) {
// descriptor is in byte 3 of 'off' for primitive types (buf == null)
buf.append((char) ((off & 0xFF000000) >>> 24));
} else if (sort == OBJECT) {
buf.append('L');
buf.append(this.buf, off, len);
buf.append(';');
} else { // sort == ARRAY || sort == METHOD
buf.append(this.buf, off, len);
}
}
// ------------------------------------------------------------------------
// Direct conversion from classes to type descriptors,
// without intermediate Type objects
// ------------------------------------------------------------------------
/**
* Returns the internal name of the given class. The internal name of a
* class is its fully qualified name, as returned by Class.getName(), where
* '.' are replaced by '/'.
*
* @param c an object or array class.
* @return the internal name of the given class.
*/
public static String getInternalName(Class<?> c) {
return c.getName().replace('.', '/');
}
/**
* Returns the descriptor corresponding to the given Java type.
*
* @param c an object class, a primitive class or an array class.
* @return the descriptor corresponding to the given class.
*/
public static String getDescriptor(Class<?> c) {
StringBuffer buf = new StringBuffer();
getDescriptor(buf, c);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given constructor.
*
* @param c a {@link Constructor Constructor} object.
* @return the descriptor of the given constructor.
*/
public static String getConstructorDescriptor(Constructor<?> c) {
Class<?>[] parameters = c.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
return buf.append(")V").toString();
}
/**
* Returns the descriptor corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the descriptor of the given method.
*/
public static String getMethodDescriptor(Method m) {
Class<?>[] parameters = m.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
buf.append(')');
getDescriptor(buf, m.getReturnType());
return buf.toString();
}
/**
* Appends the descriptor of the given class to the given string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
* @param c the class whose descriptor must be computed.
*/
private static void getDescriptor(StringBuffer buf, Class<?> c) {
Class<?> d = c;
while (true) {
if (d.isPrimitive()) {
char car;
if (d == Integer.TYPE) {
car = 'I';
} else if (d == Void.TYPE) {
car = 'V';
} else if (d == Boolean.TYPE) {
car = 'Z';
} else if (d == Byte.TYPE) {
car = 'B';
} else if (d == Character.TYPE) {
car = 'C';
} else if (d == Short.TYPE) {
car = 'S';
} else if (d == Double.TYPE) {
car = 'D';
} else if (d == Float.TYPE) {
car = 'F';
} else /* if (d == Long.TYPE) */{
car = 'J';
}
buf.append(car);
return;
} else if (d.isArray()) {
buf.append('[');
d = d.getComponentType();
} else {
buf.append('L');
String name = d.getName();
int len = name.length();
for (int i = 0; i < len; ++i) {
char car = name.charAt(i);
buf.append(car == '.' ? '/' : car);
}
buf.append(';');
return;
}
}
}
// ------------------------------------------------------------------------
// Corresponding size and opcodes
// ------------------------------------------------------------------------
/**
* Returns the size of values of this type. This method must not be used for
* method types.
*
* @return the size of values of this type, i.e., 2 for <tt>long</tt> and
* <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise.
*/
public int getSize() {
// the size is in byte 0 of 'off' for primitive types (buf == null)
return buf == null ? off & 0xFF : 1;
}
/**
* Returns a JVM instruction opcode adapted to this Java type. This method
* must not be used for method types.
*
* @param opcode a JVM instruction opcode. This opcode must be one of ILOAD,
* ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL,
* ISHR, IUSHR, IAND, IOR, IXOR and IRETURN.
* @return an opcode that is similar to the given opcode, but adapted to
* this Java type. For example, if this type is <tt>float</tt> and
* <tt>opcode</tt> is IRETURN, this method returns FRETURN.
*/
public int getOpcode(int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
// the offset for IALOAD or IASTORE is in byte 1 of 'off' for
// primitive types (buf == null)
return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4);
} else {
// the offset for other instructions is in byte 2 of 'off' for
// primitive types (buf == null)
return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4);
}
}
// ------------------------------------------------------------------------
// Equals, hashCode and toString
// ------------------------------------------------------------------------
/**
* Tests if the given object is equal to this type.
*
* @param o the object to be compared to this type.
* @return <tt>true</tt> if the given object is equal to this type.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Type)) {
return false;
}
Type t = (Type) o;
if (sort != t.sort) {
return false;
}
if (sort >= ARRAY) {
if (len != t.len) {
return false;
}
for (int i = off, j = t.off, end = i + len; i < end; i++, j++) {
if (buf[i] != t.buf[j]) {
return false;
}
}
}
return true;
}
/**
* Returns a hash code value for this type.
*
* @return a hash code value for this type.
*/
@Override
public int hashCode() {
int hc = 13 * sort;
if (sort >= ARRAY) {
for (int i = off, end = i + len; i < end; i++) {
hc = 17 * (hc + buf[i]);
}
}
return hc;
}
/**
* Returns a string representation of this type.
*
* @return the descriptor of this type.
*/
@Override
public String toString() {
return getDescriptor();
}
}
| mit |
chorsystem/middleware | chorDataModel/src/main/java/org/eclipse/bpel4chor/model/pbd/Query.java | 3371 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.bpel4chor.model.pbd;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Query</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}</li>
* <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}</li>
* <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}</li>
* </ul>
* </p>
*
* @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery()
* @model
* @generated
*/
public interface Query extends ExtensibleElements {
/**
* Returns the value of the '<em><b>Query Language</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Query Language</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Query Language</em>' attribute.
* @see #setQueryLanguage(String)
* @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_QueryLanguage()
* @model
* @generated
*/
String getQueryLanguage();
/**
* Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Query Language</em>' attribute.
* @see #getQueryLanguage()
* @generated
*/
void setQueryLanguage(String value);
/**
* Returns the value of the '<em><b>Opaque</b></em>' attribute.
* The literals are from the enumeration {@link org.eclipse.bpel4chor.model.pbd.OpaqueBoolean}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Opaque</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Opaque</em>' attribute.
* @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean
* @see #setOpaque(OpaqueBoolean)
* @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Opaque()
* @model
* @generated
*/
OpaqueBoolean getOpaque();
/**
* Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Opaque</em>' attribute.
* @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean
* @see #getOpaque()
* @generated
*/
void setOpaque(OpaqueBoolean value);
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(String)
* @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Value()
* @model
* @generated
*/
String getValue();
/**
* Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(String value);
} // Query
| mit |
jkjoschua/poe-ladder-tracker-java | LadderTracker/src/GUIError.java | 2387 | import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.SystemColor;
/**
* The GUIError object is used to show an error message if the Path of Exile API is not responding.
*
* @author Joschn
*/
public class GUIError{
private JFrame windowError;
private JButton buttonRetry;
private volatile boolean buttonPressed = false;
private ButtonRetryListener buttonRetryListener = new ButtonRetryListener();
private String errorMessage = "Error! Path of Exile's API is not responding! Servers are probably down! Check www.pathofexile.com";
private String version = "2.7";
/**
* Constructor for the GUIError object.
*/
public GUIError(){
initialize();
}
/**
* Initializes the GUI.
*/
private void initialize(){
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// error window
windowError = new JFrame();
windowError.setBounds(100, 100, 300, 145);
windowError.setLocation(dim.width/2-windowError.getSize().width/2, dim.height/2-windowError.getSize().height/2);
windowError.setResizable(false);
windowError.setTitle("Ladder Tracker v" + version);
windowError.setIconImage(new ImageIcon(getClass().getResource("icon.png")).getImage());
windowError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windowError.getContentPane().setLayout(null);
// button retry
buttonRetry = new JButton("Retry");
buttonRetry.setBounds(10, 80, 274, 23);
buttonRetry.addActionListener(buttonRetryListener);
windowError.getContentPane().add(buttonRetry);
// error text
JTextPane textError = new JTextPane();
textError.setText(errorMessage);
textError.setEditable(false);
textError.setBackground(SystemColor.menu);
textError.setBounds(10, 21, 274, 39);
windowError.getContentPane().add(textError);
}
/**
* Shows the error GUI and waits for the retry button to be pressed.
*/
public void show(){
windowError.setVisible(true);
while(!buttonPressed){}
windowError.dispose();
}
/**
* The definition of the action listener for the retry button.
*
* @author Joschn
*/
private class ButtonRetryListener implements ActionListener{
public void actionPerformed(ActionEvent e){
buttonPressed = true;
}
}
} | mit |
SummerBlack/MasterServer | app/src/main/java/com/lamost/update/UpdateWebService.java | 2678 | package com.lamost.update;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Log;
/**
* Created by Jia on 2016/4/6.
*/
public class UpdateWebService {
private static final String TAG = "WebService";
// 命名空间
private final static String SERVICE_NS = "http://ws.smarthome.zfznjj.com/";
// 阿里云
private final static String SERVICE_URL = "http://101.201.211.87:8080/zfzn02/services/smarthome?wsdl=SmarthomeWs.wsdl";
// SOAP Action
private static String soapAction = "";
// 调用的方法名称
private static String methodName = "";
private HttpTransportSE ht;
private SoapSerializationEnvelope envelope;
private SoapObject soapObject;
private SoapObject result;
public UpdateWebService() {
ht = new HttpTransportSE(SERVICE_URL); // ①
ht.debug = true;
}
public String getAppVersionVoice(String appName) {
ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
methodName = "getAppVersionVoice";
soapAction = SERVICE_NS + methodName;// 通常为命名空间 + 调用的方法名称
// 使用SOAP1.1协议创建Envelop对象
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // ②
// 实例化SoapObject对象
soapObject = new SoapObject(SERVICE_NS, methodName); // ③
// 将soapObject对象设置为 SoapSerializationEnvelope对象的传出SOAP消息
envelope.bodyOut = soapObject; // ⑤
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
soapObject.addProperty("appName", appName);
try {
// System.out.println("测试1");
ht.call(soapAction, envelope);
// System.out.println("测试2");
// 根据测试发现,运行这行代码时有时会抛出空指针异常,使用加了一句进行处理
if (envelope != null && envelope.getResponse() != null) {
// 获取服务器响应返回的SOAP消息
// System.out.println("测试3");
result = (SoapObject) envelope.bodyIn; // ⑦
// 接下来就是从SoapObject对象中解析响应数据的过程了
// System.out.println("测试4");
String flag = result.getProperty(0).toString();
Log.e(TAG, "*********Webservice masterReadElecticOrder 服务器返回值:"
+ flag);
return flag;
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} finally {
resetParam();
}
return -1 + "";
}
private void resetParam() {
envelope = null;
soapObject = null;
result = null;
}
}
| mit |
yunxu-it/GMeizi | app/src/main/java/cn/winxo/gank/module/view/DetailActivity.java | 3411 | package cn.winxo.gank.module.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import cn.winxo.gank.R;
import cn.winxo.gank.adapter.DetailTitleBinder;
import cn.winxo.gank.adapter.DetailViewBinder;
import cn.winxo.gank.base.BaseMvpActivity;
import cn.winxo.gank.data.Injection;
import cn.winxo.gank.data.entity.constants.Constant;
import cn.winxo.gank.data.entity.remote.GankData;
import cn.winxo.gank.module.contract.DetailContract;
import cn.winxo.gank.module.presenter.DetailPresenter;
import cn.winxo.gank.util.Toasts;
import java.text.SimpleDateFormat;
import java.util.Locale;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
public class DetailActivity extends BaseMvpActivity<DetailContract.Presenter> implements DetailContract.View {
protected Toolbar mToolbar;
protected RecyclerView mRecycler;
protected SwipeRefreshLayout mSwipeLayout;
private long mDate;
private MultiTypeAdapter mTypeAdapter;
@Override protected int setLayoutResourceID() {
return R.layout.activity_detail;
}
@Override protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
mDate = getIntent().getLongExtra(Constant.ExtraKey.DATE, -1);
}
@Override protected void initView() {
mToolbar = findViewById(R.id.toolbar);
mRecycler = findViewById(R.id.recycler);
mSwipeLayout = findViewById(R.id.swipe_layout);
mToolbar.setNavigationOnClickListener(view -> finish());
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mTypeAdapter = new MultiTypeAdapter();
mTypeAdapter.register(String.class, new DetailTitleBinder());
DetailViewBinder detailViewBinder = new DetailViewBinder();
detailViewBinder.setOnItemTouchListener((v, gankData) -> {
Intent intent = new Intent();
intent.setClass(DetailActivity.this, WebActivity.class);
intent.putExtra("url", gankData.getUrl());
intent.putExtra("name", gankData.getDesc());
startActivity(intent);
});
mTypeAdapter.register(GankData.class, detailViewBinder);
mRecycler.setAdapter(mTypeAdapter);
mSwipeLayout.setOnRefreshListener(() -> mPresenter.refreshDayGank(mDate));
}
@Override protected void initData() {
if (mDate != -1) {
String dateShow = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(mDate);
mToolbar.setTitle(dateShow);
mSwipeLayout.setRefreshing(true);
mPresenter.loadDayGank(mDate);
} else {
finish();
}
}
@Override protected DetailPresenter onLoadPresenter() {
return new DetailPresenter(this, Injection.provideGankDataSource(this));
}
@Override public void showLoading() {
mSwipeLayout.setRefreshing(true);
}
@Override public void hideLoading() {
mSwipeLayout.setRefreshing(false);
}
@Override public void loadSuccess(Items items) {
hideLoading();
mTypeAdapter.setItems(items);
mTypeAdapter.notifyDataSetChanged();
}
@Override public void loadFail(String message) {
Toasts.showShort("数据加载失败,请稍后再试");
Log.e("DetailActivity", "loadFail: " + message);
}
}
| mit |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 67