repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ceji-longquan/ceji_android
app/src/main/java/com/lqtemple/android/lqbookreader/model/MusicMedia.java
2766
package com.lqtemple.android.lqbookreader.model; import java.io.Serializable; /**音乐信息 * Created by chenling on 2016/3/15. */ public class MusicMedia implements Serializable{ private int id; private String title; private String artist; private String url; private String time; private String size; private int albumId; private String album; private int duration; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getTime() { return time; } //格式化时间 public void setTime(int time) { time /= 1000; int minute = time / 60; int hour = minute / 60; int second = time % 60; minute %= 60; this.time = String.format("%02d:%02d", minute, second); } public String getSize() { return size; } public void setSize(Long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; if (size >= gb) { this.size = String.format("%.1f GB", (float) size / gb); } else if (size >= mb) { float f = (float) size / mb; this.size = String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); } else if (size >= kb) { float f = (float) size / kb; this.size = String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); } else this.size = String.format("%d B", size); } public int getAlbumId() { return albumId; } public void setAlbumId(int albumId) { this.albumId = albumId; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } @Override public String toString() { return "MusicMedia{" + "id=" + id + ", title='" + title + '\'' + ", artist='" + artist + '\'' + ", url='" + url + '\'' + ", time='" + time + '\'' + ", size='" + size + '\'' + ", albumId=" + albumId + ", album='" + album + '\'' + '}'; } }
mit
github/codeql
java/ql/src/Security/CWE/CWE-090/LdapInjectionJndi.java
1337
import javax.naming.directory.DirContext; import org.owasp.esapi.Encoder; import org.owasp.esapi.reference.DefaultEncoder; public void ldapQueryBad(HttpServletRequest request, DirContext ctx) throws NamingException { String organizationName = request.getParameter("organization_name"); String username = request.getParameter("username"); // BAD: User input used in DN (Distinguished Name) without encoding String dn = "OU=People,O=" + organizationName; // BAD: User input used in search filter without encoding String filter = "username=" + userName; ctx.search(dn, filter, new SearchControls()); } public void ldapQueryGood(HttpServletRequest request, DirContext ctx) throws NamingException { String organizationName = request.getParameter("organization_name"); String username = request.getParameter("username"); // ESAPI encoder Encoder encoder = DefaultEncoder.getInstance(); // GOOD: Organization name is encoded before being used in DN String safeOrganizationName = encoder.encodeForDN(organizationName); String safeDn = "OU=People,O=" + safeOrganizationName; // GOOD: User input is encoded before being used in search filter String safeUsername = encoder.encodeForLDAP(username); String safeFilter = "username=" + safeUsername; ctx.search(safeDn, safeFilter, new SearchControls()); }
mit
Jacob-Gray/Ario
src/sample/Controller.java
1145
package sample; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TextArea; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class Controller implements Initializable { @FXML private TextArea input; @FXML private TextFlow display; public void FocusInput(){ input.requestFocus(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { Editor ed = new Editor(); input.textProperty().addListener((observableValue, s, s2) -> { display.getChildren().clear(); ed.render(observableValue.getValue()); List x = ed.parse(); x.forEach(i -> { List y = (List) i; Text t1 = new Text(y.get(1) + " "); if((int) y.get(0) == 1) t1.setFill(Color.BLUE); display.getChildren().add(t1); System.out.println(i); }); }); } }
mit
JoshGlazebrook/tictactoe-glazebrook
api/src/main/java/com/glazebrook/tictactoe/responses/JoinGameResponse.java
1004
package com.glazebrook.tictactoe.responses; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; import java.util.UUID; public class JoinGameResponse { @JsonProperty @NotNull private UUID gameId; @JsonProperty @NotNull private UUID playerId; @JsonProperty @NotNull private UUID token; public JoinGameResponse() { } public JoinGameResponse(UUID gameId, UUID playerId, UUID token) { this.gameId = gameId; this.playerId = playerId; this.token = token; } public UUID getGameId() { return gameId; } public void setGameId(UUID gameId) { this.gameId = gameId; } public UUID getToken() { return token; } public void setToken(UUID token) { this.token = token; } public UUID getPlayerId() { return playerId; } public void setPlayerId(UUID playerId) { this.playerId = playerId; } }
mit
quyenlm/pokersu
poker-common/src/main/java/com/mrmq/poker/common/glossary/ServiceType.java
230
package com.mrmq.poker.common.glossary; public enum ServiceType { ADMIN("admin"), POKER("poker"); String value; private ServiceType(String value) { this.value = value; } public String getValue(){ return value; } }
mit
ytimesru/kkm-pc-client
src/main/java/ru/fsrar/wegais/infoversionttn/ObjectFactory.java
1434
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.06.05 at 08:50:12 PM SAMT // package ru.fsrar.wegais.infoversionttn; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the ru.fsrar.wegais.infoversionttn package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ru.fsrar.wegais.infoversionttn * */ public ObjectFactory() { } /** * Create an instance of {@link InfoVersionTTN } * */ public InfoVersionTTN createInfoVersionTTN() { return new InfoVersionTTN(); } }
mit
raptor-mvk/BiblioGuide-Java
src/ru/mvk/biblioGuide/service/BookCaseViewService.java
1907
/** * (c) raptor_MVK, 2015. All rights reserved. */ package ru.mvk.biblioGuide.service; import org.jetbrains.annotations.NotNull; import ru.mvk.biblioGuide.dao.BookCaseDao; import ru.mvk.biblioGuide.model.BookCase; import ru.mvk.iluvatar.descriptor.ListViewInfo; import ru.mvk.iluvatar.descriptor.ListViewInfoImpl; import ru.mvk.iluvatar.descriptor.ViewInfo; import ru.mvk.iluvatar.descriptor.ViewInfoImpl; import ru.mvk.iluvatar.descriptor.column.NumColumnInfo; import ru.mvk.iluvatar.descriptor.column.StringColumnInfo; import ru.mvk.iluvatar.descriptor.field.NaturalFieldInfo; import ru.mvk.iluvatar.descriptor.field.TextFieldInfo; import ru.mvk.iluvatar.module.db.HibernateAdapter; import ru.mvk.iluvatar.service.ViewServiceDescriptor; import ru.mvk.iluvatar.service.ViewServiceImpl; import ru.mvk.iluvatar.view.Layout; public class BookCaseViewService extends ViewServiceImpl<BookCase> { public BookCaseViewService(@NotNull HibernateAdapter hibernateAdapter, @NotNull Layout layout) { super(new ViewServiceDescriptor<>(new BookCaseDao(hibernateAdapter), prepareBookCaseViewInfo(), prepareAuthorListViewInfo()), layout, "Шкафы"); } @NotNull private static ViewInfo<BookCase> prepareBookCaseViewInfo() { @NotNull ViewInfo<BookCase> viewInfo = new ViewInfoImpl<>(BookCase.class); viewInfo.addFieldInfo("name", new TextFieldInfo("Название", 20)); viewInfo.addFieldInfo("shelfCount", new NaturalFieldInfo<>(Byte.class, "Кол-во полок", 2)); return viewInfo; } @NotNull private static ListViewInfo<BookCase> prepareAuthorListViewInfo() { @NotNull ListViewInfo<BookCase> listViewInfo = new ListViewInfoImpl<>(BookCase.class); listViewInfo.addColumnInfo("lowerName", new StringColumnInfo("Название", 20)); listViewInfo.addColumnInfo("lowerInitials", new NumColumnInfo("Полок", 5)); return listViewInfo; } }
mit
ssindelar/ps2-parser
src/test/java/com/github/ssindelar/ps2parser/WorldDaoTest.java
1256
package com.github.ssindelar.ps2parser; import static org.fest.assertions.api.Assertions.assertThat; import org.testng.annotations.Test; import com.github.ssindelar.ps2parser.data.world.WorldResponse; import com.github.ssindelar.ps2parser.data.world.status.ApiWorldStatus; import com.github.ssindelar.ps2parser.data.world.status.WorldStatusResponds; public class WorldDaoTest { private final WorldApiDAO dao = TestData.API_CONNECTION.getWorldDao(); @Test public void getAllWorlds() { WorldResponse worldResponse = this.dao.getAllWorlds(); assertThat(worldResponse).isNotNull(); assertThat(worldResponse.getWorlds().size()).isEqualTo(worldResponse.getReturned()); } @Test public void getStatusAllWorlds() { WorldStatusResponds statusResponse = this.dao.getStatusAllWorlds(); assertThat(statusResponse).isNotNull(); assertThat(statusResponse.getAdditionalProperties()).isEmpty(); assertThat(statusResponse.getWorlds().size()).isEqualTo(statusResponse.getReturned()); for (ApiWorldStatus worldStatus : statusResponse.getWorlds()) { assertThat(worldStatus.getAdditionalProperties()).isEmpty(); assertThat(worldStatus.getLastReported()).isNotNull(); assertThat(worldStatus.getGame()).isNotNull().isEqualTo("ps2"); } } }
mit
thomasloto/migang-crawler
src/aos/java/cn/osworks/aos/core/captcha/filter/library/DoubleRippleImageOp.java
1248
/* * Copyright (c) 2009 Piotr Piastucki * * This file is part of Patchca CAPTCHA library. * * Patchca is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Patchca is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Patchca. If not, see <http://www.gnu.org/licenses/>. */ package cn.osworks.aos.core.captcha.filter.library; public class DoubleRippleImageOp extends RippleImageOp { @Override protected void transform(int x, int y, double[] t) { double tx = Math.sin((double) y / yWavelength + yRandom) + 1.3 * Math.sin((double) 0.6 * y / yWavelength + yRandom); double ty = Math.cos((double) x / xWavelength + xRandom) + 1.3 * Math.cos((double) 0.6 * x / xWavelength + xRandom); t[0] = x + xAmplitude * tx; t[1] = y + yAmplitude * ty; } }
mit
lordmarkm/baldy-commons
baldy-commons-models/src/main/java/com/baldy/commons/models/ref/RentalStatus.java
126
package com.baldy.commons.models.ref; /** * @author mbmartinez */ public enum RentalStatus { AVAILABLE, LEASED }
mit
weiht/nrt.core
nrt-core-config/src/main/java/org/necros/settings/CascadingServiceInjector.java
644
/** * */ package org.necros.settings; /** * @author weiht * */ public class CascadingServiceInjector<T> { private Integer zIndex = 0; private T service; private CascadingService<T> cascadingService; public void doInject() { if (cascadingService != null && service != null) { cascadingService.injectImplementer(zIndex, service); } } public void setzIndex(Integer zIndex) { this.zIndex = zIndex; } public void setService(T service) { this.service = service; } public void setCascadingService(CascadingService<T> cascadingService) { this.cascadingService = cascadingService; } }
mit
Pamplemousse/bemydiary
src/com/lesgrosspoof/bemydiary/network/MediaUploader.java
4261
package com.lesgrosspoof.bemydiary.network; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import com.lesgrosspoof.bemydiary.AbstractActivity; import com.lesgrosspoof.bemydiary.R; import com.lesgrosspoof.bemydiary.entities.ItemSelection; import com.lesgrosspoof.bemydiary.entities.Media; import com.lesgrosspoof.bemydiary.entities.MediaToUpload; import com.lesgrosspoof.bemydiary.models.Boards; import com.lesgrosspoof.bemydiary.models.Medias; import com.lesgrosspoof.bemydiary.models.Selections; public class MediaUploader implements AsyncResultListener { private static MediaUploader _instance; private ArrayList<MediaToUpload> queue; private boolean isUploading; private AbstractActivity activity; public static MediaUploader getInstance() { if (_instance == null) _instance = new MediaUploader(); return _instance; } public void setCallbackActivity(AbstractActivity activity) { this.activity = activity; } private MediaUploader() { queue = new ArrayList<MediaToUpload>(); } public void addToQueue(MediaToUpload m) { queue.add(m); if(!isUploading) { System.out.println("connection is not busy, let's upload !"); notifyLoading(); uploadNext(); } else { System.out.println("oops, must wait until previous upload finishes..."); } System.out.println("queue : "+queue.toString()); } private void uploadNext() { if(queue.size() > 0) { System.out.println("beginning upload..."); isUploading = true; MediaToUpload media = queue.get(0); AsyncRequest request = new AsyncRequest(this, AsyncRequest.UPLOAD_MEDIA, "http://dev.bemydiary.fr/media.json", "POST", AuthManager.getInstance().getCookie()); HashMap<String, String> params = new HashMap<String, String>(); String id_selection_site = null; List<ItemSelection> selections = Selections.getInstance().get(Boards.getInstance().getCurrentBoardId()); for(ItemSelection item : selections) { if(item.getId() == Integer.parseInt(media.getId_lieu())) { id_selection_site = item.getId_site(); break; } } params.put("medium[selection_id]", id_selection_site); params.put("authenticity_token", AuthManager.getInstance().getCsrf_token()); System.out.println("csrf : "+AuthManager.getInstance().getCsrf_token()); params.put("medium[upload]", media.getMedia().getContent()); request.execute(params); } else { System.out.println("Queue is empty, my job here is done !"); this.deleteNotification(); } } private void uploadFinished() { System.out.println("upload finished."); isUploading = false; queue.remove(0); uploadNext(); } public void callback(String result, int type) { JSONObject json = null; try { json = new JSONObject(result); } catch (JSONException e) { e.printStackTrace(); } if(type == AsyncRequest.UPLOAD_MEDIA) { if(json != null) { System.out.println("Response : "+json.toString()); Media lastMedia = queue.get(0).getMedia(); try { lastMedia.setId_site(json.getString("_id")); } catch (JSONException e) { e.printStackTrace(); } Medias.getInstance().update(lastMedia); } uploadFinished(); } } private final void notifyLoading() { Notification notification = new Notification(R.drawable.wheelanim, null, System.currentTimeMillis()); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(), 0); notification.flags |= Notification.FLAG_NO_CLEAR; notification.setLatestEventInfo(activity, "Publication du carnet", "Mise à jour des médias...", pendingIntent); ((NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE)).notify( 1338, notification); } private final void deleteNotification() { ((NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE)).cancel(1338); } public boolean isUploading() { return isUploading; } }
mit
asposemarketplace/Aspose-Slides-Java
src/programmersguide/workingwithpresentation/convertingpresentationwithnotestotiff/java/ConvertingPresentationWithNotesToTiff.java
1098
/* * Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved. * * This file is part of Aspose.Slides. The source code in this file * is only intended as a supplement to the documentation, and is provided * "as is", without warranty of any kind, either expressed or implied. */ package programmersguide.workingwithpresentation.convertingpresentationwithnotestotiff.java; import com.aspose.slides.Presentation; import com.aspose.slides.SaveFormat; public class ConvertingPresentationWithNotesToTiff { public static void main(String[] args) throws Exception { // The path to the documents directory. String dataDir = "src/programmersguide/workingwithpresentation/convertingpresentationtotiff/convertingwithdefaultsize/data/"; //Instantiate a Presentation object that represents a presentation file Presentation pres = new Presentation(dataDir+ "Aspose.pptx"); //Saving the presentation to TIFF notes pres.save(dataDir+ "TestNotes.tiff", SaveFormat.TiffNotes); System.out.println("Program executed successfully"); } }
mit
CS2103AUG2016-F11-C1/main
src/main/java/seedu/todo/ui/UiManager.java
5299
package seedu.todo.ui; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.stage.Stage; import seedu.todo.commons.util.StringUtil; import seedu.todo.commons.core.ComponentManager; import seedu.todo.commons.core.Config; import seedu.todo.commons.core.LogsCenter; import seedu.todo.ui.views.View; import java.util.logging.Logger; // @@author A0139812A /** * The manager of the UI component. * * Singleton class for other modules to interact * with the UI. Provides two methods {@code loadView} and * {@code renderView}, which generate a view controller * and subsequently rendering it after passing/binding * relevant properties. */ public class UiManager extends ComponentManager implements Ui { private static final Logger logger = LogsCenter.getLogger(UiManager.class); // Only one instance of UiManager should be present. private static UiManager instance = null; // Only one currentView. public static View currentView; private static String currentConsoleMessage = ""; private static String currentConsoleInputValue = ""; private Config config; private MainWindow mainWindow; private static final String FATAL_ERROR_DIALOG = "Fatal error during initializing"; private static final String LOAD_VIEW_ERROR = "Cannot loadView: UiManager not instantiated."; protected UiManager() { // Prevent instantiation. } public static UiManager getInstance() { return instance; } public static void initialize(Config config) { if (instance == null) { instance = new UiManager(); } instance.config = config; } @Override public void start(Stage primaryStage) { logger.info("Starting UI..."); // Show main window. try { mainWindow = UiPartLoader.loadUiPart(primaryStage, null, MainWindow.class); mainWindow.configure(config); mainWindow.render(); mainWindow.show(); } catch (Throwable e) { logger.severe(StringUtil.getDetails(e)); showFatalErrorDialogAndShutdown(FATAL_ERROR_DIALOG, e); } } @Override public void stop() { mainWindow.hide(); } public MainWindow getMainWindow() { return mainWindow; } /** * Helper function to load view into the MainWindow. */ public static <T extends View> T loadView(Class<T> viewClass) { if (instance == null) { logger.warning(LOAD_VIEW_ERROR); return null; } return instance.mainWindow.loadView(viewClass); } /** * Updates the currentView and renders it. * * @param view View to render. */ public static void renderView(View view) { if (view != null && view.getNode() != null) { currentView = view; // Clear console values first currentConsoleInputValue = ""; currentConsoleMessage = ""; // Render view view.render(); } } public static String getConsoleMessage() { return currentConsoleMessage; } public static String getConsoleInputValue() { return currentConsoleInputValue; } /** * Sets the message shown in the console and reloads the console box. * Does not do anything if no views have been loaded yet. * * @param consoleMessage Message to display in the console. */ public static void updateConsoleMessage(String consoleMessage) { if (currentView != null) { currentConsoleMessage = consoleMessage; instance.mainWindow.loadComponents(); } } /** * Sets the message shown in the console input box and reloads the console box. * Does not do anything if no views have been loaded yet. * * @param consoleInputValue Message to display in the console input box. */ public static void updateConsoleInputValue(String consoleInputValue) { if (currentView != null) { currentConsoleInputValue = consoleInputValue; instance.mainWindow.loadComponents(); } } /** ================ DISPLAY ERRORS ================== **/ private void showAlertDialogAndWait(Alert.AlertType type, String title, String headerText, String contentText) { showAlertDialogAndWait(mainWindow.getPrimaryStage(), type, title, headerText, contentText); } private static void showAlertDialogAndWait(Stage owner, AlertType type, String title, String headerText, String contentText) { final Alert alert = new Alert(type); alert.initOwner(owner); alert.setTitle(title); alert.setHeaderText(headerText); alert.setContentText(contentText); alert.showAndWait(); } private void showFatalErrorDialogAndShutdown(String title, Throwable e) { logger.severe(title + " " + e.getMessage() + StringUtil.getDetails(e)); showAlertDialogAndWait(Alert.AlertType.ERROR, title, e.getMessage(), e.toString()); Platform.exit(); System.exit(1); } }
mit
knutgoetz/evka01
Groomba/src/de/vsis/groomba/communication/Log.java
2295
package de.vsis.groomba.communication; public class Log { /** * @author Hannes * * Helps to create different log levels for debugging purposes. * */ public final static int OFF = 0; public final static int ERROR = 1; public final static int INFO = 2; public final static int VERBOSE = 3; public final static int DEBUG = 4; private String _classname = ""; private boolean _verbose = false; private boolean _error = false; private boolean _info = false; private boolean _debug = false; public Log() { // TODO Auto-generated constructor stub setVerbose(); } public Log(int level) { set(level); } public Log(String classname) { _classname = classname; } public void debug(String msg){ if(_debug) { printLogMsg("debug", msg); } } public void log(String msg){ if (_verbose){ printLogMsg("verbose", msg); } } public void error(String msg){ if (_error){ printLogMsg("error", msg); } } public void info(String msg){ if (_info){ printLogMsg("info", msg); } } /** combine and print to console slave * * * @param kind * @param msg */ private void printLogMsg(String kind, String msg){ String fullmsg = ""; if (!_classname.equals("")){ fullmsg = "["+kind+" from "+_classname+"] --- " + msg; } else { fullmsg = "["+kind+"] --- " + msg; } System.out.println(fullmsg); } public void enableAll() { _verbose = true; } public void dissableAll() { _verbose = false; } public void setVerbose(){ _verbose = true; _error = true; _info = true; _debug = true; } public void set(int level){ //0 off, 1 error, 2 info, 3 verbose, 4 Debug(all) switch(level){ case 0: _verbose = false; _error = false; _info = false; _debug = false; break; case 1: _error = true; _verbose = false; _info = false; _debug = false; break; case 2: _error = true; _info = true; _debug = false; _verbose = false; break; case 3: _verbose = true; _error = true; _info = true; _debug = false; break; case 4: setVerbose(); default: _verbose = true; _error = true; _info = true; _debug = true; break; } } }
mit
cngu/android-fun
app/src/main/java/com/cngu/androidfun/main/TopicManager.java
3766
package com.cngu.androidfun.main; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import com.cngu.androidfun.R; import com.cngu.androidfun.data.ActionTopic; import com.cngu.androidfun.data.MenuTopic; import com.cngu.androidfun.data.Topic; import com.cngu.androidfun.view.TopicView; import java.util.ArrayList; /** * A TopicManager serves two purposes: * <ol> * <li>contain an in-memory (i.e. not-persisted) database of {@link Topic}s. * <li>manage a history of selected {@link Topic}s. * </ol> * * <p>Due to the static nature of the Topic menu navigation UI, persistence of these Topics is not * required and can easily be created on demand. */ public class TopicManager implements ITopicManager { private static final String TAG = TopicManager.class.getSimpleName(); private static final String KEY_HISTORY_STACK = "cngu.key.HISTORY_STACK"; public ArrayList<Topic> mTopics; public ArrayList<Topic> mHistory; private boolean mActionTopicReached; public TopicManager(Context context) { LayoutInflater inflater = LayoutInflater.from(context); TopicView rootTopicView = (TopicView) inflater.inflate(R.layout.ui_topic_hierarchy, null); mTopics = new ArrayList<>(); mHistory = new ArrayList<>(); mActionTopicReached = false; Topic rootMenu = generateTopicHierarchy(rootTopicView); mHistory.add(rootMenu); } @Override public boolean isActionTopicReached() { return mActionTopicReached; } @Override public int getHistorySize() { return mHistory.size(); } @Override public Topic getTopicInHistory(int pageNumber) { if (pageNumber < 0 || pageNumber >= mHistory.size()) { return null; } return mHistory.get(pageNumber); } @Override public void pushTopicToHistory(Topic topic) { if (mActionTopicReached) { throw new IllegalStateException("Cannot navigate to Topics beyond an ActionTopic."); } if (topic instanceof ActionTopic) { mActionTopicReached = true; } mHistory.add(topic); } @Override public Topic popTopicFromHistory() { if (mActionTopicReached) { mActionTopicReached = false; } return mHistory.remove(mHistory.size()-1); } @Override public void loadHistory(Bundle savedInstanceState) { mHistory = savedInstanceState.getParcelableArrayList(KEY_HISTORY_STACK); Topic top = mHistory.get(mHistory.size()-1); mActionTopicReached = (top instanceof ActionTopic); } @Override public void saveHistory(Bundle savedInstanceState) { savedInstanceState.putParcelableArrayList(KEY_HISTORY_STACK, mHistory); } @Override public boolean isTopicInHistory(Topic topic) { for (Topic t : mHistory) { if (topic.equals(t)) { return true; } } return false; } private Topic generateTopicHierarchy(TopicView root) { if (root == null) { return null; } String title = root.getTitle(); String description = root.getDescription(); if (root.getChildCount() > 0) { MenuTopic mt = new MenuTopic(title, description, null); for (int i = 0; i < root.getChildCount(); i++) { TopicView child = (TopicView) root.getChildAt(i); mt.addSubtopic(generateTopicHierarchy(child)); } return mt; } else { ActionTopic at = new ActionTopic(title, description, root.getDemoFragmentId()); return at; } } }
mit
JCThePants/NucleusFramework
src/com/jcwhatever/nucleus/internal/managed/scripting/api/SAPI_Locations.java
2857
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * 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 com.jcwhatever.nucleus.internal.managed.scripting.api; import com.jcwhatever.nucleus.Nucleus; import com.jcwhatever.nucleus.mixins.IDisposable; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.coords.NamedLocation; import org.bukkit.Location; import java.util.Collection; import javax.annotation.Nullable; /** * Sub script API for named locations that can be retrieved by scripts. */ public class SAPI_Locations implements IDisposable { private boolean _isDisposed; @Override public boolean isDisposed() { return _isDisposed; } @Override public void dispose() { _isDisposed = true; } /** * Get a quest script location by name. * * @param name The name of the location. */ @Nullable public Location get(String name) { PreCon.notNullOrEmpty(name); NamedLocation result = Nucleus.getScriptManager().getLocations().get(name); if (result == null) return null; return result.toLocation(); } /** * Get all script location objects. */ public Collection<NamedLocation> getScriptLocations() { return Nucleus.getScriptManager().getLocations().getAll(); } /** * Get all script location objects. * * @param output The output collection to put results into. * * @return The output collection. */ public <T extends Collection<NamedLocation>> T getScriptLocations(T output) { PreCon.notNull(output); return Nucleus.getScriptManager().getLocations().getAll(output); } }
mit
jinchen92/JavaBasePractice
src/com/jinwen/thread/ch01/Demo010.java
1232
package com.jinwen.thread.ch01; /** * 知识点:线程挂起的问题 * @author JIN * */ public class Demo010 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { final SynchronizedObject1 object = new SynchronizedObject1(); Thread thread1 = new Thread() { @Override public void run() { object.printString(); } }; thread1.setName("a"); thread1.start(); Thread.sleep(1000); Thread thread2 = new Thread() { @Override public void run() { System.out .println("thread2启动了,但进入不了printString()方法!只打印1个begin"); System.out .println("因为printString()方法被a线程锁定并且永远的suspend暂停了!"); object.printString(); } }; thread2.start(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class SynchronizedObject1 { synchronized public void printString() { System.out.println("begin"); if (Thread.currentThread().getName().equals("a")) { System.out.println("a线程永远 suspend了!"); Thread.currentThread().suspend(); } System.out.println("end"); } }
mit
BioDAG/odysseys
BlastBenchmark/src/blastbenchmark/Lock.java
617
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package blastbenchmark; /** * * @author thanos */ public class Lock { private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while (isLocked) { //System.out.println("locked.. sleeping"); wait(); } isLocked = true; } public synchronized void unlock() { isLocked = false; notify(); } }
mit
plugadoeep/plugado
src/test/java/br/edu/fumep/entity/GrupoEstudoTests.java
1921
package br.edu.fumep.entity; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * Created by arabasso on 09/05/2017. */ public class GrupoEstudoTests { private GrupoEstudo grupoEstudo; private Aluno aluno; private Usuario usuario; @Before public void inicializacao() { grupoEstudo = new GrupoEstudo(); grupoEstudo.setNome("Amigos"); grupoEstudo.setCurso("Ciência da Computação"); grupoEstudo.setMateria("Engenharia de Software II"); grupoEstudo.setProfessor("José da Silva"); grupoEstudo.setCoordenador("João dos Santos"); List<GrupoEstudoAluno> gruposEstudoAlunos = new ArrayList<>(); usuario = new Usuario(); aluno = new Aluno("Paulo", usuario); gruposEstudoAlunos.add(new GrupoEstudoAluno(grupoEstudo, aluno)); grupoEstudo.setGruposEstudoAluno(gruposEstudoAlunos); } @Test public void alunoEstaInseridoGrupo() { assertThat(grupoEstudo.alunoEstaInserido(aluno), is(true)); } @Test public void alunoNuloEstaInseridoGrupo() { assertThat(grupoEstudo.alunoEstaInserido(null), is(false)); } @Test public void temTags(){ assertThat(grupoEstudo.temTags(), is(false)); } @Test public void tagsVazia() { assertThat(grupoEstudo.getTags(), is("")); } @Test public void variasTags() { Tag tag1 = new Tag("Álgebra"); Tag tag2 = new Tag("Cálculo"); grupoEstudo.setGruposEstudoTag(new ArrayList<>()); grupoEstudo.getGruposEstudoTag().add(new GrupoEstudoTag(grupoEstudo, tag1)); grupoEstudo.getGruposEstudoTag().add(new GrupoEstudoTag(grupoEstudo, tag2)); assertThat(grupoEstudo.getTags(), is("Álgebra, Cálculo")); } }
mit
CS2103JAN2017-W14-B4/main
src/main/java/seedu/ezdo/logic/parser/CommandParser.java
236
package seedu.ezdo.logic.parser; import seedu.ezdo.logic.commands.Command; /** * An interface for the command parsers in ezDo. */ public interface CommandParser { /** Parses the given string */ Command parse(String args); }
mit
eslavov11/Doctor-Appointment-Booking-System
src/main/java/com/doctorAppointmentBookingSystem/repository/RoleRepository.java
393
package com.doctorAppointmentBookingSystem.repository; import com.doctorAppointmentBookingSystem.entity.Role; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by Edi on 16-Apr-17. */ @Repository public interface RoleRepository extends JpaRepository<Role, Long> { Role findOneByAuthority(String authority); }
mit
niwaniwa/WhiteEggCore
src/main/java/com/github/niwaniwa/we/core/player/EggPlayer.java
3854
package com.github.niwaniwa.we.core.player; import com.github.niwaniwa.we.core.api.callback.Callback; import com.github.niwaniwa.we.core.twitter.TwitterManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.permissions.Permission; import twitter4j.Status; import twitter4j.StatusUpdate; import java.lang.reflect.InvocationTargetException; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.List; import java.util.UUID; public abstract class EggPlayer implements Twitter, WhitePlayer { private UUID uuid; private Player player; public EggPlayer(Player player) { this.uuid = player.getUniqueId(); this.player = player; } public EggPlayer(UUID uuid){ this.uuid = uuid; this.player = getPlayer(); } @Override public void remove() { player.remove(); } @Override public String getName() { return player.getName(); } @Override public String getFullName() { return getPrefix() + getName(); } @Override public Player getPlayer() { return Bukkit.getPlayer(uuid); } public void update(){ this.player = getPlayer(); } @Override public UUID getUniqueId() { return player.getUniqueId(); } @Override public boolean isOp() { return player.isOp(); } @Override public boolean isOnline() { return player.isOnline(); } @Override public void sendMessage(String message) { this.sendMessage(message, true); } @Override public void sendMessage(String[] message) { Arrays.asList(message).forEach(msg -> sendMessage(msg, true)); } @Override public void sendMessage(String message, boolean replaceColorCode) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } @Override public TwitterManager getTwitterManager() { throw new UnsupportedOperationException(getClass().getSimpleName()); } @Override public boolean hasPermission(String permission) { return player.hasPermission(permission); } @Override public boolean hasPermission(Permission permission) { return player.hasPermission(permission); } @Override public InetSocketAddress getAddress() { return player.getAddress(); } @Override public Object getHandle() { Object object = null; try { object = player.getClass().getMethod("getHandle").invoke(player); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return object; } @Override public Location getLocation() { return player.getLocation(); } @Override public Inventory getInventory() { return player.getInventory(); } @Override public void teleport(Location loc) { player.teleport(loc); } @Override public void teleport(Entity entity) { player.teleport(entity); } @Override public void updateStatus(StatusUpdate update) { throw new UnsupportedOperationException(getClass().getSimpleName()); } @Override public void updateStatus(StatusUpdate update, Callback callback) { throw new UnsupportedOperationException(getClass().getSimpleName()); } @Override public void updateStatus(String tweet) { throw new UnsupportedOperationException(getClass().getSimpleName()); } @Override public List<Status> getTimeLine() { throw new UnsupportedOperationException(getClass().getSimpleName()); } }
mit
Elecs-Mods/RFTools
src/main/java/mcjty/rftools/blocks/dimlets/GuiDimletScrambler.java
2975
package mcjty.rftools.blocks.dimlets; import mcjty.lib.container.GenericGuiContainer; import mcjty.lib.gui.Window; import mcjty.lib.gui.layout.PositionalLayout; import mcjty.lib.gui.widgets.EnergyBar; import mcjty.lib.gui.widgets.ImageLabel; import mcjty.lib.gui.widgets.Panel; import mcjty.lib.gui.widgets.Widget; import mcjty.rftools.RFTools; import mcjty.rftools.network.RFToolsMessages; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.util.ForgeDirection; import java.awt.*; public class GuiDimletScrambler extends GenericGuiContainer<DimletScramblerTileEntity> { public static final int SCRAMBLER_WIDTH = 180; public static final int SCRAMBLER_HEIGHT = 152; private EnergyBar energyBar; private ImageLabel progressIcon; private static final ResourceLocation iconLocation = new ResourceLocation(RFTools.MODID, "textures/gui/dimletscrambler.png"); private static final ResourceLocation iconGuiElements = new ResourceLocation(RFTools.MODID, "textures/gui/guielements.png"); public GuiDimletScrambler(DimletScramblerTileEntity pearlInjectorTileEntity, DimletScramblerContainer container) { super(RFTools.instance, RFToolsMessages.INSTANCE, pearlInjectorTileEntity, container, RFTools.GUI_MANUAL_DIMENSION, "scrambler"); pearlInjectorTileEntity.setCurrentRF(pearlInjectorTileEntity.getEnergyStored(ForgeDirection.DOWN)); xSize = SCRAMBLER_WIDTH; ySize = SCRAMBLER_HEIGHT; } @Override public void initGui() { super.initGui(); int maxEnergyStored = tileEntity.getMaxEnergyStored(ForgeDirection.DOWN); energyBar = new EnergyBar(mc, this).setVertical().setMaxValue(maxEnergyStored).setLayoutHint(new PositionalLayout.PositionalHint(10, 7, 8, 54)).setShowText(false); energyBar.setValue(tileEntity.getCurrentRF()); progressIcon = new ImageLabel(mc, this).setImage(iconGuiElements, 4 * 16, 16); progressIcon.setLayoutHint(new PositionalLayout.PositionalHint(64, 24, 16, 16)); Widget toplevel = new Panel(mc, this).setBackground(iconLocation).setLayout(new PositionalLayout()).addChild(energyBar).addChild(progressIcon); toplevel.setBounds(new Rectangle(guiLeft, guiTop, xSize, ySize)); window = new Window(this, toplevel); tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE); tileEntity.requestScramblingFromServer(); } @Override protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) { int scrambling = tileEntity.getScrambling(); if (scrambling == 0) { progressIcon.setImage(iconGuiElements, 4 * 16, 16); } else { progressIcon.setImage(iconGuiElements, (scrambling % 4) * 16, 16); } drawWindow(); energyBar.setValue(tileEntity.getCurrentRF()); tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE); tileEntity.requestScramblingFromServer(); } }
mit
pitpitman/GraduateWork
petstore1.3_01/src/waf/src/view/taglibs/com/sun/j2ee/blueprints/taglibs/smart/QueryParameterTag.java
2690
/* * Copyright 2002 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of * any nuclear facility. */ package com.sun.j2ee.blueprints.waf.view.taglibs.smart; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.BodyContent; import java.io.IOException; import java.util.*; /** * A parameter for a link (i.e. a key-value pair in string such * as "?foo=yes&bar=5"). */ public class QueryParameterTag extends BodyTagSupport { String name = ""; public void setName(String n) { name = n; } public int doAfterBody() throws JspTagException { LinkTag linkTag = (LinkTag) findAncestorWithClass(this, LinkTag.class); BodyContent bc = getBodyContent(); String value = bc.getString(); if (name != null && !name.trim().equals("") && value != null && !value.trim().equals("")) { linkTag.putParameter(name, bc.getString()); } bc.clearBody(); return SKIP_BODY; } }
mit
miuramo/AnchorGarden
src/jaist/css/covis/cls/ArrayPrimitiveMenu.java
1372
package jaist.css.covis.cls; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import jaist.css.covis.util.FramePopup; public class ArrayPrimitiveMenu extends JPopupMenu implements FramePopup { private static final long serialVersionUID = 8027248166373847225L; Covis_primitive v; Covis_Array a; JFrame f; public ArrayPrimitiveMenu(Covis_primitive _v, Covis_Array _a) { this.v = _v; this.a = _a; JMenuItem menuItem; setLightWeightPopupEnabled(false); menuItem = new JMenuItem("cancel"); add(menuItem); addSeparator(); menuItem = new JMenuItem("edit value"); add(menuItem); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String input; input = JOptionPane.showInputDialog(f, "Input Value", v.getValue()); if (input == null) return; if (!v.setValue(input)){ JOptionPane.showMessageDialog(f,"Value is not accepted.","Error",JOptionPane.WARNING_MESSAGE); return; } v.buffer.putHistoryEditValueArray(v,a); //•ύX‚µ‚½‚çƒ\[ƒXƒR[ƒh‚ɒljÁ Informer.playSound("Pop.wav"); } }); } public void showWithFrame(Component c, int x, int y, JFrame _f) { f = _f; show(c, x, y); } }
mit
wahibhaq/practise-android-stuff
currencyconvertor/src/androidTest/java/com/practise/androidstuff/ApplicationTest.java
356
package com.practise.androidstuff; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
brucevsked/vskeddemolist
vskeddemos/projects/taskdemo/src/com/vsked/timer/MyJobTi.java
498
package com.vsked.timer; import java.util.Date; import java.util.TimerTask; public class MyJobTi extends TimerTask { private String jobName="defaultJob"; private int jobCount=0; public int getJobCount() { return jobCount; } public MyJobTi(String jobName) { super(); this.jobName = jobName; jobCount=0; } @Override public void run() { jobCount++; System.out.println(new Date()+ "this is my job:"+jobName+"|current count is:"+jobCount); } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/javax/naming/directory/InitialDirContext.java
9969
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1999, 2009. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.naming.directory; import java.util.Hashtable; import javax.naming.spi.NamingManager; import javax.naming.*; /** * This class is the starting context for performing * directory operations. The documentation in the class description * of InitialContext (including those for synchronization) apply here. * * * @author Rosanna Lee * @author Scott Seligman * * @see javax.naming.InitialContext * @since 1.3 */ public class InitialDirContext extends InitialContext implements DirContext { /** * Constructs an initial DirContext with the option of not * initializing it. This may be used by a constructor in * a subclass when the value of the environment parameter * is not yet known at the time the <tt>InitialDirContext</tt> * constructor is called. The subclass's constructor will * call this constructor, compute the value of the environment, * and then call <tt>init()</tt> before returning. * * @param lazy * true means do not initialize the initial DirContext; false * is equivalent to calling <tt>new InitialDirContext()</tt> * @throws NamingException if a naming exception is encountered * * @see InitialContext#init(Hashtable) * @since 1.3 */ protected InitialDirContext(boolean lazy) throws NamingException { super(lazy); } /** * Constructs an initial DirContext. * No environment properties are supplied. * Equivalent to <tt>new InitialDirContext(null)</tt>. * * @throws NamingException if a naming exception is encountered * * @see #InitialDirContext(Hashtable) */ public InitialDirContext() throws NamingException { super(); } /** * Constructs an initial DirContext using the supplied environment. * Environment properties are discussed in the * <tt>javax.naming.InitialContext</tt> class description. * * <p> This constructor will not modify <tt>environment</tt> * or save a reference to it, but may save a clone. * Caller should not modify mutable keys and values in * <tt>environment</tt> after it has been passed to the constructor. * * @param environment * environment used to create the initial DirContext. * Null indicates an empty environment. * * @throws NamingException if a naming exception is encountered */ public InitialDirContext(Hashtable<?,?> environment) throws NamingException { super(environment); } private DirContext getURLOrDefaultInitDirCtx(String name) throws NamingException { Context answer = getURLOrDefaultInitCtx(name); if (!(answer instanceof DirContext)) { if (answer == null) { throw new NoInitialContextException(); } else { throw new NotContextException( "Not an instance of DirContext"); } } return (DirContext)answer; } private DirContext getURLOrDefaultInitDirCtx(Name name) throws NamingException { Context answer = getURLOrDefaultInitCtx(name); if (!(answer instanceof DirContext)) { if (answer == null) { throw new NoInitialContextException(); } else { throw new NotContextException( "Not an instance of DirContext"); } } return (DirContext)answer; } // DirContext methods // Most Javadoc is deferred to the DirContext interface. public Attributes getAttributes(String name) throws NamingException { return getAttributes(name, null); } public Attributes getAttributes(String name, String[] attrIds) throws NamingException { return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds); } public Attributes getAttributes(Name name) throws NamingException { return getAttributes(name, null); } public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds); } public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs); } public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs); } public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods); } public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods); } public void bind(String name, Object obj, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs); } public void bind(Name name, Object obj, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs); } public void rebind(String name, Object obj, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs); } public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs); } public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs); } public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs); } public DirContext getSchema(String name) throws NamingException { return getURLOrDefaultInitDirCtx(name).getSchema(name); } public DirContext getSchema(Name name) throws NamingException { return getURLOrDefaultInitDirCtx(name).getSchema(name); } public DirContext getSchemaClassDefinition(String name) throws NamingException { return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name); } public DirContext getSchemaClassDefinition(Name name) throws NamingException { return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name); } // -------------------- search operations public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes); } public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes); } public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes, attributesToReturn); } public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes, attributesToReturn); } public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, filter, cons); } public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, filter, cons); } public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, filterExpr, filterArgs, cons); } public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx(name).search(name, filterExpr, filterArgs, cons); } }
mit
Accordance/microservice-dojo
kata-spring-restdocs/solution/mysvc/src/main/java/msvcdojo/ContactResourceAssembler.java
1105
package msvcdojo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import org.springframework.hateoas.Resource; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; // tag::ResourceAssembler[] @Component public class ContactResourceAssembler extends ResourceAssemblerSupport<Contact, ContactResourceAssembler.ContactResource> { public ContactResourceAssembler() { super(ContactController.class, ContactResource.class); } @Override public ContactResource toResource(Contact entity) { ContactResource resource = createResourceWithId(entity.getId(), entity); resource.add(linkTo(ContactController.class).slash(entity.getId()).slash("accounts").withRel("contact-accounts")); return resource; } @Override protected ContactResource instantiateResource(Contact entity) { return new ContactResource(entity); } static class ContactResource extends Resource<Contact> { public ContactResource(Contact contact) { super(contact); } } } // end::ResourceAssembler[]
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-assessment-service/src/test/java/org/innovateuk/ifs/assessment/invite/controller/ReviewInviteControllerTest.java
10855
package org.innovateuk.ifs.assessment.invite.controller; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.assessment.invite.form.ReviewInviteForm; import org.innovateuk.ifs.assessment.invite.populator.ReviewInviteModelPopulator; import org.innovateuk.ifs.assessment.invite.viewmodel.ReviewInviteViewModel; import org.innovateuk.ifs.invite.resource.RejectionReasonResource; import org.innovateuk.ifs.invite.resource.ReviewInviteResource; import org.innovateuk.ifs.invite.service.RejectionReasonRestService; import org.innovateuk.ifs.review.service.ReviewInviteRestService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MvcResult; import org.springframework.validation.BindingResult; import java.time.ZonedDateTime; import java.util.List; import static java.lang.Boolean.TRUE; import static java.util.Collections.nCopies; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND; import static org.innovateuk.ifs.commons.rest.RestResult.restFailure; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.invite.builder.RejectionReasonResourceBuilder.newRejectionReasonResource; import static org.innovateuk.ifs.review.builder.ReviewInviteResourceBuilder.newReviewInviteResource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(MockitoJUnitRunner.Silent.class) @TestPropertySource(locations = { "classpath:application.properties", "classpath:/application-web-core.properties"} ) public class ReviewInviteControllerTest extends BaseControllerMockMVCTest<ReviewInviteController> { @Spy @InjectMocks private ReviewInviteModelPopulator reviewInviteModelPopulator; @Mock private RejectionReasonRestService rejectionReasonRestService; @Mock private ReviewInviteRestService reviewInviteRestService; private List<RejectionReasonResource> rejectionReasons = newRejectionReasonResource() .withReason("Reason 1", "Reason 2") .build(2); private static final String restUrl = "/invite/panel/"; @Override protected ReviewInviteController supplyControllerUnderTest() { return new ReviewInviteController(); } @Before public void setUp() { when(rejectionReasonRestService.findAllActive()).thenReturn(restSuccess(rejectionReasons)); } @Test public void acceptInvite_loggedIn() throws Exception { Boolean accept = true; mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("acceptInvitation", accept.toString())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/invite-accept/panel/hash/accept")); verifyZeroInteractions(reviewInviteRestService); } @Test public void acceptInvite_notLoggedInAndExistingUser() throws Exception { setLoggedInUser(null); ZonedDateTime panelDate = ZonedDateTime.now(); Boolean accept = true; ReviewInviteResource inviteResource = newReviewInviteResource() .withCompetitionName("my competition") .withPanelDate(panelDate) .build(); ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, false); when(reviewInviteRestService.checkExistingUser("hash")).thenReturn(restSuccess(TRUE)); when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource)); mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("acceptInvitation", accept.toString())) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("assessor-panel-accept-user-exists-but-not-logged-in")); InOrder inOrder = inOrder(reviewInviteRestService); inOrder.verify(reviewInviteRestService).checkExistingUser("hash"); inOrder.verify(reviewInviteRestService).openInvite("hash"); inOrder.verifyNoMoreInteractions(); } @Test public void confirmAcceptInvite() throws Exception { when(reviewInviteRestService.acceptInvite("hash")).thenReturn(restSuccess()); mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "hash")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/assessor/dashboard")); verify(reviewInviteRestService).acceptInvite("hash"); } @Test public void confirmAcceptInvite_hashNotExists() throws Exception { when(reviewInviteRestService.acceptInvite("notExistHash")).thenReturn(restFailure(GENERAL_NOT_FOUND)); mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "notExistHash")) .andExpect(status().isNotFound()); verify(reviewInviteRestService).acceptInvite("notExistHash"); } @Test public void openInvite() throws Exception { ZonedDateTime panelDate = ZonedDateTime.now(); ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition") .withPanelDate(panelDate) .build(); ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, true); when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource)); mockMvc.perform(get(restUrl + "{inviteHash}", "hash")) .andExpect(status().isOk()) .andExpect(view().name("assessor-panel-invite")) .andExpect(model().attribute("model", expectedViewModel)); verify(reviewInviteRestService).openInvite("hash"); } @Test public void openInvite_hashNotExists() throws Exception { when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash"))); mockMvc.perform(get(restUrl + "{inviteHash}", "notExistHash")) .andExpect(model().attributeDoesNotExist("model")) .andExpect(status().isNotFound()); verify(reviewInviteRestService).openInvite("notExistHash"); } @Test public void noDecisionMade() throws Exception { ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition").build(); when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource)); ReviewInviteForm expectedForm = new ReviewInviteForm(); MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")) .andExpect(status().isOk()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors("form", "acceptInvitation")) .andExpect(model().attribute("form", expectedForm)) .andExpect(model().attribute("rejectionReasons", rejectionReasons)) .andExpect(model().attributeExists("model")) .andExpect(view().name("assessor-panel-invite")).andReturn(); ReviewInviteViewModel model = (ReviewInviteViewModel) result.getModelAndView().getModel().get("model"); assertEquals("hash", model.getPanelInviteHash()); assertEquals("my competition", model.getCompetitionName()); ReviewInviteForm form = (ReviewInviteForm) result.getModelAndView().getModel().get("form"); BindingResult bindingResult = form.getBindingResult(); assertTrue(bindingResult.hasErrors()); assertEquals(0, bindingResult.getGlobalErrorCount()); assertEquals(1, bindingResult.getFieldErrorCount()); assertTrue(bindingResult.hasFieldErrors("acceptInvitation")); assertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage()); verify(reviewInviteRestService).openInvite("hash"); verifyNoMoreInteractions(reviewInviteRestService); } @Test public void rejectInvite() throws Exception { Boolean accept = false; when(reviewInviteRestService.rejectInvite("hash")).thenReturn(restSuccess()); mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("acceptInvitation", accept.toString())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/invite/panel/hash/reject/thank-you")); verify(reviewInviteRestService).rejectInvite("hash"); verifyNoMoreInteractions(reviewInviteRestService); } @Test public void rejectInvite_hashNotExists() throws Exception { String comment = String.join(" ", nCopies(100, "comment")); Boolean accept = false; when(reviewInviteRestService.rejectInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash"))); when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash"))); mockMvc.perform(post(restUrl + "{inviteHash}/decision", "notExistHash") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("acceptInvitation", accept.toString())) .andExpect(status().isNotFound()); InOrder inOrder = inOrder(reviewInviteRestService); inOrder.verify(reviewInviteRestService).rejectInvite("notExistHash"); inOrder.verify(reviewInviteRestService).openInvite("notExistHash"); inOrder.verifyNoMoreInteractions(); } @Test public void rejectThankYou() throws Exception { mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash")) .andExpect(status().isOk()) .andExpect(view().name("assessor-panel-reject")) .andReturn(); } }
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-web-core/src/main/java/org/innovateuk/ifs/registration/service/CustomRequestScopeAttr.java
2061
package org.innovateuk.ifs.registration.service; import org.springframework.web.context.request.RequestAttributes; import java.util.HashMap; import java.util.Map; /** * This solves the java.lang.IllegalStateException: Cannot ask for request attribute - request is not active anymore! * Error, Request attributes are reset before the organisation is updates and removed afterwards. * @see https://stackoverflow.com/questions/44121654/inherited-servletrquestattributes-is-marked-completed-before-child-thread-finish * @see https://medium.com/@pranav_maniar/spring-accessing-request-scope-beans-outside-of-web-request-faad27b5ed57 * */ public class CustomRequestScopeAttr implements RequestAttributes { private Map<String, Object> requestAttributeMap = new HashMap<>(); @Override public Object getAttribute(String name, int scope) { if (scope == RequestAttributes.SCOPE_REQUEST) { return this.requestAttributeMap.get(name); } return null; } @Override public void setAttribute(String name, Object value, int scope) { if (scope == RequestAttributes.SCOPE_REQUEST) { this.requestAttributeMap.put(name, value); } } @Override public void removeAttribute(String name, int scope) { if (scope == RequestAttributes.SCOPE_REQUEST) { this.requestAttributeMap.remove(name); } } @Override public String[] getAttributeNames(int scope) { if (scope == RequestAttributes.SCOPE_REQUEST) { return this.requestAttributeMap.keySet().toArray(new String[0]); } return new String[0]; } @Override public void registerDestructionCallback(String name, Runnable callback, int scope) { // Not Supported } @Override public Object resolveReference(String key) { // Not supported return null; } @Override public String getSessionId() { return null; } @Override public Object getSessionMutex() { return null; } }
mit
ghiringh/Wegas
wegas-core/src/main/java/com/wegas/core/security/persistence/User.java
5838
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem * Licensed under the MIT License */ package com.wegas.core.security.persistence; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonView; import com.wegas.core.persistence.AbstractEntity; import com.wegas.core.persistence.game.Player; import com.wegas.core.rest.util.Views; import javax.persistence.*; import java.util.*; ////import javax.xml.bind.annotation.XmlTransient; /** * @author Francois-Xavier Aeberhard (fx at red-agent.com) */ @Entity @Table(name = "users") @NamedQueries({ @NamedQuery(name = "User.findUserPermissions", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :instance") , @NamedQuery(name = "User.findUsersWithRole", query = "SELECT DISTINCT users FROM User users JOIN users.roles r WHERE r.id = :role_id") , @NamedQuery(name = "User.findUserWithPermission", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :permission AND p.user.id =:userId") }) public class User extends AbstractEntity implements Comparable<User> { private static final long serialVersionUID = 1L; /** * */ @Id @GeneratedValue private Long id; /** * */ @OneToMany(mappedBy = "user", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} /*, orphanRemoval = true */) @JsonManagedReference(value = "player-user") private List<Player> players = new ArrayList<>(); /** * */ @OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, orphanRemoval = true) @JsonManagedReference(value = "user-account") private List<AbstractAccount> accounts = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") @JsonIgnore private List<Permission> permissions = new ArrayList<>(); @ManyToMany @JsonView(Views.ExtendedI.class) @JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "users_id", referencedColumnName = "id")}, inverseJoinColumns = { @JoinColumn(name = "roles_id", referencedColumnName = "id")}) private Set<Role> roles = new HashSet<>(); /** * */ public User() { } /** * @param acc */ public User(AbstractAccount acc) { this.addAccount(acc); } @Override public Long getId() { return id; } @Override public void merge(AbstractEntity a) { throw new UnsupportedOperationException("Not supported yet."); } /** * @return all user's players */ //@XmlTransient @JsonIgnore @JsonManagedReference(value = "player-user") public List<Player> getPlayers() { return players; } /** * @param players the players to set */ @JsonManagedReference(value = "player-user") public void setPlayers(List<Player> players) { this.players = players; } /** * @return the accounts */ public List<AbstractAccount> getAccounts() { return accounts; } /** * @param accounts the accounts to set */ public void setAccounts(List<AbstractAccount> accounts) { this.accounts = accounts; } /** * @param account */ public final void addAccount(AbstractAccount account) { this.accounts.add(account); account.setUser(this); } /** * @return first user account */ //@XmlTransient @JsonIgnore public final AbstractAccount getMainAccount() { if (!this.accounts.isEmpty()) { return this.accounts.get(0); } else { return null; } } /** * Shortcut for getMainAccount().getName(); * * @return main account name or unnamed if user doesn't have any account */ public String getName() { if (this.getMainAccount() != null) { return this.getMainAccount().getName(); } else { return "unnamed"; } } /** * @return the permissions */ public List<Permission> getPermissions() { return this.permissions; } /** * @param permissions the permissions to set */ public void setPermissions(List<Permission> permissions) { this.permissions = permissions; for (Permission p : this.permissions) { p.setUser(this); } } public boolean removePermission(Permission permission) { return this.permissions.remove(permission); } /** * @param permission * @return true id the permission has successfully been added */ public boolean addPermission(Permission permission) { if (!this.permissions.contains(permission)) { permission.setUser(this); return this.permissions.add(permission); } else { return false; } } /** * @return the roles */ public Set<Role> getRoles() { return roles; } /** * @param roles the roles to set */ public void setRoles(Set<Role> roles) { this.roles = roles; } /** * @param role */ public void addRole(Role role) { this.roles.add(role); } /** * strike out this account from the role * * @param role */ public void removeRole(Role role) { this.roles.remove(role); } @Override public int compareTo(User o) { return this.getName().toLowerCase(Locale.ENGLISH).compareTo(o.getName().toLowerCase(Locale.ENGLISH)); } }
mit
egg82/Java-Lib
Collections-Lib/src/ninja/egg82/concurrent/IConcurrentSet.java
172
package ninja.egg82.concurrent; import java.util.Set; public interface IConcurrentSet<T> extends Set<T> { //functions int getRemainingCapacity(); int getCapacity(); }
mit
nellochen/springboot-start
springcloud-config-client/src/test/java/com/xiaofeng/SpringcloudConfigClientApplicationTests.java
346
package com.xiaofeng; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringcloudConfigClientApplicationTests { @Test public void contextLoads() { } }
mit
longde123/MultiversePlatform
server/src/multiverse/server/engine/SearchManager.java
7815
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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 multiverse.server.engine; import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import multiverse.server.util.Log; import multiverse.server.objects.ObjectType; import multiverse.server.engine.Searchable; import multiverse.server.messages.SearchMessageFilter; import multiverse.server.messages.SearchMessage; import multiverse.msgsys.*; /** Object search framework. You can search for objects matching your criteria. <p> The platform provides the following searchable collections: <ul> <li>Markers - Search for markers in an instance by marker properties. Use SearchClause {@link multiverse.server.objects.Marker.Search Marker.Search} <li>Regions - Search for regions in an instance by region properties. Use SearchClause {@link multiverse.server.objects.Region.Search Region.Search} <li>Instances - Search for instances by instance properties. Use SearchClass {@link multiverse.server.engine.PropertySearch PropertySearch} </ul> <p> Plugins can register searchable object collections using {@link #registerSearchable registerSearchable()}. */ public class SearchManager { private SearchManager() { } /** Search for matching objects and get selected information. Search occurs for a single ObjectType. Information indicated in the 'SearchSelection' is returned for objects matching the 'SearchClause'. <p> The search clause is a SearchClass sub-class designed specifically for an object type (or class of object types). @param objectType Search for this object type @param searchClause Object matching criteria @param selection Information selection; only the indicated information will be returned. @return Collection of matching objects. */ public static Collection searchObjects(ObjectType objectType, SearchClause searchClause, SearchSelection selection) { SearchMessage message = new SearchMessage(objectType, searchClause, selection); Collector collector = new Collector(message); return collector.getResults(); } static class Collector implements ResponseCallback { public Collector(SearchMessage message) { searchMessage = message; } public Collection getResults() { int expectedResponses = Engine.getAgent().sendBroadcastRPC(searchMessage, this); synchronized (this) { responders += expectedResponses; while (responders != 0) { try { this.wait(); } catch (InterruptedException e) { } } } return results; } public synchronized void handleResponse(ResponseMessage rr) { responders --; GenericResponseMessage response = (GenericResponseMessage) rr; Collection list = (Collection)response.getData(); if (list != null) results.addAll(list); if (responders == 0) this.notify(); } Collection results = new LinkedList(); SearchMessage searchMessage; int responders = 0; } /** Register a new searchable object collection. @param objectType Collection object type. @param searchable Object search implementation. */ public static void registerSearchable(ObjectType objectType, Searchable searchable) { SearchMessageFilter filter = new SearchMessageFilter(objectType); Engine.getAgent().createSubscription(filter, new SearchMessageCallback(searchable), MessageAgent.RESPONDER); } /** Register object match factory. A MatcherFactory returns a Matcher object that works for the given search clause and object class. @param searchClauseClass A SearchClause sub-class. @param instanceClass Instance object class. @param matcherFactory Can return a Matcher object capable of running the SearchClause against the instance object. */ public static void registerMatcher(Class searchClauseClass, Class instanceClass, MatcherFactory matcherFactory) { matchers.put(new MatcherKey(searchClauseClass,instanceClass), matcherFactory); } /** Get object matcher that can apply 'searchClause' to objects of 'instanceClass'. @param searchClause The matching criteria. @param instanceClass Instance object class. */ public static Matcher getMatcher(SearchClause searchClause, Class instanceClass) { MatcherFactory matcherFactory; matcherFactory = matchers.get(new MatcherKey(searchClause.getClass(), instanceClass)); if (matcherFactory == null) { Log.error("runSearch: No matcher for "+searchClause.getClass()+" "+instanceClass); return null; } return matcherFactory.createMatcher(searchClause); } static class MatcherKey { public MatcherKey(Class qt, Class it) { queryType = qt; instanceType = it; } public Class queryType; public Class instanceType; public boolean equals(Object key) { return (((MatcherKey)key).queryType == queryType) && (((MatcherKey)key).instanceType == instanceType); } public int hashCode() { return queryType.hashCode() + instanceType.hashCode(); } } static class SearchMessageCallback implements MessageCallback { public SearchMessageCallback(Searchable searchable) { this.searchable = searchable; } public void handleMessage(Message msg, int flags) { SearchMessage message = (SearchMessage) msg; Collection result = null; try { result = searchable.runSearch( message.getSearchClause(), message.getSearchSelection()); } catch (Exception e) { Log.exception("runSearch failed", e); } Engine.getAgent().sendObjectResponse(message, result); } Searchable searchable; } static Map<MatcherKey,MatcherFactory> matchers = new HashMap<MatcherKey,MatcherFactory>(); }
mit
RangerWolf/Finance-News-Helper
src/crawler/impl/BaiduNewsCrawler.java
2712
package crawler.impl; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import main.Constants; import model.News; import org.horrabin.horrorss.RssFeed; import org.horrabin.horrorss.RssItemBean; import org.horrabin.horrorss.RssParser; import utils.MiscUtils; import utils.USDateParser; import com.google.common.collect.Lists; import crawler.Crawler; import dao.KeywordDAO; import dao.NewsDAO; import dao.mysql.MySQLKeywordDAO; import dao.mysql.MySQLNewsDAO; public class BaiduNewsCrawler implements Crawler{ // private static NewsDAO newsDao = new MongoNewsDAO(); // private static KeywordDAO wordDao = new MongoKeywordDAO(); private NewsDAO newsDao = new MySQLNewsDAO(); private KeywordDAO wordDao = new MySQLKeywordDAO(); @Override public List<String> getKeywords() { return MiscUtils.mergeKeywordList(wordDao.query()); // return wordDao.query(); } @Override public String buildURL(String keyword) { // Baidu新闻采用RSS爬虫的形式 String baseURL = "http://news.baidu.com/ns?word=%s&tn=newsrss&sr=0&cl=2&rn=100&ct=0"; String queryURL = null; try { queryURL = String.format(baseURL, URLEncoder.encode(keyword, "GB2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return queryURL; } @Override public String fetch(String newsURL) { // do nothing return null; } @Override public List<News> parse(String str) { Date now = new Date(); List<News> list = Lists.newArrayList(); RssParser rss = new RssParser(); rss.setCharset("gb2312"); rss.setDateParser(new USDateParser()); try{ RssFeed feed = null; feed = rss.load(str); // Gets and iterate the items of the feed List<RssItemBean> items = feed.getItems(); for(RssItemBean item : items) { News news = new News(); news.setTitle(item.getTitle()); news.setDescription(item.getDescription()); news.setPubFrom(item.getAuthor()); news.setNewsUrl(item.getLink()); news.setDateTime(item.getPubDate().getTime()); long timeDiff = now.getTime() - item.getPubDate().getTime(); if(timeDiff <= Constants.MSEC_PER_DAY) list.add(news); } }catch(Exception e){ e.printStackTrace(); } return list; } @Override public Boolean save(List<News> list) { if(list.size() > 0 && newsDao.save(list) >= 0) { return true; } else return false; } public static void main(String[] args) throws UnknownHostException { } }
mit
reasonml-editor/reasonml-idea-plugin
src/com/reason/ide/console/ClearLogAction.java
918
package com.reason.ide.console; import com.intellij.execution.ui.ConsoleView; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbAwareAction; import org.jetbrains.annotations.NotNull; class ClearLogAction extends DumbAwareAction { private final ConsoleView m_console; ClearLogAction(ConsoleView console) { super("Clear All", "Clear the contents of the logs", AllIcons.Actions.GC); m_console = console; } @Override public void update(@NotNull AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); e.getPresentation().setEnabled(editor != null && editor.getDocument().getTextLength() > 0); } @Override public void actionPerformed(@NotNull AnActionEvent e) { m_console.clear(); } }
mit
bunnyc1986/leetcode
min-stack/src/MinStack.java
1302
import org.junit.Test; import java.util.Stack; import static junit.framework.Assert.assertEquals; /** * https://leetcode.com/problems/min-stack/ */ public class MinStack { class StackItem { int value; int min; StackItem(int value, int min) { this.value = value; this.min = min; } } Stack<StackItem> stack = new Stack<>(); public void push(int x) { if (stack.isEmpty()) { stack.push(new StackItem(x, x)); } else { int min = stack.peek().min; if (x < min) { min = x; } stack.push(new StackItem(x, min)); } } public void pop() { stack.pop(); } public int top() { return stack.peek().value; } public int getMin() { return stack.peek().min; } @Test public void test() { MinStack minStack = new MinStack(); minStack.push(10); assertEquals(10, minStack.getMin()); assertEquals(10, minStack.top()); minStack.push(20); assertEquals(10, minStack.getMin()); assertEquals(20, minStack.top()); minStack.push(5); assertEquals(5, minStack.getMin()); assertEquals(5, minStack.top()); } }
mit
caizixian/algorithm_exercise
LeetCode/104.Maximum Depth of Binary Tree.java
225
public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } else { return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } } }
mit
nab-velocity/java-sdk
velocity-sdk/velocity-services/src/main/java/com/velocity/enums/ApplicationLocation.java
249
/** * */ package com.velocity.enums; /** * This Enum defines the values for ApplicationLocation * * @author Vimal Kumar * @date 12-March-2015 */ public enum ApplicationLocation { HomeInternet, NotSet, OffPremises, OnPremises, Unknown }
mit
KuehneThomas/model-to-model-transformation-generator
src/MetaModels.UmlClass.diagram/src/umlClassMetaModel/diagram/navigator/UmlClassMetaModelNavigatorActionProvider.java
4850
/* * */ package umlClassMetaModel.diagram.navigator; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.emf.common.ui.URIEditorInput; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; import org.eclipse.gmf.runtime.notation.Diagram; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.navigator.CommonActionProvider; import org.eclipse.ui.navigator.ICommonActionConstants; import org.eclipse.ui.navigator.ICommonActionExtensionSite; import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite; import org.eclipse.ui.part.FileEditorInput; /** * @generated */ public class UmlClassMetaModelNavigatorActionProvider extends CommonActionProvider { /** * @generated */ private boolean myContribute; /** * @generated */ private OpenDiagramAction myOpenDiagramAction; /** * @generated */ public void init(ICommonActionExtensionSite aSite) { super.init(aSite); if (aSite.getViewSite() instanceof ICommonViewerWorkbenchSite) { myContribute = true; makeActions((ICommonViewerWorkbenchSite) aSite.getViewSite()); } else { myContribute = false; } } /** * @generated */ private void makeActions(ICommonViewerWorkbenchSite viewerSite) { myOpenDiagramAction = new OpenDiagramAction(viewerSite); } /** * @generated */ public void fillActionBars(IActionBars actionBars) { if (!myContribute) { return; } IStructuredSelection selection = (IStructuredSelection) getContext() .getSelection(); myOpenDiagramAction.selectionChanged(selection); if (myOpenDiagramAction.isEnabled()) { actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, myOpenDiagramAction); } } /** * @generated */ public void fillContextMenu(IMenuManager menu) { } /** * @generated */ private static class OpenDiagramAction extends Action { /** * @generated */ private Diagram myDiagram; /** * @generated */ private ICommonViewerWorkbenchSite myViewerSite; /** * @generated */ public OpenDiagramAction(ICommonViewerWorkbenchSite viewerSite) { super( umlClassMetaModel.diagram.part.Messages.NavigatorActionProvider_OpenDiagramActionName); myViewerSite = viewerSite; } /** * @generated */ public final void selectionChanged(IStructuredSelection selection) { myDiagram = null; if (selection.size() == 1) { Object selectedElement = selection.getFirstElement(); if (selectedElement instanceof umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) { selectedElement = ((umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) selectedElement) .getView(); } else if (selectedElement instanceof IAdaptable) { selectedElement = ((IAdaptable) selectedElement) .getAdapter(View.class); } if (selectedElement instanceof Diagram) { Diagram diagram = (Diagram) selectedElement; if (umlClassMetaModel.diagram.edit.parts.UmlPackageEditPart.MODEL_ID .equals(umlClassMetaModel.diagram.part.UmlClassMetaModelVisualIDRegistry .getModelID(diagram))) { myDiagram = diagram; } } } setEnabled(myDiagram != null); } /** * @generated */ public void run() { if (myDiagram == null || myDiagram.eResource() == null) { return; } IEditorInput editorInput = getEditorInput(myDiagram); IWorkbenchPage page = myViewerSite.getPage(); try { page.openEditor( editorInput, umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditor.ID); } catch (PartInitException e) { umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditorPlugin .getInstance().logError( "Exception while openning diagram", e); //$NON-NLS-1$ } } /** * @generated */ private static IEditorInput getEditorInput(Diagram diagram) { Resource diagramResource = diagram.eResource(); for (EObject nextEObject : diagramResource.getContents()) { if (nextEObject == diagram) { return new FileEditorInput( WorkspaceSynchronizer.getFile(diagramResource)); } if (nextEObject instanceof Diagram) { break; } } URI uri = EcoreUtil.getURI(diagram); String editorName = uri.lastSegment() + '#' + diagram.eResource().getContents().indexOf(diagram); IEditorInput editorInput = new URIEditorInput(uri, editorName); return editorInput; } } }
mit
Dimmerworld/TechReborn
src/main/java/techreborn/tiles/TileGenericMachine.java
3620
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2018 TechReborn * * 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 techreborn.tiles; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import reborncore.api.IToolDrop; import reborncore.api.recipe.IRecipeCrafterProvider; import reborncore.api.tile.IInventoryProvider; import reborncore.common.powerSystem.TilePowerAcceptor; import reborncore.common.recipes.RecipeCrafter; import reborncore.common.util.Inventory; /** * @author drcrazy * */ public abstract class TileGenericMachine extends TilePowerAcceptor implements IToolDrop, IInventoryProvider, IRecipeCrafterProvider{ public String name; public int maxInput; public int maxEnergy; public Block toolDrop; public int energySlot; public Inventory inventory; public RecipeCrafter crafter; /** * @param name String Name for a tile. Do we need it at all? * @param maxInput int Maximum energy input, value in EU * @param maxEnergy int Maximum energy buffer, value in EU * @param toolDrop Block Block to drop with wrench * @param energySlot int Energy slot to use to charge machine from battery */ public TileGenericMachine(String name, int maxInput, int maxEnergy, Block toolDrop, int energySlot) { this.name = "Tile" + name; this.maxInput = maxInput; this.maxEnergy = maxEnergy; this.toolDrop = toolDrop; this.energySlot = energySlot; checkTeir(); } public int getProgressScaled(final int scale) { if (crafter != null && crafter.currentTickTime != 0) { return crafter.currentTickTime * scale / crafter.currentNeededTicks; } return 0; } // TilePowerAcceptor @Override public void update() { super.update(); if (!world.isRemote) { charge(energySlot); } } @Override public double getBaseMaxPower() { return maxEnergy; } @Override public boolean canAcceptEnergy(final EnumFacing direction) { return true; } @Override public boolean canProvideEnergy(final EnumFacing direction) { return false; } @Override public double getBaseMaxOutput() { return 0; } @Override public double getBaseMaxInput() { return maxInput; } // IToolDrop @Override public ItemStack getToolDrop(EntityPlayer p0) { return new ItemStack(toolDrop, 1); } // IInventoryProvider @Override public Inventory getInventory() { return inventory; } // IRecipeCrafterProvider @Override public RecipeCrafter getRecipeCrafter() { return crafter; } }
mit
yanhongwang/TicketBookingSystem
src/elektra/WebChangeCustomerPassword.java
14526
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package elektra; import java.io.IOException; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedOutputStream; import java.io.FileWriter; import java.util.ResourceBundle; import java.util.Properties; import java.util.Date; import java.net.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import javax.servlet.ServletConfig; import javax.servlet.http.HttpSession; import javax.servlet.RequestDispatcher; import javax.mail.*; import javax.activation.*; import javax.mail.internet.*; /** * * @author Rolfs */ public class WebChangeCustomerPassword extends HttpServlet { protected String szElektraConfig = ""; protected String szElektraServer = ""; protected String szElektraServerPort = ""; protected String szRequest = "27"; // Kundenpaßwort ändern protected String szVersion = "270"; protected Integer nDebug; protected String strJSP = ""; protected String strJSPError = ""; protected String strJSPReload = ""; protected ServletContext context; ResourceBundle resource = ResourceBundle.getBundle("elektra.Resource"); /** Adresse/Name des Mailservers, definiert in elektra.properties */ protected String szMailServer = ""; /** gewuenschte From-Adresse, definiert in elektra.properties */ protected String szMailFrom = ""; /** Liste der CC-Adressen, definiert in elektra.properties */ protected String szMailCC = ""; /** Liste der BCC-Adressen, definiert in elektra.properties */ protected String szMailBCC = ""; /** Liste der Reply-Adressen, definiert in elektra.properties */ protected String szMailReply = ""; /** Benutzer auf Mailserver: optional, definiert in elektra.properties */ protected String szMailUserName = ""; /** Passwort auf Mailserver: optional, definiert in elektra.properties */ protected String szMailUserPassword = ""; public void init(ServletConfig config) throws ServletException { super.init(config); // Remember context context = config.getServletContext(); try { szElektraConfig = context.getInitParameter("ElektraConfig"); } catch (Exception e) { e.printStackTrace(); } if (null == szElektraConfig) { throw new ServletException("Servlet configuration property \"ElektraConfig\" is not defined!"); } String szDebug = ""; try { szDebug = context.getInitParameter("Debug"); } catch (Exception e) { e.printStackTrace(); } if (null == szDebug) nDebug = new Integer(0); else nDebug = new Integer(szDebug); // Properties laden Properties props = new Properties(); try { props.load(new FileInputStream(szElektraConfig)); strJSP = props.getProperty("ChangeCustomerPasswordPage"); if (null == strJSP) strJSP = "/jsp/webchangecustomerpassword.jsp"; strJSPError = props.getProperty("ChangeCustomerPasswordErrorPage"); if (null == strJSPError) strJSPError = "/jsp/webchangecustomerpassworderr.jsp"; strJSPReload = props.getProperty("ChangeCustomerPasswordReloadPage"); if (null == strJSPReload) strJSPReload = "/jsp/webchangecustomerpasswordreload.jsp"; } catch (IOException ex) { ex.printStackTrace(); } // Remember context context = config.getServletContext(); } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Date d = new Date(); // Getting current date ChangeCustomerPasswordInData changecustomerpasswordData = new ChangeCustomerPasswordInData(); boolean bHeaderPrinted = false; int nCnt = 1; WriteDebug wd = new WriteDebug(); String szTemp = ""; HttpSession session = request.getSession(); session.getLastAccessedTime(); // try { szTemp = request.getParameter(resource.getString("SysID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("SysID")+" fehlt", e, nDebug); } changecustomerpasswordData.setSysID(szTemp); // try { szTemp = request.getParameter(resource.getString("ClientID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("ClientID")+" fehlt", e, nDebug); } changecustomerpasswordData.setClientID(szTemp); // try { szTemp = request.getParameter("CustomerNumber"); } catch (Exception e) { wd.write(response, "Feld CustomerNumber fehlt", e, nDebug); } if (null == szTemp) changecustomerpasswordData.setCustomerNumber("0"); else changecustomerpasswordData.setCustomerNumber(szTemp); try { szTemp = request.getParameter("Password"); } catch (Exception e) { wd.write(response, "Feld Password fehlt", e, nDebug); } changecustomerpasswordData.setCustomerPassword(szTemp); try { szTemp = request.getParameter("NewPassword"); } catch (Exception e) { wd.write(response, "Feld NewPassword fehlt", e, nDebug); } changecustomerpasswordData.setNewCustomerPassword(szTemp); try { szTemp = request.getParameter("EMail"); } catch (Exception e) { wd.write(response, "Feld EMail fehlt", e, nDebug); } changecustomerpasswordData.setEMail(szTemp); changecustomerpasswordData.setSession(session.getId()); // Properties laden Configuration Conf = new Configuration(context, szElektraConfig, "ElektraServerChangeCustomerPassword", changecustomerpasswordData.getSysID(), changecustomerpasswordData.getClientID(), nDebug.intValue()); szElektraServer = Conf.getServerName(); szElektraServerPort = Conf.getServerPort(); szMailServer = Conf.getMailServer(); szMailFrom = Conf.getMailFrom(); szMailCC = Conf.getMailCC(); szMailBCC = Conf.getMailBCC(); szMailReply = Conf.getMailReply(); if (null == szElektraServer) { wd.write(response, "Internal error!<br />System error: Elektra-Server not defined<br />", nDebug); context.log("Elektra-Server not defined!"); } else { // Daten an DB-Server senden Socket socket = null; ChangeCustomerPasswordOutData changecustomerpasswordOut = new ChangeCustomerPasswordOutData(); if (nDebug.intValue() > 0) context.log(" starting ChangeCustomerpassword."); try { socket = new Socket(szElektraServer, Integer.parseInt(szElektraServerPort)); if (nDebug.intValue() > 1) context.log(" socket created."); //BufferedInputStream is = new BufferedInputStream(socket.getInputStream()); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); // Daten senden try { os.write(szVersion.getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(szRequest.getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); // Encryption try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); // compression try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getSysID().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getClientID().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getCustomerNumber().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getSession().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getNewCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); try { os.write(changecustomerpasswordData.getEMail().getBytes() ); } catch (IOException e) { e.printStackTrace(); } os.write( 9 ); if (nDebug.intValue() > 1) context.log(" flushing: "+os.toString()); os.flush(); // Daten senden, nun auf die Buchung warten changecustomerpasswordOut.readSock(in, szVersion); if (nDebug.intValue() > 4) { wd.write(response, "<br><h2>Getting:</h2>Error: "+changecustomerpasswordOut.getErrorCode(), nDebug ); } if (nDebug.intValue() > 0) context.log(" changecustomerpasswordData performed."); request.setAttribute("changecustomerpasswordData", changecustomerpasswordData); request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut); // Im Fehlerfall if (0 != changecustomerpasswordOut.getErrorCode()) { context.log("Systemerror: "+changecustomerpasswordOut.getErrorCode()); // hole den Request Dispatcher fuer die JSP Datei RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError); //leite auf die JSP Datei zum Anzeigen der Liste weiter dispatcher.forward(request, response); } else { // hole den Request Dispatcher fuer die JSP Datei // Alles OK Password per Mail if (null != szMailServer) { String szMailText = ""; String szKopfText = ""; szKopfText = szKopfText.concat("Ihr neues Password"); /* szMailText = szMailText.concat("Seher geehrte(r) "); szMailText = szMailText.concat(changecustomerpasswordData.getSalution()); szMailText = szMailText.concat(" "); szMailText = szMailText.concat(changecustomerpasswordOut.getName1()); szMailText = szMailText.concat(" "); szMailText = szMailText.concat(changecustomerpasswordOut.getName2()); szMailText = szMailText.concat(" "); szMailText = szMailText.concat(changecustomerpasswordOut.getName3()); szMailText = szMailText.concat(",\r\n\r\n"); szMailText = szMailText.concat("anbei das geaenderte Password für Ihren Kundenzugriff auf den Server von Frankfurt Ticket.\r\n\r\n"); szMailText = szMailText.concat("Ihre Kundennummer : "); szMailText = szMailText.concat(changecustomerpasswordOut.getCustId()); szMailText = szMailText.concat("\r\n"); szMailText = szMailText.concat("Ihr geaendertes Password: "); szMailText = szMailText.concat(changecustomerpasswordOut.getNewPassword()); szMailText = szMailText.concat("\r\n"); Mail m = new Mail(szMailServer, szMailFrom , changecustomerpasswordOut.getEMail(), szMailBCC, szMailCC, szMailReply, szKopfText, szMailText); MailSender.getInstance().sendMail(m); */ } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSP); //leite auf die JSP Datei zum Anzeigen der Liste weiter dispatcher.forward(request, response); } } catch (IOException ioex) { changecustomerpasswordOut.setErrorCode( -999); changecustomerpasswordOut.setErrorMessage(ioex.getLocalizedMessage()); if ( (null != strJSPError) && !strJSPError.equals("")) { request.setAttribute("changecustomerpasswordData", changecustomerpasswordData); request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError); //leite auf die JSP Datei zum Anzeigen der Liste weiter dispatcher.forward(request, response); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
mit
ke2g/cuedRecall
app/src/main/java/com/ke2g/cued_recall/LoginActivity.java
5334
package com.ke2g.cued_recall; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; public class LoginActivity extends ActionBarActivity { public static final String TAG = LoginActivity.class.getSimpleName(); private int discretization; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void doLogin(View V){ if(!getUsername().equals("")) { Intent i = new Intent(this, returnIntent.class); startActivityForResult(i, 1); } } private ArrayList<Point> getUserPoints(String username){ SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); Gson gson = new Gson(); String json = appSharedPrefs.getString(username, ""); if(json.equals("")){ return null; } else { User u = gson.fromJson(json, User.class); return u.getPoints(); } } private String getUserHash(String username){ SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); Gson gson = new Gson(); String json = appSharedPrefs.getString(username, ""); if(json.equals("")){ return null; } else { User u = gson.fromJson(json, User.class); return u.getHash(); } } private void setTry(String username, int total, int invalid) { SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); Gson gson = new Gson(); String json = appSharedPrefs.getString(username, ""); if(!json.equals("")){ User u = gson.fromJson(json, User.class); u.setInvalidLogins(invalid); u.setTotalLogins(total); json = gson.toJson(u); prefsEditor.putString(username, json); prefsEditor.commit(); } } private int getTolerance(){ SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); return Integer.parseInt(SP.getString("tolerance", "75")); } private String getUsername() { EditText et = (EditText) findViewById(R.id.editText_login); return et.getText().toString().trim(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { ArrayList<Point> points = data.getParcelableArrayListExtra("RESULT_CLICKS"); //check if points are the saved ones if(getDiscretization() == 1){ if (CuedRecallIntent.areHashEqual(points, getUserHash(getUsername()), getTolerance())) { setTry(getUsername(), 1, 0); Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show(); } else { setTry(getUsername(), 1, 1); Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show(); } } else { if (CuedRecallIntent.arePointsEqual(points, getUserPoints(getUsername()), getTolerance())) { setTry(getUsername(), 1, 0); Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show(); } else { setTry(getUsername(), 1, 1); Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show(); } } } } public int getDiscretization() { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); return Integer.parseInt(SP.getString("discreType", "0")); } }
mit
PatriciaRosembluth/VoiceMailSimulator
src/BusinessLogic/ConnectionStates/MessageMenuState.java
1243
package BusinessLogic.ConnectionStates; import BusinessLogic.ActualConnection; import BusinessLogic.Message; public class MessageMenuState implements ConnectionState{ public void dial(String key, ActualConnection connection) { if (key.equals("1")) { String output = ""; Message m = connection.currentMailbox.getCurrentMessage(); if (m == null) output += "No messages." + "\n"; else output += m.getText() + "\n"; output += ActualConnection.MESSAGE_MENU_TEXT; connection.speakToAllUIs(output); } else if (key.equals("2")) { connection.currentMailbox.saveCurrentMessage(); connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT); } else if (key.equals("3")) { connection.currentMailbox.removeCurrentMessage(); connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT); } else if (key.equals("4")) { //connection.state = Connection.MAILBOX_MENU; connection.currentState = new MailBoxMenuState(); connection.speakToAllUIs(ActualConnection.MAILBOX_MENU_TEXT); } } public int getState(){ return 4; } }
mit
sivaprasadreddy/jcart
jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java
1464
/** * */ package com.sivalabs.jcart.common.services; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import com.sivalabs.jcart.JCartException; /** * @author Siva * */ @Component public class EmailService { private static final JCLogger logger = JCLogger.getLogger(EmailService.class); @Autowired JavaMailSender javaMailSender; @Value("${support.email}") String supportEmail; public void sendEmail(String to, String subject, String content) { try { // Prepare message using a Spring helper final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setSubject(subject); message.setFrom(supportEmail); message.setTo(to); message.setText(content, true /* isHtml */); javaMailSender.send(message.getMimeMessage()); } catch (MailException | MessagingException e) { logger.error(e); throw new JCartException("Unable to send email"); } } }
mit
vhromada/File_utils
src/main/java/cz/vhromada/utils/file/gui/CopyingFileVisitor.java
5102
package cz.vhromada.utils.file.gui; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import cz.vhromada.validators.Validators; import org.springframework.util.StringUtils; /** * A class represents file visitor for copying directories and files. */ public class CopyingFileVisitor extends SimpleFileVisitor<Path> { /** * Delimiter in replacing text */ private static final String REPLACING_TEXT_DELIMITER = ","; /** * Source directory */ private Path source; /** * Target directory */ private Path target; /** * Replacing patterns */ private List<ReplacePattern> replacePatterns; /** * Directories */ private Deque<Path> directories; /** * Creates a new instance of CopyingFileVisitor. * * @param source source directory * @param target target directory * @param replacingText replacing text * @param newText new text * @throws IllegalArgumentException if source directory is null * or target directory is null * or replacing text is null * or new text is null * or count of replacing texts is different from count of new texts */ public CopyingFileVisitor(final Path source, final Path target, final String replacingText, final String newText) { Validators.validateArgumentNotNull(source, "Source"); Validators.validateArgumentNotNull(target, "Target"); Validators.validateArgumentNotNull(replacingText, "Replacing text"); Validators.validateArgumentNotNull(newText, "New text"); this.source = source; this.target = target; this.directories = new LinkedList<>(); this.replacePatterns = createReplacePatterns(replacingText, newText); } @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { final Path directory = getDirectoryName(dir); directories.addLast(directory); if (!Files.exists(directory)) { Files.createDirectory(directory); } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { directories.removeLast(); return super.postVisitDirectory(dir, exc); } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { FileCopy.copy(file, directories.getLast(), replacePatterns); return super.visitFile(file, attrs); } /** * Returns created replace patters. * * @param replacingText replacing text * @param newText new text * @return created replace patters * @throws IllegalArgumentException if count of replacing texts is different from count of new texts */ private static List<ReplacePattern> createReplacePatterns(final String replacingText, final String newText) { final String[] replacingTexts = StringUtils.tokenizeToStringArray(replacingText, REPLACING_TEXT_DELIMITER); final String[] newTexts = StringUtils.tokenizeToStringArray(newText, REPLACING_TEXT_DELIMITER); if (replacingTexts.length != newTexts.length) { throw new IllegalArgumentException("Count of replacing texts is different from count of new texts"); } final List<ReplacePattern> result = new ArrayList<>(); for (int i = 0; i < replacingTexts.length; i++) { final String source = replacingTexts[i]; final String target = newTexts[i]; result.add(new ReplacePattern(source, target)); result.add(new ReplacePattern(source.toLowerCase(), target.toLowerCase())); result.add(new ReplacePattern(StringUtils.capitalize(source.toLowerCase()), StringUtils.capitalize(target.toLowerCase()))); result.add(new ReplacePattern(source.toUpperCase(), target.toUpperCase())); } return result; } /** * Returns directory name. * * @param directory directory * @return directory name */ private Path getDirectoryName(final Path directory) { final String sourcePath = source.toAbsolutePath().toString(); final String targetPath = target.toAbsolutePath().toString(); final String directoryPath = directory.toAbsolutePath().toString(); final String result = directoryPath.replace(sourcePath, targetPath); final String replacedResult = FileCopy.replaceText(result, replacePatterns); return Paths.get(replacedResult); } }
mit
mrkosterix/lua-commons
lua-commons-3-custom-level/src/main/java/org/lua/commons/customapi/javafunctions/handlers/TypeCastManager.java
653
package org.lua.commons.customapi.javafunctions.handlers; import org.lua.commons.baseapi.LuaThread; import org.lua.commons.baseapi.extensions.LuaExtension; import org.lua.commons.baseapi.types.LuaObject; import org.lua.commons.customapi.javafunctions.handlers.types.Type; public interface TypeCastManager extends LuaExtension { public void addHandler(Class<? extends TypeHandler> handler); public void add(Class<? extends TypeHandler> handler, Class<?>... keys); public void remove(Class<?> key); public Object castFrom(LuaThread thread, LuaObject obj, Type expected); public LuaObject castTo(LuaThread thread, Object obj); }
mit
Crystark/Orestes-Bloomfilter
src/main/java/orestes/bloomfilter/redis/helper/RedisPool.java
4691
package orestes.bloomfilter.redis.helper; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.exceptions.JedisConnectionException; import backport.java.util.function.Consumer; import backport.java.util.function.Function; /** * Encapsulates a Connection Pool and offers convenience methods for safe access through Java 8 Lambdas. */ public class RedisPool { private final JedisPool pool; private List<RedisPool> slavePools; private Random random; public RedisPool(JedisPool pool) { this.pool = pool; } public RedisPool(JedisPool pool, int redisConnections, Set<Entry<String, Integer>> readSlaves) { this(pool); if (readSlaves != null && !readSlaves.isEmpty()) { slavePools = new ArrayList<>(); random = new Random(); for (Entry<String, Integer> slave : readSlaves) { slavePools.add(new RedisPool(slave.getKey(), slave.getValue(), redisConnections)); } } } public RedisPool(String host, int port, int redisConnections) { this(createJedisPool(host, port, redisConnections)); } public RedisPool(String host, int port, int redisConnections, Set<Entry<String, Integer>> readSlaves) { this(createJedisPool(host, port, redisConnections), redisConnections, readSlaves); } private static JedisPool createJedisPool(String host, int port, int redisConnections) { JedisPoolConfig config = new JedisPoolConfig(); config.setBlockWhenExhausted(true); config.setMaxTotal(redisConnections); return new JedisPool(config, host, port); } public RedisPool allowingSlaves() { if(slavePools == null) return this; int index = random.nextInt(slavePools.size()); return slavePools.get(index); } public void safelyDo(final Consumer<Jedis> f) { safelyReturn(new Function<Jedis, Object>() { @Override public Object apply(Jedis jedis) { f.accept(jedis); return null; } }); } public <T> T safelyReturn(Function<Jedis, T> f) { T result; Jedis jedis = pool.getResource(); try { result = f.apply(jedis); return result; } catch (JedisConnectionException e) { if (jedis != null) { pool.returnBrokenResource(jedis); jedis = null; } throw e; } finally { if (jedis != null) pool.returnResource(jedis); } } @SuppressWarnings("unchecked") public <T> List<T> transactionallyDo(final Consumer<Pipeline> f, final String... watch) { return (List<T>) safelyReturn(new Function<Jedis, Object>() { @Override public Object apply(Jedis jedis) { Pipeline p = jedis.pipelined(); if (watch.length != 0) p.watch(watch); p.multi(); f.accept(p); Response<List<Object>> exec = p.exec(); p.sync(); return exec.get(); } }); } public <T> List<T> transactionallyRetry(Consumer<Pipeline> f, String... watch) { while(true) { List<T> result = transactionallyDo(f, watch); if(result != null) return result; } } public <T> T transactionallyDoAndReturn(final Function<Pipeline, T> f, final String... watch) { return safelyReturn(new Function<Jedis, T>() { @Override public T apply(Jedis jedis) { Pipeline p = jedis.pipelined(); if (watch.length != 0) p.watch(watch); p.multi(); T responses = f.apply(p); Response<List<Object>> exec = p.exec(); p.sync(); if(exec.get() == null) { return null; // failed } return responses; } }); } public <T> T transactionallyRetryAndReturn(Function<Pipeline, T> f, String... watch) { while(true) { T result = transactionallyDoAndReturn(f, watch); if(result != null) return result; } } public void destroy() { pool.destroy(); } }
mit
ScorpionJay/wechat
src/main/java/com/weixin/util/MessageUtil.java
1844
package com.weixin.util; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.thoughtworks.xstream.XStream; import com.weixin.vo.TextMessage; /** * @author : Jay */ public class MessageUtil { /** * xml 转为 map * @param request * @return * @throws IOException * @throws DocumentException */ public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException { Map<String, String> map = new HashMap<String, String>(); SAXReader reader = new SAXReader(); InputStream ins = request.getInputStream(); org.dom4j.Document doc = reader.read(ins); Element root = doc.getRootElement(); List<Element> list = root.elements(); for (Element e : list) { map.put(e.getName(), e.getText()); } ins.close(); return map; } /** * 将文本消息对象转为xml * @return */ public static String textMessageToXml(TextMessage textMessage){ XStream xstream = new XStream(); xstream.alias("xml", textMessage.getClass()); return xstream.toXML(textMessage); } /** * 初始化文本消 * @param toUserName * @param fromUserName * @param content * @return */ public static String initText(String toUserName, String fromUserName,String content){ TextMessage text = new TextMessage(); text.setFromUserName(toUserName); text.setToUserName(fromUserName); text.setMsgType("text"); text.setCreateTime(new Date().getTime()); text.setContent(content); return MessageUtil.textMessageToXml(text); } }
mit
Data2Semantics/mustard
mustard-experiments/src/main/java/org/data2semantics/mustard/rdfvault/RDFGraphListURIPrefixKernel.java
2327
package org.data2semantics.mustard.rdfvault; import java.util.List; import java.util.Set; import org.data2semantics.mustard.kernels.ComputationTimeTracker; import org.data2semantics.mustard.kernels.FeatureInspector; import org.data2semantics.mustard.kernels.KernelUtils; import org.data2semantics.mustard.kernels.data.RDFData; import org.data2semantics.mustard.kernels.data.SingleDTGraph; import org.data2semantics.mustard.kernels.graphkernels.FeatureVectorKernel; import org.data2semantics.mustard.kernels.graphkernels.GraphKernel; import org.data2semantics.mustard.kernels.graphkernels.singledtgraph.DTGraphGraphListWLSubTreeKernel; import org.data2semantics.mustard.kernels.SparseVector; import org.data2semantics.mustard.rdf.RDFDataSet; import org.data2semantics.mustard.rdf.RDFUtils; import org.openrdf.model.Resource; import org.openrdf.model.Statement; public class RDFGraphListURIPrefixKernel implements GraphKernel<RDFData>, FeatureVectorKernel<RDFData>, ComputationTimeTracker { private int depth; private boolean inference; private DTGraphGraphListURIPrefixKernel kernel; private SingleDTGraph graph; public RDFGraphListURIPrefixKernel(double lambda, int depth, boolean inference, boolean normalize) { super(); this.depth = depth; this.inference = inference; kernel = new DTGraphGraphListURIPrefixKernel(lambda, depth, normalize); } public String getLabel() { return KernelUtils.createLabel(this) + "_" + kernel.getLabel(); } public void setNormalize(boolean normalize) { kernel.setNormalize(normalize); } public SparseVector[] computeFeatureVectors(RDFData data) { init(data.getDataset(), data.getInstances(), data.getBlackList()); return kernel.computeFeatureVectors(graph); } public double[][] compute(RDFData data) { init(data.getDataset(), data.getInstances(), data.getBlackList()); return kernel.compute(graph); } private void init(RDFDataSet dataset, List<Resource> instances, List<Statement> blackList) { Set<Statement> stmts = RDFUtils.getStatements4Depth(dataset, instances, depth, inference); stmts.removeAll(blackList); graph = RDFUtils.statements2Graph(stmts, RDFUtils.REGULAR_LITERALS, instances, true); } public long getComputationTime() { return kernel.getComputationTime(); } }
mit
hzqjyyx/SphinxWebView
app/src/main/java/com/hzq/sphinxwebview/WebViewConfig.java
243
package com.hzq.sphinxwebview; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Build; import android.webkit.WebSettings; /** * Created by friencis on 2017/4/3 0003. */ public class WebViewConfig { }
mit
Col-E/Bytecode-Modification-Framework
src/main/java/me/coley/bmf/insn/impl/CALOAD.java
229
package me.coley.bmf.insn.impl; import me.coley.bmf.insn.Instruction; import me.coley.bmf.insn.OpType; public class CALOAD extends Instruction { public CALOAD() { super(OpType.ARRAY, Instruction.CALOAD, 1); } }
mit
MD4/EPSICalendar
app/src/main/java/epsi/md4/com/epsicalendar/activities/EventListActivity.java
5006
package epsi.md4.com.epsicalendar.activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.List; import epsi.md4.com.epsicalendar.Common; import epsi.md4.com.epsicalendar.R; import epsi.md4.com.epsicalendar.adapters.EventItemAdapter; import epsi.md4.com.epsicalendar.beans.Event; import epsi.md4.com.epsicalendar.ws.ApiClient; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class EventListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { public static final int EVENT_FORM_ACTIVITY_REQUEST_CODE = 1; public static final String TAG = EventListActivity.class.getName(); public static final String EXTRA_EVENT_ID = "EXTRA_EVENT_ID"; private ListView mList; private ApiClient mApiClient; private SharedPreferences mSharedPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Init view setContentView(R.layout.activity_event_list); // Init fields this.mList = (ListView) findViewById(R.id.event_list_view); this.mSharedPrefs = getSharedPreferences(Common.PREFS_SCOPE, Context.MODE_PRIVATE); mApiClient = new ApiClient(this); } /** * Refresh data */ private void refreshData() { mApiClient.listEvents().enqueue(new Callback<List<Event>>() { @Override public void onResponse(Response<List<Event>> response, Retrofit retrofit) { Log.v(TAG, String.format("listEvents.response: %d", response.code())); if (response.isSuccess()) { EventItemAdapter eventItemAdapter = new EventItemAdapter(EventListActivity.this, response.body()); mList.setOnItemClickListener(EventListActivity.this); mList.setAdapter(eventItemAdapter); } else { Log.e(TAG, "can't get events from api "); } } @Override public void onFailure(Throwable t) { Log.e(TAG, String.format("Error: %s", t.getMessage())); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == EventFormActivity.REQUEST_CODE) { if (resultCode == EventFormActivity.RESULT_OK) { Log.d(TAG, "new event, refreshing list"); refreshData(); } else if (resultCode == EventFormActivity.RESULT_CANCELED) { Log.d(TAG, "operation cancelled"); } } } public void onClickAddEvent(View view) { Intent intent = new Intent(EventListActivity.this, EventFormActivity.class); this.startActivityForResult(intent, EVENT_FORM_ACTIVITY_REQUEST_CODE); } @Override protected void onResume() { super.onResume(); Log.v(TAG, String.format("prefs.USER_EMAIL_KEY = %s", mSharedPrefs.getString(Common.USER_EMAIL_KEY, ""))); if (mSharedPrefs.getString(Common.USER_EMAIL_KEY, "").equals("")) { Intent intent = new Intent(this, UserFormActivity.class); startActivity(intent); } else { refreshData(); } } public void onClickDisconnect(View view) { mApiClient.logout().enqueue(new Callback<Void>() { @Override public void onResponse(Response<Void> response, Retrofit retrofit) { localDisconnect(); onResume(); } @Override public void onFailure(Throwable t) { Toast.makeText(EventListActivity.this, "Can not logout", Toast.LENGTH_SHORT).show(); Log.e(TAG, String.format("Error while logging out: %s", t.getLocalizedMessage())); } }); } private void localDisconnect() { Log.v(TAG, String.format("Clearing %s prefs", Common.PREFS_SCOPE)); SharedPreferences.Editor edit = this.mSharedPrefs.edit(); edit.clear(); edit.apply(); } /** * Listener for list item click * * @param parent * @param view * @param position * @param id */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Event clickedItem = (Event) parent.getItemAtPosition(position); Log.v(TAG, clickedItem.toString()); Intent intent = new Intent(this, EventItemActivity.class); intent.putExtra(EXTRA_EVENT_ID, clickedItem.getId().toString()); startActivity(intent); } }
mit
jaredlll08/ModTweaker
src/main/java/com/blamejared/compat/tcomplement/highoven/HighOven.java
11580
package com.blamejared.compat.tcomplement.highoven; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.blamejared.ModTweaker; import com.blamejared.compat.mantle.RecipeMatchIIngredient; import com.blamejared.compat.tcomplement.highoven.recipes.HeatRecipeTweaker; import com.blamejared.compat.tcomplement.highoven.recipes.HighOvenFuelTweaker; import com.blamejared.compat.tcomplement.highoven.recipes.MixRecipeTweaker; import com.blamejared.compat.tconstruct.recipes.MeltingRecipeTweaker; import com.blamejared.mtlib.helpers.InputHelper; import com.blamejared.mtlib.helpers.LogHelper; import com.blamejared.mtlib.utils.BaseAction; import crafttweaker.CraftTweakerAPI; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IIngredient; import crafttweaker.api.item.IItemStack; import crafttweaker.api.liquid.ILiquidStack; import crafttweaker.mc1120.item.MCItemStack; import knightminer.tcomplement.library.TCompRegistry; import knightminer.tcomplement.library.events.TCompRegisterEvent; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import stanhebben.zenscript.util.Pair; @ZenClass("mods.tcomplement.highoven.HighOven") @ZenRegister @ModOnly("tcomplement") public class HighOven { public static final List<IIngredient> REMOVED_FUELS = new LinkedList<>(); public static final Map<ILiquidStack, IItemStack> REMOVED_OVERRIDES = new LinkedHashMap<>(); public static final List<Pair<FluidStack, FluidStack>> REMOVED_HEAT_RECIPES = new LinkedList<>(); public static final List<Pair<FluidStack, FluidStack>> REMOVED_MIX_RECIPES = new LinkedList<>(); private static boolean init = false; private static void init() { if (!init) { MinecraftForge.EVENT_BUS.register(new HighOven()); init = true; } } /*-------------------------------------------------------------------------*\ | High Oven Fuels | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeFuel(IIngredient stack) { init(); CraftTweakerAPI.apply(new HighOven.RemoveFuel(stack)); } @ZenMethod public static void addFuel(IIngredient fuel, int burnTime, int tempRate) { init(); ModTweaker.LATE_ADDITIONS.add(new HighOven.AddFuel(fuel, burnTime, tempRate)); } private static class AddFuel extends BaseAction { private IIngredient fuel; private int time; private int rate; public AddFuel(IIngredient fuel, int time, int rate) { super("High Oven fuel"); this.fuel = fuel; this.time = time; this.rate = rate; } @Override public void apply() { TCompRegistry.registerFuel(new HighOvenFuelTweaker(new RecipeMatchIIngredient(fuel), time, rate)); } @Override public String describe() { return String.format("Adding %s as %s", this.getRecipeInfo(), this.name); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(fuel); } } private static class RemoveFuel extends BaseAction { private IIngredient fuel; public RemoveFuel(IIngredient fuel) { super("High Oven fuel"); this.fuel = fuel; }; @Override public void apply() { REMOVED_FUELS.add(fuel); } @Override public String describe() { return String.format("Removing %s as %s", this.getRecipeInfo(), this.name); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(fuel); } } /*-------------------------------------------------------------------------*\ | High Oven Melting | \*-------------------------------------------------------------------------*/ @ZenMethod public static void addMeltingOverride(ILiquidStack output, IIngredient input, @Optional int temp) { init(); ModTweaker.LATE_ADDITIONS .add(new HighOven.AddMelting(InputHelper.toFluid(output), input, (temp == 0 ? -1 : temp))); } @ZenMethod public static void removeMeltingOverride(ILiquidStack output, @Optional IItemStack input) { init(); CraftTweakerAPI.apply(new HighOven.RemoveMelting(output, input)); } private static class AddMelting extends BaseAction { private IIngredient input; private FluidStack output; private int temp; public AddMelting(FluidStack output, IIngredient input, int temp) { super("High Oven melting override"); this.input = input; this.output = output; this.temp = temp; } @Override public void apply() { if (temp > 0) { TCompRegistry.registerHighOvenOverride( new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output, temp)); } else { TCompRegistry.registerHighOvenOverride( new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output)); } } @Override public String describe() { return String.format("Adding %s for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(input) + ", now yields " + LogHelper.getStackDescription(output); } } private static class RemoveMelting extends BaseAction { private ILiquidStack output; private IItemStack input; public RemoveMelting(ILiquidStack output, IItemStack input) { super("High Oven melting override"); this.input = input; this.output = output; } @Override public void apply() { REMOVED_OVERRIDES.put(output, input); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output); } } /*-------------------------------------------------------------------------*\ | High Oven Heat | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeHeatRecipe(ILiquidStack output, @Optional ILiquidStack input) { init(); CraftTweakerAPI.apply(new RemoveHeat(input, output)); } @ZenMethod public static void addHeatRecipe(ILiquidStack output, ILiquidStack input, int temp) { init(); ModTweaker.LATE_ADDITIONS .add(new HighOven.AddHeat(InputHelper.toFluid(output), InputHelper.toFluid(input), temp)); } private static class AddHeat extends BaseAction { private FluidStack output, input; private int temp; public AddHeat(FluidStack output, FluidStack input, int temp) { super("High Oven Heat"); this.output = output; this.input = input; this.temp = temp; } @Override public void apply() { TCompRegistry.registerHeatRecipe(new HeatRecipeTweaker(input, output, temp)); } @Override public String describe() { return String.format("Adding %s Recipe for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output); } } private static class RemoveHeat extends BaseAction { private ILiquidStack input; private ILiquidStack output; public RemoveHeat(ILiquidStack input, ILiquidStack output) { super("High Oven Heat"); this.input = input; this.output = output; } @Override public void apply() { REMOVED_HEAT_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output))); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override public String getRecipeInfo() { return LogHelper.getStackDescription(output) + ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input))); } } /*-------------------------------------------------------------------------*\ | High Oven Mix | \*-------------------------------------------------------------------------*/ @ZenMethod public static void removeMixRecipe(ILiquidStack output, @Optional ILiquidStack input) { init(); CraftTweakerAPI.apply(new RemoveMix(output, input)); } @ZenMethod public static MixRecipeBuilder newMixRecipe(ILiquidStack output, ILiquidStack input, int temp) { init(); return new MixRecipeBuilder(output, input, temp); } @ZenMethod public static MixRecipeManager manageMixRecipe(ILiquidStack output, ILiquidStack input) { init(); return new MixRecipeManager(output, input); } private static class RemoveMix extends BaseAction { private ILiquidStack output; private ILiquidStack input; public RemoveMix(ILiquidStack output, ILiquidStack input) { super("High Oven Mix"); this.output = output; this.input = input; } @Override public void apply() { REMOVED_MIX_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output))); } @Override public String describe() { return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo()); } @Override protected String getRecipeInfo() { return LogHelper.getStackDescription(output) + ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input))); } } /*-------------------------------------------------------------------------*\ | Event handlers | \*-------------------------------------------------------------------------*/ @SubscribeEvent public void onHighOvenFuelRegister(TCompRegisterEvent.HighOvenFuelRegisterEvent event) { if (event.getRecipe() instanceof HighOvenFuelTweaker) { return; } for (IIngredient entry : REMOVED_FUELS) { for (ItemStack fuel : event.getRecipe().getFuels()) { if (entry.matches(new MCItemStack(fuel))) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenHeatRegister(TCompRegisterEvent.HighOvenHeatRegisterEvent event) { if (event.getRecipe() instanceof HeatRecipeTweaker) { return; } else { for (Pair<FluidStack, FluidStack> entry : REMOVED_HEAT_RECIPES) { if (event.getRecipe().matches(entry.getKey(), entry.getValue())) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenMixRegister(TCompRegisterEvent.HighOvenMixRegisterEvent event) { if (event.getRecipe() instanceof MixRecipeTweaker) { return; } else { for (Pair<FluidStack, FluidStack> entry : REMOVED_MIX_RECIPES) { if (event.getRecipe().matches(entry.getKey(), entry.getValue())) { event.setCanceled(true); return; } } } } @SubscribeEvent public void onHighOvenOverrideRegister(TCompRegisterEvent.HighOvenOverrideRegisterEvent event) { if (event.getRecipe() instanceof MeltingRecipeTweaker) { return; } for (Map.Entry<ILiquidStack, IItemStack> entry : REMOVED_OVERRIDES.entrySet()) { if (event.getRecipe().getResult().isFluidEqual(((FluidStack) entry.getKey().getInternal()))) { if (entry.getValue() != null) { if (event.getRecipe().input .matches(NonNullList.withSize(1, (ItemStack) entry.getValue().getInternal())).isPresent()) { event.setCanceled(true); } } else event.setCanceled(true); } } } }
mit
yegor256/cactoos
src/test/java/org/cactoos/io/SlowInputStream.java
2637
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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.cactoos.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * InputStream that returns content in small portions. * * @since 0.12 */ public final class SlowInputStream extends InputStream { /** * Original stream. */ private final InputStream origin; /** * Ctor. * @param size The size of the array to encapsulate */ public SlowInputStream(final int size) { this(new ByteArrayInputStream(new byte[size])); } /** * Ctor. * @param stream Original stream to encapsulate and make slower */ SlowInputStream(final InputStream stream) { super(); this.origin = stream; } @Override public int read() throws IOException { final byte[] buf = new byte[1]; final int result; if (this.read(buf) < 0) { result = -1; } else { result = Byte.toUnsignedInt(buf[0]); } return result; } @Override public int read(final byte[] buf, final int offset, final int len) throws IOException { final int result; if (len > 1) { result = this.origin.read(buf, offset, len - 1); } else { result = this.origin.read(buf, offset, len); } return result; } @Override public int read(final byte[] buf) throws IOException { return this.read(buf, 0, buf.length); } }
mit
vladimir-golovnin/otus-java-2017-04-golovnin
hw09/src/main/java/ru/otus/java_2017_04/golovnin/hw09/User.java
642
package ru.otus.java_2017_04.golovnin.hw09; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity(name = "user") @Table(name = "users") public class User extends DataSet{ @Column(name = "name") private String name; @Column(name = "age", nullable = false, length = 3) private int age; User(){ super(); name = ""; age = 0; } User(long id, String name, int age){ super(id); this.name = name; this.age = age; } String getName(){ return name; } int getAge() { return age; } }
mit
SkyTreasure/Airbnb-Android-Google-Map-View
app/src/main/java/com/purvotara/airbnbmapexample/model/AddressModel.java
5013
package com.purvotara.airbnbmapexample.model; import android.content.Context; import com.android.volley.Request; import com.google.gson.Gson; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.purvotara.airbnbmapexample.constants.NetworkConstants; import com.purvotara.airbnbmapexample.controller.BaseInterface; import com.purvotara.airbnbmapexample.network.BaseNetwork; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; /** * Created by skytreasure on 15/4/16. */ public class AddressModel extends BaseModel { @SerializedName("address_id") @Expose private Integer addressId; @SerializedName("mPincode") @Expose private String mPincode; @SerializedName("city") @Expose private String city; @SerializedName("line_1") @Expose private String line1; @SerializedName("line_2") @Expose private String line2; @SerializedName("longitude") @Expose private String longitude; @SerializedName("latitude") @Expose private String latitude; @SerializedName("address_type") @Expose private String addressType; @SerializedName("default") @Expose private Boolean _default; @SerializedName("image") @Expose private String image; @SerializedName("rating") @Expose private String rating; @SerializedName("distance") @Expose private String distance; /** * Constructor for the base model * * @param context the application mContext * @param baseInterface it is the instance of baseinterface, */ public AddressModel(Context context, BaseInterface baseInterface) { super(context, baseInterface); } public void fetchAddressFromServer() { BaseNetwork baseNetwork = new BaseNetwork(mContext, this); baseNetwork.getJSONObjectForRequest(Request.Method.GET, NetworkConstants.ADDRESS_URL, null, NetworkConstants.ADDRESS_REQUEST); } @Override public void parseAndNotifyResponse(JSONObject response, int requestType) throws JSONException { try { // boolean error = response.getBoolean(NetworkConstants.ERROR); Gson gson = new Gson(); switch (requestType) { case NetworkConstants.ADDRESS_REQUEST: JSONArray addressArray = response.getJSONArray(NetworkConstants.ADDRESS); List<AddressModel> addressList = gson.fromJson(addressArray.toString(), new TypeToken<List<AddressModel>>() { }.getType()); mBaseInterface.handleNetworkCall(addressList, requestType); break; } } catch (Exception e) { mBaseInterface.handleNetworkCall(e.getMessage(), requestType); } } @Override public HashMap<String, Object> getRequestBodyObject(int requestType) { return null; } @Override public HashMap<String, String> getRequestBodyString(int requestType) { return null; } public Integer getAddressId() { return addressId; } public void setAddressId(Integer addressId) { this.addressId = addressId; } public String getmPincode() { return mPincode; } public void setmPincode(String mPincode) { this.mPincode = mPincode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public Boolean get_default() { return _default; } public void set_default(Boolean _default) { this._default = _default; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } }
mit
CS319-G12/uMonopoly
src/models/factories/PropertyFactory.java
198
package models.factories; import models.squares.PropertySquare; import java.util.Set; /** * @author Ani Kristo */ interface PropertyFactory { Set<? extends PropertySquare> makeSquares(); }
mit
eroicaleo/DesignPatterns
HeadFirst/ch04/PizzaStoreAbstractFactory/EggPlant.java
85
/** * Created by yangge on 1/29/2016. */ public class EggPlant extends Veggies { }
mit
aerialls/Turtle
src/turtle/gui/panel/TeamBehaviorPanel.java
2309
/* * This file is part of the Turtle project * * (c) 2011 Julien Brochet <julien.brochet@etu.univ-lyon1.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package turtle.gui.panel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import turtle.behavior.team.TeamBehaviorInterface; import turtle.controller.Kernel; import turtle.entity.Team; import turtle.util.Log; /** * Représentation du panel permettant le changement du * comportement d'une équipe * * @author Julien Brochet <julien.brochet@etu.univ-lyon1.fr> * @since 1.0 */ public class TeamBehaviorPanel extends JPanel implements ActionListener { /** * L'équipe concernée */ protected Team mTeam; /** * Le contrôlleur */ protected Kernel mKernel; public TeamBehaviorPanel(Kernel kernel, Team team) { mTeam = team; mKernel = kernel; initialize(); } /** * Création de la fenêtre et de ses composants */ private void initialize() { Border paddingBorder = BorderFactory.createEmptyBorder(0,10,10,0); JLabel label = new JLabel("Comportement de l'équipe " + mTeam.getName()); label.setBorder(paddingBorder); JComboBox comboBox = new JComboBox(mTeam.getAvailableBehaviors().toArray()); comboBox.addActionListener(this); comboBox.setSelectedIndex(-1); setLayout(new BorderLayout()); add(label, BorderLayout.NORTH); add(comboBox, BorderLayout.SOUTH); } @Override public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); TeamBehaviorInterface behavior = (TeamBehaviorInterface) cb.getSelectedItem(); TeamBehaviorInterface oldBehavior = mTeam.getBehavior(); if (behavior != oldBehavior) { Log.i(String.format("Behavior change for Team %s (old=%s, new=%s)", mTeam.getName(), mTeam.getBehavior(), behavior)); mKernel.changeTeamBehavior(mTeam, behavior); } } }
mit
erikmr/Java-Api-Rest
src/main/java/platzi/app/InstructorRepository.java
250
package platzi.app; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; public interface InstructorRepository extends JpaRepository<Instructor, Long> { Optional<Instructor> findByUsername(String username); }
mit
longbai/happy-dns-android
library/src/main/java/com/qiniu/android/dns/http/DnspodFree.java
1751
package com.qiniu.android.dns.http; import com.qiniu.android.dns.Domain; import com.qiniu.android.dns.IResolver; import com.qiniu.android.dns.NetworkInfo; import com.qiniu.android.dns.Record; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by bailong on 15/6/12. */ public final class DnspodFree implements IResolver { @Override public Record[] query(Domain domain, NetworkInfo info) throws IOException { URL url = new URL("http://119.29.29.29/d?ttl=1&dn=" + domain.domain); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } int length = httpConn.getContentLength(); if (length > 1024 || length == 0) { return null; } InputStream is = httpConn.getInputStream(); byte[] data = new byte[length]; int read = is.read(data); is.close(); String response = new String(data, 0, read); String[] r1 = response.split(","); if (r1.length != 2) { return null; } int ttl; try { ttl = Integer.parseInt(r1[1]); } catch (Exception e) { return null; } String[] ips = r1[0].split(";"); if (ips.length == 0) { return null; } Record[] records = new Record[ips.length]; long time = System.currentTimeMillis() / 1000; for (int i = 0; i < ips.length; i++) { records[i] = new Record(ips[i], Record.TYPE_A, ttl, time); } return records; } }
mit
swaldman/ethereumj
ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java
10826
package test.ethereum.core; import test.ethereum.TestContext; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.BlockchainImpl; import org.ethereum.core.Genesis; import org.ethereum.facade.Blockchain; import org.ethereum.manager.WorldManager; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class BlockTest { private static final Logger logger = LoggerFactory.getLogger("test"); @Configuration @ComponentScan(basePackages = "org.ethereum") static class ContextConfiguration extends TestContext { } @Autowired WorldManager worldManager; // https://ethereum.etherpad.mozilla.org/12 private String PoC7_GENESIS_HEX_RLP_ENCODED = "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0"; private String PoC7_GENESIS_HEX_HASH = "c9cb614fddd89b3bc6e2f0ed1f8e58e8a0d826612a607a6151be6f39c991a941"; String block_2 = "f8b5f8b1a0cf4b25b08b39350304fe12a16e4216c01a426f8f3dbf0d392b5b45" + "8ffb6a399da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a1" + "42fd40d493479476f5eabe4b342ee56b8ceba6ab2a770c3e2198e7a08a22d58b" + "a5c65b2bf660a961b075a43f564374d38bfe6cc69823eea574d1d16e80833fe0" + "04028609184e72a000830f3aab80845387c60380a00000000000000000000000" + "0000000000000000000000000033172b6669131179c0c0"; String block_17 = "f9016df8d3a0aa142573b355c6f2e8306471c869b0d12d0638cea3f57d39991a" + "b1b03ffa40daa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40" + "d4934794e559de5527492bcb42ec68d07df0742a98ec3f1ea031c973c20e7a15c319a9ff" + "9b0aab5bdc121320767fee71fb2b771ce1c93cf812a01b224ec310c2bfb40fd0e6a668ee" + "7c06a5a4a4bfb99620d0fea8f7b43315dd59833f3130118609184e72a000830f01ec8201" + "f4845387f36980a00000000000000000000000000000000000000000000000000532c3ae" + "9b3503f6f895f893f86d018609184e72a0008201f494f625565ac58ec5dadfce1b8f9fb1" + "dd30db48613b8862cf5246d0c80000801ca05caa26abb350e0521a25b8df229806f3777d" + "9e262996493846a590c7011697dba07bb7680a256ede4034212b7a1ae6c7caea73190cb0" + "7dedb91a07b72f34074e76a00cd22d78d556175604407dc6109797f5c8d990d05f1b352e" + "10c71b3dd74bc70f8201f4c0"; String block_32 = "f8f8f8f4a00a312c2b0a8f125c60a3976b6e508e740e095eb59943988d9bbfb8" + "aa43922e31a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4" + "934794e559de5527492bcb42ec68d07df0742a98ec3f1ea050188ab86bdf164ac90eb283" + "5a04a8930aae5393c3a2ef1166fb95028f9456b88080b840000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000833ee248208609184e72a000830eca0080845387" + "fd2080a00000000000000000000000000000000000000000000000001f52ebb192c4ea97" + "c0c0"; @After public void doReset() { worldManager.reset(); } @Test /* got from go guy */ public void testGenesisFromRLP() { // from RLP encoding byte[] genesisBytes = Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED); Block genesisFromRLP = new Block(genesisBytes); Block genesis = Genesis.getInstance(); assertEquals(Hex.toHexString(genesis.getHash()), Hex.toHexString(genesisFromRLP.getHash())); assertEquals(Hex.toHexString(genesis.getParentHash()), Hex.toHexString(genesisFromRLP.getParentHash())); assertEquals(Hex.toHexString(genesis.getStateRoot()), Hex.toHexString(genesisFromRLP.getStateRoot())); } @Test public void testGenesisFromNew() { Block genesis = Genesis.getInstance(); logger.info(genesis.toString()); logger.info("genesis hash: [{}]", Hex.toHexString(genesis.getHash())); logger.info("genesis rlp: [{}]", Hex.toHexString(genesis.getEncoded())); assertEquals(PoC7_GENESIS_HEX_HASH, Hex.toHexString(genesis.getHash())); assertEquals(PoC7_GENESIS_HEX_RLP_ENCODED, Hex.toHexString(genesis.getEncoded())); } @Test /* block without transactions - block#32 in PoC5 cpp-chain */ public void testEmptyBlock() { byte[] payload = Hex.decode(block_32); Block blockData = new Block(payload); logger.info(blockData.toString()); } @Test /* block with single balance transfer transaction - block#17 in PoC5 cpp-chain */ @Ignore public void testSingleBalanceTransfer() { byte[] payload = Hex.decode(block_17); // todo: find out an uptodate block wire Block blockData = new Block(payload); logger.info(blockData.toString()); } @Test /* large block with 5 transactions -block#1 in PoC5 cpp-chain */ public void testBlockWithContractCreation() { byte[] payload = Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED); Block block = new Block(payload); logger.info(block.toString()); } @Test public void testCalcDifficulty() { Blockchain blockchain = worldManager.getBlockchain(); Block genesis = Genesis.getInstance(); BigInteger difficulty = new BigInteger(1, genesis.calcDifficulty()); logger.info("Genesis difficulty: [{}]", difficulty.toString()); assertEquals(new BigInteger(1, Genesis.DIFFICULTY), difficulty); // Storing genesis because the parent needs to be in the DB for calculation. blockchain.add(genesis); Block block1 = new Block(Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED)); BigInteger calcDifficulty = new BigInteger(1, block1.calcDifficulty()); BigInteger actualDifficulty = new BigInteger(1, block1.getDifficulty()); logger.info("Block#1 actual difficulty: [{}] ", actualDifficulty.toString()); logger.info("Block#1 calculated difficulty: [{}] ", calcDifficulty.toString()); assertEquals(actualDifficulty, calcDifficulty); } @Test public void testCalcGasLimit() { BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); Block genesis = Genesis.getInstance(); long gasLimit = blockchain.calcGasLimit(genesis.getHeader()); logger.info("Genesis gasLimit: [{}] ", gasLimit); assertEquals(Genesis.GAS_LIMIT, gasLimit); // Test with block Block block1 = new Block(Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED)); long calcGasLimit = blockchain.calcGasLimit(block1.getHeader()); long actualGasLimit = block1.getGasLimit(); blockchain.tryToConnect(block1); logger.info("Block#1 actual gasLimit [{}] ", actualGasLimit); logger.info("Block#1 calculated gasLimit [{}] ", calcGasLimit); assertEquals(actualGasLimit, calcGasLimit); } @Ignore @Test public void testScenario1() throws URISyntaxException, IOException { BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); URL scenario1 = ClassLoader .getSystemResource("blockload/scenario1.dmp"); File file = new File(scenario1.toURI()); List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); byte[] root = Genesis.getInstance().getStateRoot(); for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); root = block.getStateRoot(); } logger.info("asserting root state is: {}", Hex.toHexString(root)); //expected root: fb8be59e6420892916e3967c60adfdf48836af040db0072ca411d7aaf5663804 assertEquals(Hex.toHexString(root), Hex.toHexString(worldManager.getRepository().getRoot())); } @Ignore @Test public void testScenario2() throws URISyntaxException, IOException { BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); URL scenario1 = ClassLoader .getSystemResource("blockload/scenario2.dmp"); File file = new File(scenario1.toURI()); List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); byte[] root = Genesis.getInstance().getStateRoot(); for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); root = block.getStateRoot(); } logger.info("asserting root state is: {}", Hex.toHexString(root)); //expected root: a5e2a18bdbc4ab97775f44852382ff5585b948ccb15b1d69f0abb71e2d8f727d assertEquals(Hex.toHexString(root), Hex.toHexString(worldManager.getRepository().getRoot())); } @Test @Ignore public void testUncleValidGenerationGap() { // TODO fail("Not yet implemented"); } @Test @Ignore public void testUncleInvalidGenerationGap() { // TODO fail("Not yet implemented"); } @Test @Ignore public void testUncleInvalidParentGenerationGap() { // TODO fail("Not yet implemented"); } }
mit
DobrinAlexandru/Wabbit-Messenger---android-client
Wabbit/src/com/wabbit/libraries/Installation.java
1373
package com.wabbit.libraries; import android.content.Context; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.UUID; public class Installation { private static String sID = null; private static final String INSTALLATION = "INSTALLATION"; public synchronized static String id(Context context) { if (sID == null) { File installation = new File(context.getFilesDir(), INSTALLATION); try { if (!installation.exists()) writeInstallationFile(installation); sID = readInstallationFile(installation); } catch (Exception e) { throw new RuntimeException(e); } } return sID; } private static String readInstallationFile(File installation) throws IOException { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes); } private static void writeInstallationFile(File installation) throws IOException { FileOutputStream out = new FileOutputStream(installation); String id = UUID.randomUUID().toString(); out.write(id.getBytes()); out.close(); } }
mit
mrswoop/BubbleSort2DArrayRange
BubbleSort2D/src/BubbleSort2D/person.java
253
package BubbleSort2D; public class person { String name; int age; boolean sortme = false; public person(String n, int a) { name = n; age = a; } public String toString(){ return name + " " + Integer.toString(age); } }
mit
mmonkey/Automator
src/main/java/com/github/mmonkey/Automator/Migrations/MigrationRunner.java
701
package com.github.mmonkey.Automator.Migrations; import com.github.mmonkey.Automator.Automator; public abstract class MigrationRunner { protected Automator plugin; protected int version; protected int latest = 0; public void run() { while (this.version != this.latest) { MigrationInterface migration = this.getMigration(this.version); if (migration != null) { migration.up(); this.version++; } } } abstract MigrationInterface getMigration(int version); public MigrationRunner(Automator plugin, int version) { this.plugin = plugin; this.version = version; } }
mit
asposemarketplace/Aspose-Words-Java
src/loadingandsaving/loadingandsavinghtml/splitintohtmlpages/java/Topic.java
791
/* * Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved. * * This file is part of Aspose.Words. The source code in this file * is only intended as a supplement to the documentation, and is provided * "as is", without warranty of any kind, either expressed or implied. */ package loadingandsaving.loadingandsavinghtml.splitintohtmlpages.java; /** * A simple class to hold a topic title and HTML file name together. */ class Topic { Topic(String title, String fileName) throws Exception { mTitle = title; mFileName = fileName; } String getTitle() throws Exception { return mTitle; } String getFileName() throws Exception { return mFileName; } private final String mTitle; private final String mFileName; }
mit
archimatetool/archi
org.opengroup.archimate.xmlexchange/src/org/opengroup/archimate/xmlexchange/XMLModelParserException.java
597
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package org.opengroup.archimate.xmlexchange; /** * XML Exception * * @author Phillip Beauvoir */ public class XMLModelParserException extends Exception { public XMLModelParserException() { super(Messages.XMLModelParserException_0); } public XMLModelParserException(String message) { super(message); } public XMLModelParserException(String message, Throwable cause) { super(message, cause); } }
mit
MKA-Nigeria/MKAN-Report-Android
mkan_report_app/src/main/java/com/aliumujib/majlis/mkan_report_app/addnew/fragments/SihateJismaniPart2.java
1164
package com.aliumujib.majlis.mkan_report_app.addnew.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.aliumujib.majlis.mkan_report_app.R; import com.stepstone.stepper.VerificationError; public class SihateJismaniPart2 extends BaseReportFragment { public static SihateJismaniPart2 newInstance() { SihateJismaniPart2 fragment = new SihateJismaniPart2(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_sihate_jismani_part2, container, false); } @Override public VerificationError verifyStep() { return null; } @Override public void onSelected() { } }
mit
jjhesk/slideSelectionList
SmartSelectionList/hbsdk/src/main/java/com/hypebeast/sdk/api/model/hypebeaststore/ReponseNormal.java
438
package com.hypebeast.sdk.api.model.hypebeaststore; import com.google.gson.annotations.SerializedName; import com.hypebeast.sdk.api.model.Alternative; import com.hypebeast.sdk.api.model.symfony.taxonomy; /** * Created by hesk on 7/1/2015. */ public class ReponseNormal extends Alternative { @SerializedName("products") public ResponseProductList product_list; @SerializedName("taxon") public taxonomy taxon_result; }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java
875
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.containerservice.generated; import com.azure.core.util.Context; /** Samples for ManagedClusters List. */ public final class ManagedClustersListSamples { /* * x-ms-original-file: specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2022-01-01/examples/ManagedClustersList.json */ /** * Sample code: List Managed Clusters. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void listManagedClusters(com.azure.resourcemanager.AzureResourceManager azure) { azure.kubernetesClusters().manager().serviceClient().getManagedClusters().list(Context.NONE); } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ProximityPlacementGroupListResult.java
2679
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.compute.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.compute.fluent.models.ProximityPlacementGroupInner; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** The List Proximity Placement Group operation response. */ @Fluent public final class ProximityPlacementGroupListResult { /* * The list of proximity placement groups */ @JsonProperty(value = "value", required = true) private List<ProximityPlacementGroupInner> value; /* * The URI to fetch the next page of proximity placement groups. */ @JsonProperty(value = "nextLink") private String nextLink; /** * Get the value property: The list of proximity placement groups. * * @return the value value. */ public List<ProximityPlacementGroupInner> value() { return this.value; } /** * Set the value property: The list of proximity placement groups. * * @param value the value value to set. * @return the ProximityPlacementGroupListResult object itself. */ public ProximityPlacementGroupListResult withValue(List<ProximityPlacementGroupInner> value) { this.value = value; return this; } /** * Get the nextLink property: The URI to fetch the next page of proximity placement groups. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Set the nextLink property: The URI to fetch the next page of proximity placement groups. * * @param nextLink the nextLink value to set. * @return the ProximityPlacementGroupListResult object itself. */ public ProximityPlacementGroupListResult withNextLink(String nextLink) { this.nextLink = nextLink; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException( "Missing required property value in model ProximityPlacementGroupListResult")); } else { value().forEach(e -> e.validate()); } } private static final ClientLogger LOGGER = new ClientLogger(ProximityPlacementGroupListResult.class); }
mit
jonesd/st2x
src/main/java/info/dgjones/st2x/transform/method/intra/TransformCreateCall.java
2846
/** * The MIT License * Copyright (c) 2003 David G Jones * * 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 info.dgjones.st2x.transform.method.intra; import java.util.List; import info.dgjones.st2x.ClassParser; import info.dgjones.st2x.JavaMethod; import info.dgjones.st2x.javatoken.JavaCallStart; import info.dgjones.st2x.javatoken.JavaIdentifier; import info.dgjones.st2x.javatoken.JavaKeyword; import info.dgjones.st2x.javatoken.JavaToken; import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation; import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher; import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory; public class TransformCreateCall extends AbstractMethodBodyTransformation { public TransformCreateCall() { super(); } public TransformCreateCall(TokenMatcherFactory factory) { super(factory); } protected TokenMatcher matchers(TokenMatcherFactory factory) { return factory.token(JavaCallStart.class, "create.*"); } protected int transform(JavaMethod javaMethod, List tokens, int i) { JavaCallStart call = (JavaCallStart)tokens.get(i); if (ClassParser.NON_CONSTRUCTORS.contains(call.value)) { return i; } if (i > 0 && (tokens.get(i - 1) instanceof JavaIdentifier)) { JavaToken token = (JavaToken) tokens.get(i - 1); if (token.value.equals("super")) { return i; } else if (token.value.equals(javaMethod.javaClass.className) && javaMethod.isConstructor()) { call.value = "this"; tokens.remove(i-1); return i-1; } call.value = token.value; tokens.remove(i - 1); tokens.add(i - 1, new JavaKeyword("new")); } else if (javaMethod.isConstructor()) { call.value = "this"; } else { call.value = javaMethod.javaClass.className; tokens.add(i, new JavaKeyword("new")); } return i; } }
mit
LeeCIT/FallApp
FallApp/src/ie/lc/fallApp/ActivityFallHeight.java
5073
package ie.lc.fallApp; import java.text.DecimalFormat; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.text.Editable; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class ActivityFallHeight extends Activity { private double persistentRandomNumber; private static final String persistentRandomNumberKey = "prn"; private final int planetRequestCode = 1337; private final Interlock fieldInterlock = new Interlock(); protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_fall ); setupActions(); persistentRandomNumber = Math.random() * 10.0; } protected void onSaveInstanceState( Bundle out ) { out.putDouble( persistentRandomNumberKey, persistentRandomNumber ); showToastMessage( "Saved instance variable: " + persistentRandomNumber ); } protected void onRestoreInstanceState( Bundle in ) { persistentRandomNumber = in.getDouble( persistentRandomNumberKey ); showToastMessage( "Restored instance variable: " + persistentRandomNumber ); } protected void onActivityResult( int requestCode, int resultCode, Intent data ) { if (requestCode == planetRequestCode && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Planet selectedPlanet = (Planet) extras.getSerializable( Common.planetSelectIdentifier ); Planet activePlanet = Physics.getActivePlanet(); if ( ! selectedPlanet.equals(activePlanet)) { Physics.setActivePlanet( selectedPlanet ); showToastMessage( getString(R.string.planetChanged) + " " + selectedPlanet + "." ); updateDisplayedHeightFromVelocity(); } } } public boolean onCreateOptionsMenu( Menu menu ) { getMenuInflater().inflate( R.menu.fall_height, menu ); return true; } /** Used by computeAndShow */ private interface ComputeCallback { double execute( String textInput ) throws NumberFormatException; } private void computeAndShow( EditText targetField, String textInput, ComputeCallback comp ) { if ( ! fieldInterlock.isLocked()) { fieldInterlock.setLocked( true ); String textOutput = ""; try { double num = comp.execute( textInput ); textOutput = formatTwoDecimalPlaces( num ); } catch (Exception ex) { // Ducked } targetField.setText( textOutput ); fieldInterlock.setLocked( false ); } } private void setupActions() { final EditText velocityField = (EditText) findViewById( R.id.velocityField ); final EditText heightField = (EditText) findViewById( R.id.heightField ); final Button optionsButton = (Button) findViewById( R.id.optionsButton ); final Button showBigButton = (Button) findViewById( R.id.showBigButton ); velocityField.addTextChangedListener( new TextWatcherAdapter() { public void afterTextChanged( Editable e ) { computeAndShow( heightField, e.toString(), new ComputeCallback() { public double execute( String textInput ) throws NumberFormatException { double vKmh = Double.parseDouble( textInput ); double vMps = Physics.kilometresPerHourToMetresPerSec( vKmh ); return Physics.computeEquivalentFallHeight( vMps ); } }); } }); heightField.addTextChangedListener( new TextWatcherAdapter() { public void afterTextChanged( Editable e ) { computeAndShow( velocityField, e.toString(), new ComputeCallback() { public double execute( String textInput ) throws NumberFormatException { double height = Double.parseDouble( textInput ); double vMps = Physics.computeEquivalentVelocity( height ); return Physics.metresPerSecToKilometresPerHour( vMps ); } }); } }); optionsButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Intent intent = new Intent( ActivityFallHeight.this, ActivityOptions.class ); intent.putExtra( Common.planetSelectIdentifier, Physics.getActivePlanet() ); startActivityForResult( intent, planetRequestCode ); } }); showBigButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Intent intent = new Intent( ActivityFallHeight.this, ActivityDisplay.class ); intent.putExtra( Common.displayHeightIdentifier, heightField.getText().toString() ); startActivity( intent ); } }); } private void updateDisplayedHeightFromVelocity() { final EditText velocityField = (EditText) findViewById( R.id.velocityField ); velocityField.setText( velocityField.getText() ); // Triggers event. } private static String formatTwoDecimalPlaces( double num ) { DecimalFormat f = new DecimalFormat( "0.00" ); return f.format( num ); } private void showToastMessage( String str ) { Toast.makeText( this, str, Toast.LENGTH_SHORT ).show(); } }
mit
maximusvladimir/randomfinder
src/com/maximusvladimir/randomfinder/Test.java
3649
package com.maximusvladimir.randomfinder; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JProgressBar; import javax.swing.Timer; import javax.swing.JTextPane; import java.awt.Font; public class Test extends JFrame { private JTextField textField; private Searcher scanner; private JTextPane txtpncodeWillGenerate; public static void main(String[] args) { new Test(); } public Test() { setVisible(true); setSize(324,270); setTitle("Test"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(null); scanner = new Searcher(); JLabel lblEnterStringTo = new JLabel("Enter string to find:"); lblEnterStringTo.setBounds(10, 11, 136, 14); getContentPane().add(lblEnterStringTo); textField = new JTextField(); textField.setBounds(10, 30, 189, 20); getContentPane().add(textField); textField.setColumns(10); final JButton btnGo = new JButton("Go!"); btnGo.setBounds(209, 29, 89, 23); getContentPane().add(btnGo); final JProgressBar progressBar = new JProgressBar(); progressBar.setBounds(10, 90, 288, 20); getContentPane().add(progressBar); JLabel lblMaximumTimeRemaining = new JLabel("Maximum time remaining:"); lblMaximumTimeRemaining.setBounds(10, 61, 178, 14); getContentPane().add(lblMaximumTimeRemaining); final JLabel lblResult = new JLabel("Result:"); lblResult.setBounds(10, 121, 189, 14); getContentPane().add(lblResult); txtpncodeWillGenerate = new JTextPane(); txtpncodeWillGenerate.setFont(new Font("Courier New", Font.PLAIN, 10)); txtpncodeWillGenerate.setText("(Code will generate here)"); txtpncodeWillGenerate.setBounds(10, 141, 298, 90); getContentPane().add(txtpncodeWillGenerate); btnGo.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { if (btnGo.getText().equals("Go!")) { btnGo.setText("Halt"); lblResult.setText("Result:"); try { scanner.setString(textField.getText()); } catch (Throwable t) { JOptionPane.showMessageDialog(Test.this, t.getMessage()); } scanner.startAsync(); Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } else { Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); btnGo.setText("Go!"); scanner.halt(); } } }); new Timer(250,new ActionListener() { public void actionPerformed(ActionEvent arg0) { progressBar.setValue((int)(100 * scanner.getProgress())); if (scanner.isFinished()) { Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if (scanner.getResultSeed() == Integer.MIN_VALUE) lblResult.setText("Result: Not found."); else { lblResult.setText("Result: " + scanner.getResultSeed()); genCode(); } btnGo.setText("Go!"); } } }).start(); repaint(); } private void genCode() { String pieces = ""; for (int i = 0; i < scanner.getString().length(); i++) { pieces += "((char)(rand.nextInt(96)+32)) + \"\""; pieces += " +"; } if (scanner.getString().length() >= 1) pieces = pieces.substring(0,pieces.length()-2); txtpncodeWillGenerate.setText("Random rand = new Random("+scanner.getResultSeed()+");\n"+ "System.out.println(" + pieces + ");\n"+ "// Outputs " + scanner.getString()); } }
mit
rjwut/ian
src/test/java/com/walkertribe/ian/protocol/core/weap/SetBeamFreqPacketTest.java
906
package com.walkertribe.ian.protocol.core.weap; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.walkertribe.ian.enums.BeamFrequency; import com.walkertribe.ian.enums.Origin; import com.walkertribe.ian.protocol.AbstractPacketTester; public class SetBeamFreqPacketTest extends AbstractPacketTester<SetBeamFreqPacket> { @Test public void test() { execute("core/weap/SetBeamFreqPacket.txt", Origin.CLIENT, 1); } @Test public void testConstruct() { test(new SetBeamFreqPacket(BeamFrequency.B)); } @Test(expected = IllegalArgumentException.class) public void testConstructNullBeamFrequency() { new SetBeamFreqPacket((BeamFrequency) null); } @Override protected void testPackets(List<SetBeamFreqPacket> packets) { test(packets.get(0)); } private void test(SetBeamFreqPacket pkt) { Assert.assertEquals(BeamFrequency.B, pkt.getBeamFrequency()); } }
mit
Beta-nanos/SolidDomino
SolidDomino/src/soliddomino/game/exceptions/IncorrectMoveFormatException.java
289
package soliddomino.game.exceptions; public class IncorrectMoveFormatException extends Exception { public IncorrectMoveFormatException(String format) { super(format + " is not the correct format. Expected \'#number-direction(e.g left, right).\'\nExample: 4-right"); } }
mit
brentnash/gbecho
src/main/java/com/giantbomb/main/ListOfGamesGenerator.java
137
package com.giantbomb.main; public class ListOfGamesGenerator { public static void main(final String[] args) { } }
mit
GluuFederation/oxAuth
Server/src/main/java/org/gluu/oxauth/util/RedirectUtil.java
2806
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.util; import org.gluu.oxauth.model.common.ResponseMode; import org.jboss.resteasy.specimpl.ResponseBuilderImpl; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import java.net.MalformedURLException; import java.net.URI; import static org.gluu.oxauth.client.AuthorizationRequest.NO_REDIRECT_HEADER; /** * @version October 7, 2019 */ public class RedirectUtil { private final static Logger log = LoggerFactory.getLogger(RedirectUtil.class); static String JSON_REDIRECT_PROPNAME = "redirect"; static int HTTP_REDIRECT = 302; public static ResponseBuilder getRedirectResponseBuilder(RedirectUri redirectUriResponse, HttpServletRequest httpRequest) { ResponseBuilder builder; if (httpRequest != null && httpRequest.getHeader(NO_REDIRECT_HEADER) != null) { try { URI redirectURI = URI.create(redirectUriResponse.toString()); JSONObject jsonObject = new JSONObject(); jsonObject.put(JSON_REDIRECT_PROPNAME, redirectURI.toURL()); String jsonResp = jsonObject.toString(); jsonResp = jsonResp.replace("\\/", "/"); builder = Response.ok( new GenericEntity<String>(jsonResp, String.class), MediaType.APPLICATION_JSON_TYPE ); } catch (MalformedURLException e) { builder = Response.serverError(); log.debug(e.getMessage(), e); } catch (JSONException e) { builder = Response.serverError(); log.debug(e.getMessage(), e); } } else if (redirectUriResponse.getResponseMode() != ResponseMode.FORM_POST) { URI redirectURI = URI.create(redirectUriResponse.toString()); builder = new ResponseBuilderImpl(); builder = Response.status(HTTP_REDIRECT); builder.location(redirectURI); } else { builder = new ResponseBuilderImpl(); builder.status(Response.Status.OK); builder.type(MediaType.TEXT_HTML_TYPE); builder.cacheControl(CacheControl.valueOf("no-cache, no-store")); builder.header("Pragma", "no-cache"); builder.entity(redirectUriResponse.toString()); } return builder; } }
mit
nendhruv/data-dictionary
src/java/filediff/myers/DifferentiationFailedException.java
294
package filediff.myers; public class DifferentiationFailedException extends DiffException { private static final long serialVersionUID = 1L; public DifferentiationFailedException() { } public DifferentiationFailedException(String msg) { super(msg); } }
mit
zasadnyy/android-hothack-13
example/source/src/main/java/ua/org/gdg/devfest/iosched/receiver/SessionAlarmReceiver.java
1444
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ua.org.gdg.devfest.iosched.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import ua.org.gdg.devfest.iosched.service.SessionAlarmService; import static ua.org.gdg.devfest.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
mit
ronggenliu/DesignPattern
src/me/ronggenliu/dp/creation/builder/Product.java
544
package me.ronggenliu.dp.creation.builder; /** * Created by garliu on 2017/5/29. */ public class Product { private String partA; private String partB; private String partC; public String getPartA() { return partA; } public void setPartA(String partA) { this.partA = partA; } public String getPartB() { return partB; } public void setPartB(String partB) { this.partB = partB; } public String getPartC() { return partC; } public void setPartC(String partC) { this.partC = partC; } }
mit
AndrewBell/boredgames-mongo
src/main/java/com/recursivechaos/boredgames/domain/Game.java
888
package com.recursivechaos.boredgames.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.data.annotation.Id; /** * Created by Andrew Bell 5/28/2015 * www.recursivechaos.com * andrew@recursivechaos.com * Licensed under MIT License 2015. See license.txt for details. */ public class Game { @Id @JsonIgnore private String id; private String title; private String description; public Game() { } public Game(String id) { this.id = id; } public String getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
mit
bobbrady/tpteam
tpbridge/src/edu/harvard/fas/rbrady/tpteam/tpbridge/hibernate/TestType.java
1142
package edu.harvard.fas.rbrady.tpteam.tpbridge.hibernate; // Generated Nov 10, 2006 5:22:58 PM by Hibernate Tools 3.2.0.beta8 import java.util.HashSet; import java.util.Set; /** * TestType generated by hbm2java */ public class TestType implements java.io.Serializable { // Fields private static final long serialVersionUID = 1L; private int id; private String name; private Set<Test> tests = new HashSet<Test>(0); // Constructors /** default constructor */ public TestType() { } /** minimal constructor */ public TestType(int id) { this.id = id; } /** full constructor */ public TestType(int id, String name, Set<Test> tests) { this.id = id; this.name = name; this.tests = tests; } // Property accessors public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<Test> getTests() { return this.tests; } public void setTests(Set<Test> tests) { this.tests = tests; } }
mit
johannv/javaTestEasy
src/domain/Mark.java
497
package domain; import java.util.Date; /** * @author Verbroucht Johann * Test Java Date : 15 aožt. 2011 */ public class Mark { private Date date; private int mark; public Mark(Date _date, int _mark) { this.date = _date; this.mark = _mark; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } }
mit
gazbert/BX-bot
bxbot-exchanges/src/test/java/com/gazbert/bxbot/exchanges/trading/api/impl/TestOpenOrderImpl.java
5233
/* * The MIT License (MIT) * * Copyright (c) 2015 Gareth Jon Lynch * * 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 com.gazbert.bxbot.exchanges.trading.api.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import com.gazbert.bxbot.trading.api.OrderType; import java.math.BigDecimal; import java.util.Date; import org.junit.Test; /** * Tests the Open Order impl behaves as expected. * * @author gazbert */ public class TestOpenOrderImpl { private static final String ID = "abc_123_def_456_ghi_789"; private static final Date CREATION_DATE = new Date(); private static final String MARKET_ID = "BTC_USD"; private static final BigDecimal PRICE = new BigDecimal("671.91"); private static final BigDecimal ORIGINAL_QUANTITY = new BigDecimal("0.01433434"); private static final BigDecimal TOTAL = PRICE.multiply(ORIGINAL_QUANTITY); private static final BigDecimal QUANTITY = ORIGINAL_QUANTITY.subtract(new BigDecimal("0.00112112")); @Test public void testOpenOrderIsInitialisedAsExpected() { final OpenOrderImpl openOrder = new OpenOrderImpl( ID, CREATION_DATE, MARKET_ID, OrderType.SELL, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL); assertEquals(ID, openOrder.getId()); assertEquals(CREATION_DATE, openOrder.getCreationDate()); assertEquals(MARKET_ID, openOrder.getMarketId()); assertEquals(OrderType.SELL, openOrder.getType()); assertEquals(PRICE, openOrder.getPrice()); assertEquals(QUANTITY, openOrder.getQuantity()); assertEquals(ORIGINAL_QUANTITY, openOrder.getOriginalQuantity()); assertEquals(TOTAL, openOrder.getTotal()); } @Test public void testSettersWorkAsExpected() { final OpenOrderImpl openOrder = new OpenOrderImpl(null, null, null, null, null, null, null, null); assertNull(openOrder.getId()); assertNull(openOrder.getCreationDate()); assertNull(openOrder.getMarketId()); assertNull(openOrder.getType()); assertNull(openOrder.getPrice()); assertNull(openOrder.getQuantity()); assertNull(openOrder.getOriginalQuantity()); assertNull(openOrder.getTotal()); openOrder.setId(ID); assertEquals(ID, openOrder.getId()); openOrder.setCreationDate(CREATION_DATE); assertEquals(CREATION_DATE, openOrder.getCreationDate()); openOrder.setMarketId(MARKET_ID); assertEquals(MARKET_ID, openOrder.getMarketId()); openOrder.setType(OrderType.BUY); assertEquals(OrderType.BUY, openOrder.getType()); openOrder.setPrice(PRICE); assertEquals(PRICE, openOrder.getPrice()); openOrder.setQuantity(QUANTITY); assertEquals(QUANTITY, openOrder.getQuantity()); openOrder.setOriginalQuantity(ORIGINAL_QUANTITY); assertEquals(ORIGINAL_QUANTITY, openOrder.getOriginalQuantity()); openOrder.setTotal(TOTAL); assertEquals(TOTAL, openOrder.getTotal()); } @Test public void testEqualsWorksAsExpected() { final OpenOrderImpl openOrder1 = new OpenOrderImpl( ID, CREATION_DATE, MARKET_ID, OrderType.SELL, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL); final OpenOrderImpl openOrder2 = new OpenOrderImpl( "different-id", CREATION_DATE, MARKET_ID, OrderType.SELL, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL); final OpenOrderImpl openOrder3 = new OpenOrderImpl( ID, CREATION_DATE, "diff-market", OrderType.SELL, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL); final OpenOrderImpl openOrder4 = new OpenOrderImpl( ID, CREATION_DATE, MARKET_ID, OrderType.BUY, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL); assertEquals(openOrder1, openOrder1); assertNotEquals(openOrder1, openOrder2); assertNotEquals(openOrder1, openOrder3); assertNotEquals(openOrder1, openOrder4); } }
mit
wawaeasybuy/jobandroid
Job/app/src/main/java/com/mardin/job/widgets/wizard/ui/SingleChoiceFragment.java
4068
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mardin.job.widgets.wizard.ui; import com.mardin.job.R; import com.mardin.job.widgets.wizard.model.Page; import com.mardin.job.widgets.wizard.model.SingleFixedChoicePage; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class SingleChoiceFragment extends ListFragment { private static final String ARG_KEY = "key"; private PageFragmentCallbacks mCallbacks; private List<String> mChoices; private String mKey; private Page mPage; public static SingleChoiceFragment create(String key) { Bundle args = new Bundle(); args.putString(ARG_KEY, key); SingleChoiceFragment fragment = new SingleChoiceFragment(); fragment.setArguments(args); return fragment; } public SingleChoiceFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mKey = args.getString(ARG_KEY); mPage = mCallbacks.onGetPage(mKey); SingleFixedChoicePage fixedChoicePage = (SingleFixedChoicePage) mPage; mChoices = new ArrayList<String>(); for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) { mChoices.add(fixedChoicePage.getOptionAt(i)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_page, container, false); ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle()); final ListView listView = (ListView) rootView.findViewById(android.R.id.list); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, mChoices)); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Pre-select currently selected item. new Handler().post(new Runnable() { @Override public void run() { String selection = mPage.getData().getString(Page.SIMPLE_DATA_KEY); for (int i = 0; i < mChoices.size(); i++) { if (mChoices.get(i).equals(selection)) { listView.setItemChecked(i, true); break; } } } }); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof PageFragmentCallbacks)) { throw new ClassCastException("Activity must implement PageFragmentCallbacks"); } mCallbacks = (PageFragmentCallbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onListItemClick(ListView l, View v, int position, long id) { mPage.getData().putString(Page.SIMPLE_DATA_KEY, getListAdapter().getItem(position).toString()); mPage.notifyDataChanged(); } }
mit
jkazama/sandbox
amqp/src/main/java/sample/rabbitmq/RabbitDirectChecker.java
3030
package sample.rabbitmq; import static sample.rabbitmq.annotation.RabbitDirectRouting.*; import java.util.Arrays; import java.util.concurrent.*; import org.springframework.amqp.rabbit.annotation.*; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import sample.model.News; import sample.rabbitmq.annotation.RabbitDirectRouting; /** * RabbitMQ の Exchange#Direct ( 1-1 ) 接続サンプル。 * <p>Sender -> Receiver * <p>利用する Exchange / Queue は RabbitListener を用いて自動的に作成しています。 * <p>Rabbit の依存を避けてベタに定義したい場合は Queue / Exchange をコンテナに登録し、 * 受信コンポーネントを SimpleMessageListenerContainer で構築してください。 */ @Slf4j @Component public class RabbitDirectChecker { @Autowired private NewsSender newsSender; @Autowired private NewsReceiver newsReceiver; public void checkDirect() { log.info("## RabbitMQ DirectCheck ###"); log.info("### send"); newsSender.send(new News(1L, "subject", "body")); log.info("### wait..."); newsReceiver.waitMessage(); log.info("### finish"); } /** * コンシューマ定義。 * <p>RabbitListener と admin 指定を利用する事で動的に Exchange と Queue の定義 ( Binding 含 ) を行っている。 * 1-n の時は使い捨ての Queue を前提にして名称は未指定で。 * <pre> * [NewsRoutingKey] -> -1- [NewsQueue] -1-> Queue * </pre> * <p>アノテーションを別途切り出す例 ( RabbitDirectRouting )。逆に分かりにくいかも、、 */ @Component @RabbitDirectRouting static class NewsReceiver { private final CountDownLatch latch = new CountDownLatch(1); @RabbitHandler public void receiveMessage(News... news) { log.info("receive message."); Arrays.stream(news) .map(News::toString) .forEach(log::info); latch.countDown(); } public void waitMessage() { try { latch.await(5000, TimeUnit.SECONDS); } catch (InterruptedException e) { } } } /** <pre>Message -> [NewsRoutingKey]</pre> */ @Component static class NewsSender { @Autowired RabbitTemplate tmpl; public NewsSender send(News... news) { tmpl.convertAndSend(NewsDirect, NewsRoutingKey, news); return this; } } @EventListener void handleContextRefresh(ListenerContainerConsumerFailedEvent event) { log.error("起動失敗事由: " + event.getReason()); } }
mit
graphql-java/graphql-java
src/main/java/graphql/analysis/MaxQueryComplexityInstrumentation.java
7538
package graphql.analysis; import graphql.PublicApi; import graphql.execution.AbortExecutionException; import graphql.execution.instrumentation.InstrumentationContext; import graphql.execution.instrumentation.SimpleInstrumentation; import graphql.execution.instrumentation.parameters.InstrumentationValidationParameters; import graphql.validation.ValidationError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import static graphql.Assert.assertNotNull; import static graphql.execution.instrumentation.SimpleInstrumentationContext.whenCompleted; import static java.util.Optional.ofNullable; /** * Prevents execution if the query complexity is greater than the specified maxComplexity. * * Use the {@code Function<QueryComplexityInfo, Boolean>} parameter to supply a function to perform a custom action when the max complexity * is exceeded. If the function returns {@code true} a {@link AbortExecutionException} is thrown. */ @PublicApi public class MaxQueryComplexityInstrumentation extends SimpleInstrumentation { private static final Logger log = LoggerFactory.getLogger(MaxQueryComplexityInstrumentation.class); private final int maxComplexity; private final FieldComplexityCalculator fieldComplexityCalculator; private final Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction; /** * new Instrumentation with default complexity calculator which is `1 + childComplexity` * * @param maxComplexity max allowed complexity, otherwise execution will be aborted */ public MaxQueryComplexityInstrumentation(int maxComplexity) { this(maxComplexity, (queryComplexityInfo) -> true); } /** * new Instrumentation with default complexity calculator which is `1 + childComplexity` * * @param maxComplexity max allowed complexity, otherwise execution will be aborted * @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded */ public MaxQueryComplexityInstrumentation(int maxComplexity, Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) { this(maxComplexity, (env, childComplexity) -> 1 + childComplexity, maxQueryComplexityExceededFunction); } /** * new Instrumentation with custom complexity calculator * * @param maxComplexity max allowed complexity, otherwise execution will be aborted * @param fieldComplexityCalculator custom complexity calculator */ public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator) { this(maxComplexity, fieldComplexityCalculator, (queryComplexityInfo) -> true); } /** * new Instrumentation with custom complexity calculator * * @param maxComplexity max allowed complexity, otherwise execution will be aborted * @param fieldComplexityCalculator custom complexity calculator * @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded */ public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator, Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) { this.maxComplexity = maxComplexity; this.fieldComplexityCalculator = assertNotNull(fieldComplexityCalculator, () -> "calculator can't be null"); this.maxQueryComplexityExceededFunction = maxQueryComplexityExceededFunction; } @Override public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraverser queryTraverser = newQueryTraverser(parameters); Map<QueryVisitorFieldEnvironment, Integer> valuesByParent = new LinkedHashMap<>(); queryTraverser.visitPostOrder(new QueryVisitorStub() { @Override public void visitField(QueryVisitorFieldEnvironment env) { int childsComplexity = valuesByParent.getOrDefault(env, 0); int value = calculateComplexity(env, childsComplexity); valuesByParent.compute(env.getParentEnvironment(), (key, oldValue) -> ofNullable(oldValue).orElse(0) + value ); } }); int totalComplexity = valuesByParent.getOrDefault(null, 0); if (log.isDebugEnabled()) { log.debug("Query complexity: {}", totalComplexity); } if (totalComplexity > maxComplexity) { QueryComplexityInfo queryComplexityInfo = QueryComplexityInfo.newQueryComplexityInfo() .complexity(totalComplexity) .instrumentationValidationParameters(parameters) .build(); boolean throwAbortException = maxQueryComplexityExceededFunction.apply(queryComplexityInfo); if (throwAbortException) { throw mkAbortException(totalComplexity, maxComplexity); } } }); } /** * Called to generate your own error message or custom exception class * * @param totalComplexity the complexity of the query * @param maxComplexity the maximum complexity allowed * * @return a instance of AbortExecutionException */ protected AbortExecutionException mkAbortException(int totalComplexity, int maxComplexity) { return new AbortExecutionException("maximum query complexity exceeded " + totalComplexity + " > " + maxComplexity); } QueryTraverser newQueryTraverser(InstrumentationValidationParameters parameters) { return QueryTraverser.newQueryTraverser() .schema(parameters.getSchema()) .document(parameters.getDocument()) .operationName(parameters.getOperation()) .variables(parameters.getVariables()) .build(); } private int calculateComplexity(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment, int childsComplexity) { if (queryVisitorFieldEnvironment.isTypeNameIntrospectionField()) { return 0; } FieldComplexityEnvironment fieldComplexityEnvironment = convertEnv(queryVisitorFieldEnvironment); return fieldComplexityCalculator.calculate(fieldComplexityEnvironment, childsComplexity); } private FieldComplexityEnvironment convertEnv(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { FieldComplexityEnvironment parentEnv = null; if (queryVisitorFieldEnvironment.getParentEnvironment() != null) { parentEnv = convertEnv(queryVisitorFieldEnvironment.getParentEnvironment()); } return new FieldComplexityEnvironment( queryVisitorFieldEnvironment.getField(), queryVisitorFieldEnvironment.getFieldDefinition(), queryVisitorFieldEnvironment.getFieldsContainer(), queryVisitorFieldEnvironment.getArguments(), parentEnv ); } }
mit
Maxopoly/Finale
src/main/java/com/github/maxopoly/finale/combat/CombatConfig.java
4053
package com.github.maxopoly.finale.combat; public class CombatConfig { private int cpsLimit; private long cpsCounterInterval; private boolean noCooldown; private double maxReach; private boolean sweepEnabled; private CombatSoundConfig combatSounds; private double horizontalKb; private double verticalKb; private double sprintHorizontal; private double sprintVertical; private double airHorizontal; private double airVertical; private double waterHorizontal; private double waterVertical; private double attackMotionModifier; private boolean stopSprinting; private double potionCutOffDistance; public CombatConfig(boolean noCooldown, int cpsLimit, long cpsCounterInterval, double maxReach, boolean sweepEnabled, CombatSoundConfig combatSounds, double horizontalKb, double verticalKb, double sprintHorizontal, double sprintVertical, double airHorizontal, double airVertical, double waterHorizontal, double waterVertical, double attackMotionModifier, boolean stopSprinting, double potionCutOffDistance) { this.noCooldown = noCooldown; this.cpsLimit = cpsLimit; this.cpsCounterInterval = cpsCounterInterval; this.maxReach = maxReach; this.sweepEnabled = sweepEnabled; this.combatSounds = combatSounds; this.horizontalKb = horizontalKb; this.verticalKb = verticalKb; this.sprintHorizontal = sprintHorizontal; this.sprintVertical = sprintVertical; this.airHorizontal = airHorizontal; this.airVertical = airVertical; this.waterHorizontal = waterHorizontal; this.waterVertical = waterVertical; this.attackMotionModifier = attackMotionModifier; this.stopSprinting = stopSprinting; this.potionCutOffDistance = potionCutOffDistance; } public void setPotionCutOffDistance(double potionCutOffDistance) { this.potionCutOffDistance = potionCutOffDistance; } public double getPotionCutOffDistance() { return potionCutOffDistance; } public void setHorizontalKb(double horizontalKb) { this.horizontalKb = horizontalKb; } public void setVerticalKb(double verticalKb) { this.verticalKb = verticalKb; } public void setSprintHorizontal(double sprintHorizontal) { this.sprintHorizontal = sprintHorizontal; } public void setSprintVertical(double sprintVertical) { this.sprintVertical = sprintVertical; } public void setAirHorizontal(double airHorizontal) { this.airHorizontal = airHorizontal; } public void setAirVertical(double airVertical) { this.airVertical = airVertical; } public void setWaterHorizontal(double waterHorizontal) { this.waterHorizontal = waterHorizontal; } public void setWaterVertical(double waterVertical) { this.waterVertical = waterVertical; } public void setAttackMotionModifier(double attackMotionModifier) { this.attackMotionModifier = attackMotionModifier; } public void setStopSprinting(boolean stopSprinting) { this.stopSprinting = stopSprinting; } public double getAirHorizontal() { return airHorizontal; } public double getAirVertical() { return airVertical; } public double getWaterHorizontal() { return waterHorizontal; } public double getWaterVertical() { return waterVertical; } public boolean isStopSprinting() { return stopSprinting; } public double getHorizontalKb() { return horizontalKb; } public double getVerticalKb() { return verticalKb; } public double getSprintHorizontal() { return sprintHorizontal; } public double getSprintVertical() { return sprintVertical; } public double getAttackMotionModifier() { return attackMotionModifier; } public int getCPSLimit() { return cpsLimit; } public long getCpsCounterInterval() { return cpsCounterInterval; } public boolean isNoCooldown() { return noCooldown; } public double getMaxReach() { return maxReach; } public boolean isSweepEnabled() { return sweepEnabled; } public CombatSoundConfig getCombatSounds() { return combatSounds; } public double getHorizontalKB() { return horizontalKb; } public double getVerticalKB() { return verticalKb; } }
mit
xetorthio/jedis
src/main/java/redis/clients/jedis/util/RedisOutputStream.java
4015
package redis.clients.jedis.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * The class implements a buffered output stream without synchronization There are also special * operations like in-place string encoding. This stream fully ignore mark/reset and should not be * used outside Jedis */ public final class RedisOutputStream extends FilterOutputStream { protected final byte[] buf; protected int count; private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public RedisOutputStream(final OutputStream out) { this(out, 8192); } public RedisOutputStream(final OutputStream out, final int size) { super(out); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; } private void flushBuffer() throws IOException { if (count > 0) { out.write(buf, 0, count); count = 0; } } public void write(final byte b) throws IOException { if (count == buf.length) { flushBuffer(); } buf[count++] = b; } @Override public void write(final byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { if (len >= buf.length) { flushBuffer(); out.write(b, off, len); } else { if (len >= buf.length - count) { flushBuffer(); } System.arraycopy(b, off, buf, count, len); count += len; } } public void writeCrLf() throws IOException { if (2 >= buf.length - count) { flushBuffer(); } buf[count++] = '\r'; buf[count++] = '\n'; } public void writeIntCrLf(int value) throws IOException { if (value < 0) { write((byte) '-'); value = -value; } int size = 0; while (value > sizeTable[size]) size++; size++; if (size >= buf.length - count) { flushBuffer(); } int q, r; int charPos = count + size; while (value >= 65536) { q = value / 100; r = value - ((q << 6) + (q << 5) + (q << 2)); value = q; buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitTens[r]; } for (;;) { q = (value * 52429) >>> (16 + 3); r = value - ((q << 3) + (q << 1)); buf[--charPos] = digits[r]; value = q; if (value == 0) break; } count += size; writeCrLf(); } @Override public void flush() throws IOException { flushBuffer(); out.flush(); } }
mit
imrenagi/microservice-skeleton
service-auth/src/test/java/com/imrenagi/service_auth/service/security/MysqlUserDetailsServiceTest.java
2072
package com.imrenagi.service_auth.service.security; import com.imrenagi.service_auth.AuthApplication; import com.imrenagi.service_auth.domain.User; import com.imrenagi.service_auth.repository.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; /** * Created by imrenagi on 5/14/17. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AuthApplication.class) @WebAppConfiguration public class MysqlUserDetailsServiceTest { @InjectMocks private MysqlUserDetailsService userDetailsService; @Mock private UserRepository repository; @Before public void setup() { initMocks(this); } @Test public void shouldReturnUserDetailWhenAUserIsFound() throws Exception { final User user = new User("imrenagi", "1234", "imre", "nagi"); doReturn(user).when(repository).findByUsername(user.getUsername()); UserDetails found = userDetailsService.loadUserByUsername(user.getUsername()); assertEquals(user.getUsername(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); verify(repository, times(1)).findByUsername(user.getUsername()); } @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(repository).findByUsername(anyString()); try { userDetailsService.loadUserByUsername(anyString()); fail(); } catch (Exception e) { } } }
mit
Josecho93/ExamenCliente
src/main/java/net/daw/bean/Element.java
1120
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.daw.bean; import com.google.gson.annotations.Expose; /** * * @author rafa */ public class Element implements IElement { @Expose private String tag; // @Expose // private String name; @Expose private String id; @Expose private String clase; @Override public String getTag() { return tag; } @Override public void setTag(String tag) { this.tag = tag; } // @Override // public String getName() { // return name; // } // // @Override // public void setName(String name) { // this.name = name; // } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getTagClass() { return clase; } @Override public void setTagClass(String clase) { this.clase = clase; } }
mit
vitrivr/cineast
cineast-api/src/main/java/org/vitrivr/cineast/api/rest/handlers/actions/metadata/FindObjectMetadataFullyQualifiedGetHandler.java
2769
package org.vitrivr.cineast.api.rest.handlers.actions.metadata; import io.javalin.http.Context; import io.javalin.plugin.openapi.dsl.OpenApiBuilder; import io.javalin.plugin.openapi.dsl.OpenApiDocumentation; import java.util.Map; import org.vitrivr.cineast.api.messages.result.MediaObjectMetadataQueryResult; import org.vitrivr.cineast.api.rest.OpenApiCompatHelper; import org.vitrivr.cineast.api.rest.handlers.interfaces.GetRestHandler; import org.vitrivr.cineast.api.rest.services.MetadataRetrievalService; /** * This class handles GET requests with an object id, domain and key and returns all matching metadata descriptors. * <p> * <h3>GET</h3> * This action's resource should have the following structure: {@code find/metadata/of/:id/in/:domain/with/:key}. It returns then all metadata of the object with this id, belonging to that domain with the specified key. * </p> */ public class FindObjectMetadataFullyQualifiedGetHandler implements GetRestHandler<MediaObjectMetadataQueryResult> { public static final String OBJECT_ID_NAME = "id"; public static final String DOMAIN_NAME = "domain"; public static final String KEY_NAME = "key"; public static final String ROUTE = "find/metadata/of/{" + OBJECT_ID_NAME + "}/in/{" + DOMAIN_NAME + "}/with/{" + KEY_NAME + "}"; @Override public MediaObjectMetadataQueryResult doGet(Context ctx) { final Map<String, String> parameters = ctx.pathParamMap(); final String objectId = parameters.get(OBJECT_ID_NAME); final String domain = parameters.get(DOMAIN_NAME); final String key = parameters.get(KEY_NAME); final MetadataRetrievalService service = new MetadataRetrievalService(); return new MediaObjectMetadataQueryResult("", service.find(objectId, domain, key) ); } public OpenApiDocumentation docs() { return OpenApiBuilder.document() .operation(op -> { op.description("The description"); op.summary("Find metadata for specific object id in given domain with given key"); op.addTagsItem(OpenApiCompatHelper.METADATA_OAS_TAG); op.operationId("findMetaFullyQualified"); }) .pathParam(OBJECT_ID_NAME, String.class, param -> { param.description("The object id"); }) .pathParam(DOMAIN_NAME, String.class, param -> { param.description("The domain name"); }) .pathParam(KEY_NAME, String.class, param -> param.description("Metadata key")) .json("200", outClass()); } @Override public String route() { return ROUTE; } @Override public Class<MediaObjectMetadataQueryResult> outClass() { return MediaObjectMetadataQueryResult.class; } /* TODO Actually, there is a lot of refactoring potential in this entire package */ }
mit
Rubentxu/GDX-Logic-Bricks
gdx-logic-bricks/src/main/java/com/indignado/logicbricks/utils/builders/joints/JointBuilder.java
2754
package com.indignado.logicbricks.utils.builders.joints; import com.badlogic.gdx.physics.box2d.World; /** * @author Rubentxu */ public class JointBuilder { private final World world; private DistanceJointBuilder distanceJointBuilder; private FrictionJointBuilder frictionJointBuilder; private GearJointBuilder gearJointBuilder; private PrismaticJointBuilder prismaticJointBuilder; private PulleyJointBuilder pulleyJointBuilder; private RevoluteJointBuilder revoluteJointBuilder; private RopeJointBuilder ropeJointBuilder; private WeldJointBuilder weldJointBuilder; private WheelJointBuilder wheelJointBuilder; public JointBuilder(World world) { this.world = world; } public DistanceJointBuilder distanceJoint() { if (distanceJointBuilder == null) distanceJointBuilder = new DistanceJointBuilder(world); else distanceJointBuilder.reset(); return distanceJointBuilder; } public FrictionJointBuilder frictionJoint() { if (frictionJointBuilder == null) frictionJointBuilder = new FrictionJointBuilder(world); else frictionJointBuilder.reset(); return frictionJointBuilder; } public GearJointBuilder gearJoint() { if (gearJointBuilder == null) gearJointBuilder = new GearJointBuilder(world); else gearJointBuilder.reset(); return gearJointBuilder; } public PrismaticJointBuilder prismaticJoint() { if (prismaticJointBuilder == null) prismaticJointBuilder = new PrismaticJointBuilder(world); else prismaticJointBuilder.reset(); return prismaticJointBuilder; } public PulleyJointBuilder pulleyJoint() { if (pulleyJointBuilder == null) pulleyJointBuilder = new PulleyJointBuilder(world); else pulleyJointBuilder.reset(); return pulleyJointBuilder; } public RevoluteJointBuilder revoluteJoint() { if (revoluteJointBuilder == null) revoluteJointBuilder = new RevoluteJointBuilder(world); else revoluteJointBuilder.reset(); return revoluteJointBuilder; } public RopeJointBuilder ropeJoint() { if (ropeJointBuilder == null) ropeJointBuilder = new RopeJointBuilder(world); else ropeJointBuilder.reset(); return ropeJointBuilder; } public WeldJointBuilder weldJoint() { if (weldJointBuilder == null) weldJointBuilder = new WeldJointBuilder(world); else weldJointBuilder.reset(); return weldJointBuilder; } public WheelJointBuilder wheelJoint() { if (wheelJointBuilder == null) wheelJointBuilder = new WheelJointBuilder(world); else wheelJointBuilder.reset(); return wheelJointBuilder; } }
mit
kristinclemens/checkers
GameLogic/src/checkers/logic/main/Player.java
451
package checkers.logic.main; import java.util.Scanner; public class Player { public static void main(String[] args) { consolePlayer(); } private static void consolePlayer(){ CheckersGame g = new CheckersGame(); Scanner in = new Scanner(System.in); int x; int y; while(!g.gameOver()){ //g.testPrint(); System.out.println(g.getBoardStateString()); x = in.nextInt(); y = in.nextInt(); g.act(Util.coord(x, y)); } } }
mit
daneko/SimpleItemAnimator
library/src/main/java/com/github/daneko/simpleitemanimator/DefaultAnimations.java
3855
package com.github.daneko.simpleitemanimator; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorCompat; import android.view.View; import fj.F; import fj.F2; import fj.F3; import fj.Unit; import fj.data.Option; /** * @see {@link android.support.v7.widget.DefaultItemAnimator} */ public class DefaultAnimations { public static F<View, Unit> addPrepareStateSetter() { return (view -> { ViewCompat.setAlpha(view, 0); return Unit.unit(); }); } public static F<View, Unit> removePrepareStateSetter() { return (view -> Unit.unit()); } public static F2<View, SimpleItemAnimator.EventParam, Unit> movePrepareStateSetter() { return ((view, param) -> { if (param.getFromPoint().isNone() || param.getToPoint().isNone()) { return Unit.unit(); } final int deltaX = param.getToPoint().some().x - param.getFromPoint().some().x + (int) ViewCompat.getTranslationX(view); final int deltaY = param.getToPoint().some().y - param.getFromPoint().some().y + (int) ViewCompat.getTranslationY(view); ViewCompat.setTranslationX(view, -deltaX); ViewCompat.setTranslationY(view, -deltaY); return Unit.unit(); }); } public static F3<View, Option<View>, SimpleItemAnimator.EventParam, Unit> changePrepareStateSetter() { return ((oldView, newViewOption, param) -> { if (param.getFromPoint().isNone() || param.getToPoint().isNone() || newViewOption.isNone()) { return Unit.unit(); } final View newView = newViewOption.some(); final int deltaX = param.getToPoint().some().x - param.getFromPoint().some().x + (int) ViewCompat.getTranslationX(oldView); final int deltaY = param.getToPoint().some().y - param.getFromPoint().some().y + (int) ViewCompat.getTranslationY(oldView); ViewCompat.setTranslationX(newView, -deltaX); ViewCompat.setTranslationY(newView, -deltaY); ViewCompat.setAlpha(newView, 0); return Unit.unit(); }); } public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> addEventAnimation() { return (animator -> animator.alpha(1f)); } public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> removeEventAnimation() { return (animator -> animator.alpha(0f)); } public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> moveEventAnimation() { return ((animator, param) -> animator.translationY(0f).translationX(0f)); } public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForOldView() { return ((animator, param) -> { if (param.getFromPoint().isNone() || param.getToPoint().isNone()) { return animator; } final int deltaX = param.getToPoint().some().x - param.getFromPoint().some().x; final int deltaY = param.getToPoint().some().y - param.getFromPoint().some().y; return animator.translationX(deltaX).translationY(deltaY).alpha(0f); }); } public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForNewView() { return ((animator, param) -> animator.translationX(0f).translationY(0f).alpha(0f)); } }
mit
d2fn/passage
src/main/java/com/bbn/openmap/image/ImageServerUtils.java
5229
// ********************************************************************** // // <copyright> // // BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> // ********************************************************************** // // $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerUtils.java,v $ // $RCSfile: ImageServerUtils.java,v $ // $Revision: 1.10 $ // $Date: 2006/02/16 16:22:49 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.image; import java.awt.Color; import java.awt.Paint; import java.awt.geom.Point2D; import java.util.Properties; import com.bbn.openmap.omGraphics.OMColor; import com.bbn.openmap.proj.Proj; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.proj.ProjectionFactory; import com.bbn.openmap.util.Debug; import com.bbn.openmap.util.PropUtils; /** * A class to contain convenience functions for parsing web image requests. */ public class ImageServerUtils implements ImageServerConstants { /** * Create an OpenMap projection from the values stored in a Properties * object. The properties inside should be parsed out from a map request, * with the keywords being those defined in the ImageServerConstants * interface. Assumes that the shared instance of the ProjectionFactory has * been initialized with the expected Projections. */ public static Proj createOMProjection(Properties props, Projection defaultProj) { float scale = PropUtils.floatFromProperties(props, SCALE, defaultProj.getScale()); int height = PropUtils.intFromProperties(props, HEIGHT, defaultProj.getHeight()); int width = PropUtils.intFromProperties(props, WIDTH, defaultProj.getWidth()); Point2D llp = defaultProj.getCenter(); float longitude = PropUtils.floatFromProperties(props, LON, (float) llp.getX()); float latitude = PropUtils.floatFromProperties(props, LAT, (float) llp.getY()); Class<? extends Projection> projClass = null; String projType = props.getProperty(PROJTYPE); ProjectionFactory projFactory = ProjectionFactory.loadDefaultProjections(); if (projType != null) { projClass = projFactory.getProjClassForName(projType); } if (projClass == null) { projClass = defaultProj.getClass(); } if (Debug.debugging("imageserver")) { Debug.output("ImageServerUtils.createOMProjection: projection " + projClass.getName() + ", with HEIGHT = " + height + ", WIDTH = " + width + ", lat = " + latitude + ", lon = " + longitude + ", scale = " + scale); } Proj proj = (Proj) projFactory.makeProjection(projClass, new Point2D.Float(longitude, latitude), scale, width, height); return (Proj) proj; } /** * Create a Color object from the properties TRANSPARENT and BGCOLOR * properties. Default color returned is white. * * @param props the Properties containing background color information. * @return Color object for background. */ public static Color getBackground(Properties props) { return (Color) getBackground(props, Color.white); } /** * Create a Color object from the properties TRANSPARENT and BGCOLOR * properties. Default color returned is white. * * @param props the Properties containing background color information. * @param defPaint the default Paint to use in case the color isn't defined * in the properties. * @return Color object for background. */ public static Paint getBackground(Properties props, Paint defPaint) { boolean transparent = PropUtils.booleanFromProperties(props, TRANSPARENT, false); Paint backgroundColor = PropUtils.parseColorFromProperties(props, BGCOLOR, defPaint); if (backgroundColor == null) { backgroundColor = Color.white; } if (transparent) { if (backgroundColor instanceof Color) { Color bgc = (Color) backgroundColor; backgroundColor = new Color(bgc.getRed(), bgc.getGreen(), bgc.getBlue(), 0x00); } else { backgroundColor = OMColor.clear; } } if (Debug.debugging("imageserver")) { Debug.output("ImageServerUtils.createOMProjection: projection color: " + (backgroundColor instanceof Color ? Integer.toHexString(((Color) backgroundColor).getRGB()) : backgroundColor.toString()) + ", transparent(" + transparent + ")"); } return backgroundColor; } }
mit