repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
swaplicado/siie32
src/erp/mmkt/view/SViewConfigurationSalesAgent.java
5616
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mmkt.view; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.lib.SLibConstants; import erp.lib.table.STabFilterDeleted; import erp.lib.table.STableColumn; import erp.lib.table.STableConstants; import erp.lib.table.STableField; import erp.lib.table.STableSetting; import javax.swing.JButton; import sa.gui.util.SUtilConsts; /** * * @author Néstor Ávalos */ public class SViewConfigurationSalesAgent extends erp.lib.table.STableTab implements java.awt.event.ActionListener { private erp.lib.table.STabFilterDeleted moTabFilterDeleted; public SViewConfigurationSalesAgent(erp.client.SClientInterface client, java.lang.String tabTitle) { super(client, tabTitle, SDataConstants.MKT_CFG_SAL_AGT); initComponents(); } private void initComponents() { int i; int levelRightEdit = SDataConstantsSys.UNDEFINED; moTabFilterDeleted = new STabFilterDeleted(this); addTaskBarUpperSeparator(); addTaskBarUpperComponent(moTabFilterDeleted); STableField[] aoKeyFields = new STableField[1]; STableColumn[] aoTableColumns = new STableColumn[9]; i = 0; aoKeyFields[i++] = new STableField(SLibConstants.DATA_TYPE_INTEGER, "c.id_sal_agt"); for (i = 0; i < aoKeyFields.length; i++) { moTablePane.getPrimaryKeyFields().add(aoKeyFields[i]); } i = 0; aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "b.bp", "Agente ventas", 300); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "t.tp_sal_agt", "Tipo agente ventas", 150); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_BOOLEAN, "c.b_del", "Eliminado", STableConstants.WIDTH_BOOLEAN); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "un.usr", "Usr. creación", STableConstants.WIDTH_USER); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "c.ts_new", "Creación", STableConstants.WIDTH_DATE_TIME); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "ue.usr", "Usr. modificación", STableConstants.WIDTH_USER); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "c.ts_edit", "Modificación", STableConstants.WIDTH_DATE_TIME); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "ud.usr", "Usr. eliminación", STableConstants.WIDTH_USER); aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "c.ts_del", "Eliminación", STableConstants.WIDTH_DATE_TIME); for (i = 0; i < aoTableColumns.length; i++) { moTablePane.addTableColumn(aoTableColumns[i]); } levelRightEdit = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_MKT_COMMS).Level; jbNew.setEnabled(levelRightEdit >= SUtilConsts.LEV_AUTHOR); jbEdit.setEnabled(levelRightEdit >= SUtilConsts.LEV_AUTHOR); jbDelete.setEnabled(false); mvSuscriptors.add(mnTabType); mvSuscriptors.add(SDataConstants.USRU_USR); mvSuscriptors.add(SDataConstants.BPSX_BP_ATT_SAL_AGT); populateTable(); } @Override public void actionNew() { if (jbNew.isEnabled()) { if (miClient.getGuiModule(SDataConstants.MOD_MKT).showForm(mnTabType, null) == SLibConstants.DB_ACTION_SAVE_OK) { miClient.getGuiModule(SDataConstants.MOD_MKT).refreshCatalogues(mnTabType); } } } @Override public void actionEdit() { if (jbEdit.isEnabled()) { if (moTablePane.getSelectedTableRow() != null) { if (miClient.getGuiModule(SDataConstants.MOD_MKT).showForm(mnTabType, moTablePane.getSelectedTableRow().getPrimaryKey()) == SLibConstants.DB_ACTION_SAVE_OK) { miClient.getGuiModule(SDataConstants.MOD_MKT).refreshCatalogues(mnTabType); } } } } @Override public void actionDelete() { if (jbDelete.isEnabled()) { } } @Override public void createSqlQuery() { String sqlWhere = ""; STableSetting setting = null; for (int i = 0; i < mvTableSettings.size(); i++) { setting = (erp.lib.table.STableSetting) mvTableSettings.get(i); if (setting.getType() == STableConstants.SETTING_FILTER_DELETED && setting.getStatus() == STableConstants.STATUS_ON) { sqlWhere += (sqlWhere.length() == 0 ? "" : "AND ") + "c.b_del = FALSE "; } } msSql = "SELECT b.bp, t.tp_sal_agt, un.usr, ue.usr, ud.usr, c.* " + "FROM mkt_cfg_sal_agt AS c " + "INNER JOIN erp.bpsu_bp AS b ON c.id_sal_agt = b.id_bp " + "INNER JOIN mktu_tp_sal_agt AS t ON c.fid_tp_sal_agt = t.id_tp_sal_agt " + "INNER JOIN erp.usru_usr AS un ON c.fid_usr_new = un.id_usr " + "INNER JOIN erp.usru_usr AS ue ON c.fid_usr_edit = ue.id_usr " + "INNER JOIN erp.usru_usr AS ud ON c.fid_usr_del = ud.id_usr " + (sqlWhere.length() == 0 ? "" : "WHERE " + sqlWhere) + "ORDER BY b.bp, t.tp_sal_agt "; } @Override public void actionPerformed(java.awt.event.ActionEvent e) { super.actionPerformed(e); if (e.getSource() instanceof javax.swing.JButton) { JButton button = (javax.swing.JButton) e.getSource(); } } }
mit
phase/Pore
src/main/java/blue/lapis/pore/impl/event/world/PoreWorldInitEvent.java
1868
/* * Pore * Copyright (c) 2014-2015, Lapis <https://github.com/LapisBlue> * * The MIT License * * 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 blue.lapis.pore.impl.event.world; import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang.NotImplementedException; import org.bukkit.World; import org.bukkit.event.world.WorldInitEvent; import org.spongepowered.api.event.world.WorldEvent; public class PoreWorldInitEvent extends WorldInitEvent { private final WorldEvent handle; public PoreWorldInitEvent(WorldEvent handle) { super(null); this.handle = checkNotNull(handle, "handle"); } public WorldEvent getHandle() { return handle; } @Override public World getWorld() { throw new NotImplementedException(); // TODO } }
mit
hubek/Refugees
src/main/java/de/zalando/refugees/config/package-info.java
85
/** * Spring Framework configuration files. */ package de.zalando.refugees.config;
mit
pgriffel/pacioli
src/mvm/values/matrix/MatrixShape.java
8589
/* * Copyright (c) 2013 - 2014 Paul Griffioen * * 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 mvm.values.matrix; import java.io.PrintWriter; import java.util.List; import mvm.AbstractPrintable; import uom.Fraction; import uom.Unit; public class MatrixShape extends AbstractPrintable { private final Unit<MatrixBase> factor; private final MatrixDimension rowDimension; private final MatrixDimension columnDimension; public final Unit<MatrixBase> rowUnit; public final Unit<MatrixBase> columnUnit; public MatrixShape(Unit<MatrixBase> factor, MatrixDimension rowDimension, Unit<MatrixBase> rowUnit, MatrixDimension columnDimension, Unit<MatrixBase> columnUnit) { this.factor = factor; this.rowDimension = rowDimension; this.rowUnit = rowUnit; this.columnDimension = columnDimension; this.columnUnit = columnUnit; } public MatrixShape(Unit<MatrixBase> factor, MatrixDimension rowDimension, MatrixDimension columnDimension) { this.factor = factor; this.rowDimension = rowDimension; this.rowUnit = MatrixBase.ONE; this.columnDimension = columnDimension; this.columnUnit = MatrixBase.ONE; } public MatrixShape(Unit<MatrixBase> factor) { this.factor = factor; this.rowDimension = new MatrixDimension(); this.rowUnit = MatrixBase.ONE; this.columnDimension = new MatrixDimension(); this.columnUnit = MatrixBase.ONE; } public MatrixShape() { this.factor = MatrixBase.ONE; this.rowDimension = new MatrixDimension(); this.rowUnit = MatrixBase.ONE; this.columnDimension = new MatrixDimension(); this.columnUnit = MatrixBase.ONE; } public Unit<MatrixBase> getFactor() { return factor; } public int rowOrder() { return rowDimension().width(); } public int columnOrder() { return columnDimension().width(); } @Override public int hashCode() { return factor.hashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof MatrixShape)) { return false; } MatrixShape otherType = (MatrixShape) other; return factor.equals(otherType.factor) && rowDimension.equals(otherType.rowDimension) && rowUnit.equals(otherType.rowUnit) && columnDimension.equals(otherType.columnDimension) && columnUnit.equals(otherType.columnUnit); } public MatrixDimension rowDimension() { return rowDimension; } public MatrixDimension columnDimension() { return columnDimension; } public MatrixShape rowUnits() { return new MatrixShape(MatrixBase.ONE, rowDimension(), rowUnit, new MatrixDimension(), MatrixBase.ONE); } public MatrixShape columnUnits() { return new MatrixShape(MatrixBase.ONE, columnDimension(), columnUnit, new MatrixDimension(), MatrixBase.ONE); } public IndexSet nthRowIndexSet(int n) { return rowDimension().nthIndexSet(n); } public IndexSet nthColumnIndexSet(int n) { return columnDimension().nthIndexSet(n); } public Unit<MatrixBase> nthRowUnit(int n) { assert (n < rowOrder()); return MatrixBase.kroneckerNth(rowUnit, n); } public Unit<MatrixBase> nthColumnUnit(int n) { assert (n < columnOrder()); return MatrixBase.kroneckerNth(columnUnit, n); } public boolean unitSquare() { return rowUnit.equals(columnUnit); } public MatrixShape dimensionless() { return new MatrixShape(MatrixBase.ONE, rowDimension(), MatrixBase.ONE, columnDimension(), MatrixBase.ONE); } public MatrixShape transpose() { return new MatrixShape(factor, columnDimension(), columnUnit.reciprocal(), rowDimension(), rowUnit.reciprocal()); } public boolean multiplyable(MatrixShape other) { return (rowDimension.equals(other.rowDimension) && columnDimension.equals(other.columnDimension)); } public MatrixShape multiply(MatrixShape other) { return new MatrixShape(factor.multiply(other.factor), rowDimension(), rowUnit.multiply(other.rowUnit), columnDimension(), columnUnit.multiply(other.columnUnit)); } public MatrixShape reciprocal() { return new MatrixShape(factor.reciprocal(), rowDimension(), rowUnit.reciprocal(), columnDimension(), columnUnit.reciprocal()); } public MatrixShape sqrt() { Fraction half = new Fraction(1, 2); return new MatrixShape(factor.raise(half), rowDimension(), rowUnit.raise(half), columnDimension(), columnUnit.raise(half)); } public boolean joinable(MatrixShape other) { return columnUnit.equals(other.rowUnit); } public MatrixShape join(MatrixShape other) { return new MatrixShape(factor.multiply(other.factor), rowDimension(), rowUnit, other.columnDimension(), other.columnUnit); } public MatrixShape kronecker(MatrixShape other) { return new MatrixShape(factor.multiply(other.factor), rowDimension.kronecker(other.rowDimension), rowUnit.multiply(MatrixBase.shiftUnit(other.rowUnit, rowDimension.width())), columnDimension.kronecker(other.columnDimension), columnUnit.multiply(MatrixBase.shiftUnit(other.columnUnit, columnDimension.width()))); } public MatrixShape project(List<Integer> cols) { Unit<MatrixBase> projectedUnit = MatrixBase.ONE; for (int i = 0; i < cols.size(); i++) { projectedUnit = projectedUnit .multiply(MatrixBase.shiftUnit(MatrixBase.kroneckerNth(rowUnit, cols.get(i)), i - cols.get(i))); } return new MatrixShape(factor, rowDimension.project(cols), projectedUnit, columnDimension, columnUnit); } public boolean singleton() { return rowOrder() == 0 && columnOrder() == 0; } public MatrixShape scale(MatrixShape other) { return new MatrixShape(factor.multiply(other.factor), other.rowDimension(), other.rowUnit, other.columnDimension(), other.columnUnit); } public MatrixShape extractColumn() { return new MatrixShape(factor, rowDimension(), rowUnit, new MatrixDimension(), MatrixBase.ONE); } public MatrixShape extractRow() { return new MatrixShape(factor, new MatrixDimension(), MatrixBase.ONE, columnDimension(), columnUnit); } public MatrixShape leftIdentity() { return new MatrixShape(MatrixBase.ONE, rowDimension(), rowUnit, rowDimension(), rowUnit); } public MatrixShape rightIdentity() { return new MatrixShape(MatrixBase.ONE, columnDimension(), columnUnit, columnDimension(), columnUnit); } public MatrixShape raise(Fraction power) { return new MatrixShape(factor.raise(power), rowDimension, rowUnit.raise(power), columnDimension, columnUnit.raise(power)); } @Override public void printText(PrintWriter out) { out.print("shape("); out.print(factor.pretty()); out.print(", "); out.print(rowDimension.toText()); out.print(", "); out.print(rowUnit.pretty()); out.print(", "); out.print(columnDimension.toText()); out.print(", "); out.print(columnUnit.pretty()); out.print(")"); } }
mit
tadeusz-piotr-pawlus/jexif
jexif-tags-database-default/src/main/java/org/jexif/tags/database/type/JExifTypeFactory.java
1822
package org.jexif.tags.database.type; import org.jexif.tags.database.spi.JExifType; import java.util.HashMap; import java.util.Map; public class JExifTypeFactory { private final Map<String, Short> name2id; public JExifTypeFactory() { this.name2id = new HashMap<>(); this.name2id.put(JExifByte.instance.getName(), JExifByte.instance.getId()); this.name2id.put(JExifAscii.instance.getName(), JExifAscii.instance.getId()); this.name2id.put(JExifShort.instance.getName(), JExifShort.instance.getId()); this.name2id.put(JExifLong.instance.getName(), JExifLong.instance.getId()); this.name2id.put(JExifRational.instance.getName(), JExifRational.instance.getId()); this.name2id.put(JExifUndefined.instance.getName(), JExifUndefined.instance.getId()); this.name2id.put(JExifSLong.instance.getName(), JExifSLong.instance.getId()); this.name2id.put(JExifSRational.instance.getName(), JExifSRational.instance.getId()); } public JExifType createByName(String name) { Short id = name2id.get(name); return createById(id); } public JExifType createById(short id) { switch (id) { case 1: return JExifByte.instance; case 2: return JExifAscii.instance; case 3: return JExifShort.instance; case 4: return JExifLong.instance; case 5: return JExifRational.instance; case 7: return JExifUndefined.instance; case 9: return JExifSLong.instance; case 10: return JExifSRational.instance; default: throw new RuntimeException("Unknown type ID: " + id); } } }
mit
clejacquet/LOD
MediaSelector/src/main/java/jp/kde/lod/jacquet/mediaselector/controller/ServletHandler.java
1030
package jp.kde.lod.jacquet.mediaselector.controller; import jp.kde.lod.jacquet.mediaselector.model.DaoProvider; import jp.kde.lod.jacquet.mediaselector.model.QueryStorage; import jp.kde.lod.jacquet.mediaselector.model.UpdateStorage; import jp.kde.lod.jacquet.pageprocessing.View; import org.json.JSONObject; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by Clement on 15/05/2015. */ public interface ServletHandler { ServletContext getContext(); HttpServletRequest getRequest(); HttpServletResponse getResponse(); void setContext(ServletContext context); void setRequest(HttpServletRequest request); void setResponse(HttpServletResponse response); View processHTML(HTMLCommand command); JSONObject processJSON(JSONCommand command); String getAbsolutePath(String relativePath); DaoProvider getDaoProvider(); QueryStorage getQueryStorage(); UpdateStorage getUpdateStorage(); }
mit
JacobMDavidson/farkle-csc478
farkle-csc478/src/main/java/com/lotsofun/farkle/Player.java
5990
package com.lotsofun.farkle; import java.util.ArrayList; import java.util.HashMap; /** * The Player class creates a player object that tracks the roll scores, game * score, player number, player type, player name, turn number, roll number, * turn scores, and game score for this player. * * @author Brant Mullinix * @version 3.0.0 */ public class Player { /** The hash map of roll scores for the player */ private HashMap<Integer, Integer> rollScore = new HashMap<Integer, Integer>(); /** This player's number */ private int playerNumber; /** The turn number for this player */ private int turnNumber = 1; /** The roll number for this player */ private int rollNumber; /** The game score for this player */ private int gameScore = 0; /** The list of turn scores for this player */ private ArrayList<Integer> turnScores; /** The PlayerType for this player */ private PlayerType type; /** The name for this player */ private String playerName; /** * Constructor: Takes player number and initializes the turnScores * * @param playerNumber * The player number for this player. */ public Player(int playerNumber) { // Set this player's number this.playerNumber = playerNumber; // Initialize the type to PlayerType.USER type = PlayerType.USER; // Initialize the turn scores turnScores = new ArrayList<Integer>(); } /** * Puts the score in to the map for the given roll * * @param score * The integer score to enter into the rollScore map */ public void scoreRoll(int score) { rollScore.put(rollNumber, score); } /** * Get the sum of all the roll scores * * @return integer sum of all the roll scores */ public int getRollScores() { // Variable used to sum the roll scores int currentTurnScore = 0; // Sum the roll scores, and return the sum for (int i : this.getRollScore().values()) { currentTurnScore += i; } return currentTurnScore; } /** * Sets the appropriate turn's score, increments turnNumber, resets * rollNumber, currentPlayer, and rollSCore * * @param didFarkle * Set to true if the end of the turn was caused by a Farkle */ public void endTurn(boolean didFarkle) { // If the turn ended on a Farkle, set add 0 to the turn scores list if (didFarkle) { turnScores.add(0); } // Else, add the sum of the roll scores to the list else { turnScores.add(getRollScores()); } // Add the turn score to this player's game score gameScore += turnScores.get(turnNumber - 1); // Increment the turn number turnNumber++; // Reset the roll number to 0 rollNumber = 0; // Clear the map of roll scores rollScore.clear(); } /** * Get this player's player number * * @return integer representing the player number */ public int getPlayerNumber() { return playerNumber; } /** * Get this player's current turn number * * @return integer representing the current turn number */ public int getTurnNumber() { return turnNumber; } /** * Set the turn number for this player * * @param turnNumber * integer turn number to set */ public void setTurnNumber(int turnNumber) { this.turnNumber = turnNumber; } /** * Get this player's current roll number * * @return int representing the current roll number */ public int getRollNumber() { return rollNumber; } /** * Set this player's roll number * * @param rollNumber * integer roll number to set */ public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; } /** * Get this player's total game score for the current game * * @return integer representing the current total game score */ public int getGameScore() { return gameScore; } /** * Set the game score for the current player * * @param gameScore * integer game score to set */ public void setGameScore(int gameScore) { this.gameScore = gameScore; } /** * Get the list of turn scores for this player * * @return ArrayList<Integer> of the turn scores */ public ArrayList<Integer> getTurnScores() { return turnScores; } /** * Set the list of turn scores for this player * * @param turnScores * ArrayList<Integer> of turn scores to set */ public void setTurnScores(ArrayList<Integer> turnScores) { this.turnScores = turnScores; } /** * Clear the list of turn scores for this player. */ public void resetTurnScores() { this.turnScores.clear(); } /** * Get the player type of this player * * @return PlayerType for this player */ public PlayerType getType() { return type; } /** * Set the player type for this player * * @param type * PlayerType.USER or PlayerType.COMPUTER */ public void setType(PlayerType type) { this.type = type; } /** * Get the map of roll scores for this player * * @return HashMap<Integer, Integer> of roll scores for this player */ public HashMap<Integer, Integer> getRollScore() { return rollScore; } /** * Set the map of roll scores for this player * * @param rollScore * roll scores to set */ public void setRollScore(HashMap<Integer, Integer> rollScore) { this.rollScore = rollScore; } /** * Clear the roll scores for this player */ public void resetRollScores() { this.rollScore.clear(); } /** * Get the name for this player * * @return String player name */ public String getPlayerName() { return playerName; } /** * Set the name for this player * * @param playerName * name to set */ public void setPlayerName(String playerName) { this.playerName = playerName; } }
mit
rajatgoyal715/Awaaz
app/src/main/java/com/rajatgoyal/awaaz/About.java
1939
package com.rajatgoyal.awaaz; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by mukul goyal on 6/18/2016. */ public class About extends AppCompatActivity{ protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } //WebView browser = (WebView)findViewById(R.id.webview); //browser.setWebViewClient(new MyWebViewClient()); Intent i=null,chooser=null; public void click1(View v){ //browser.loadUrl("https://in.linkedin.com/in/rajat-goyal-807b43b8"); i = new Intent(android.content.Intent.ACTION_VIEW); i.setData(Uri.parse("https://in.linkedin.com/in/rajat-goyal-807b43b8")); chooser = Intent.createChooser(i,"View Profile"); startActivity(chooser); } public void click2(View v){ //i = new Intent("android.intent.action.SEND"); i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra("android.intent.extra.TEXT","please click on the following link to download my app : https://play.google.com"); chooser = Intent.createChooser(i,"Share With"); startActivity(chooser); } public void click3(View v){ i = new Intent(Intent.ACTION_SEND); i.setData(Uri.parse("mail to:")); String to[]={"rajatgoyal715@gmail.com"}; i.putExtra(Intent.EXTRA_EMAIL,to); i.putExtra(Intent.EXTRA_SUBJECT,"AWAAZ FEEDBACK"); i.setType("message/rfc822"); chooser=Intent.createChooser(i,"Send Email"); startActivity(chooser); } }
mit
hazendaz/slf4j
slf4j-log4j12/src/test/java/org/slf4j/log4j12/Log4j12MultithreadedInitializationTest.java
2715
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.log4j12; import java.util.List; import org.apache.log4j.LogManager; import org.apache.log4j.spi.LoggingEvent; import org.junit.After; import org.junit.Before; import static org.junit.Assert.assertNotNull; import org.slf4j.LoggerFactoryFriend; import org.slf4j.log4j12.testHarness.RecursiveAppender; public class Log4j12MultithreadedInitializationTest extends org.slf4j.testHarness.MultithreadedInitializationTest { static int NUM_LINES_BY_RECURSIVE_APPENDER = 3; // value of LogManager.DEFAULT_CONFIGURATION_KEY; static String CONFIG_FILE_KEY = "log4j.configuration"; final String loggerName = this.getClass().getName(); @Before public void setup() { System.setProperty(CONFIG_FILE_KEY, "recursiveInitWithActivationDelay.properties"); System.out.println("THREAD_COUNT=" + THREAD_COUNT); } @After public void tearDown() throws Exception { System.clearProperty(CONFIG_FILE_KEY); } protected long getRecordedEventCount() { List<LoggingEvent> eventList = getRecordedEvents(); assertNotNull(eventList); return eventList.size(); } protected int extraLogEvents() { return NUM_LINES_BY_RECURSIVE_APPENDER; } private List<LoggingEvent> getRecordedEvents() { org.apache.log4j.Logger root = LogManager.getRootLogger(); RecursiveAppender ra = (RecursiveAppender) root.getAppender("RECURSIVE"); assertNotNull(ra); return ra.events; } }
mit
aidanmelen/RayTracer
src/main/java/com/aidanm/scene/shape/Plane.java
411
package com.aidanm.raytracer; import java.awt.Color; public class Plane extends ShapeBase { public Color mColor; public boolean mIsMirror; public Plane(Color color, boolean isMirror) { this.mColor = color; this.mIsMirror = isMirror; } public Color getColor() { return this.mColor; } public boolean getIsMirror() { return this.mIsMirror; } }
mit
menghou0924/snapsplit
app/src/main/java/com/rnd/snapsplit/FingerprintUiHelper.java
5123
/* * Copyright (C) 2015 The Android Open Source Project * * 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.rnd.snapsplit; import android.hardware.fingerprint.FingerprintManager; import android.os.CancellationSignal; import android.widget.ImageView; import android.widget.TextView; /** * Small helper class to manage text/icon around fingerprint authentication UI. */ public class FingerprintUiHelper extends FingerprintManager.AuthenticationCallback { private static final long ERROR_TIMEOUT_MILLIS = 1600; private static final long SUCCESS_DELAY_MILLIS = 1300; private final FingerprintManager mFingerprintManager; private final ImageView mIcon; private final TextView mErrorTextView; private final Callback mCallback; private CancellationSignal mCancellationSignal; private boolean mSelfCancelled; /** * Constructor for {@link FingerprintUiHelper}. */ public FingerprintUiHelper(FingerprintManager fingerprintManager, ImageView icon, TextView errorTextView, Callback callback) { mFingerprintManager = fingerprintManager; mIcon = icon; mErrorTextView = errorTextView; mCallback = callback; } public boolean isFingerprintAuthAvailable() { // The line below prevents the false positive inspection from Android Studio // noinspection ResourceType return mFingerprintManager.isHardwareDetected() && mFingerprintManager.hasEnrolledFingerprints(); } public void startListening(FingerprintManager.CryptoObject cryptoObject) { if (!isFingerprintAuthAvailable()) { return; } mCancellationSignal = new CancellationSignal(); mSelfCancelled = false; // The line below prevents the false positive inspection from Android Studio // noinspection ResourceType mFingerprintManager .authenticate(cryptoObject, mCancellationSignal, 0 /* flags */, this, null); mIcon.setImageResource(R.drawable.ic_fp_40px); } public void stopListening() { if (mCancellationSignal != null) { mSelfCancelled = true; mCancellationSignal.cancel(); mCancellationSignal = null; } } @Override public void onAuthenticationError(int errMsgId, CharSequence errString) { if (!mSelfCancelled) { showError(errString); mIcon.postDelayed(new Runnable() { @Override public void run() { mCallback.onError(); } }, ERROR_TIMEOUT_MILLIS); } } @Override public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { showError(helpString); } @Override public void onAuthenticationFailed() { showError(mIcon.getResources().getString( R.string.fingerprint_not_recognized)); } @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { mErrorTextView.removeCallbacks(mResetErrorTextRunnable); mIcon.setImageResource(R.drawable.ic_fingerprint_success); mErrorTextView.setTextColor( mErrorTextView.getResources().getColor(R.color.success_color, null)); mErrorTextView.setText( mErrorTextView.getResources().getString(R.string.fingerprint_success)); mIcon.postDelayed(new Runnable() { @Override public void run() { mCallback.onAuthenticated(); } }, SUCCESS_DELAY_MILLIS); } private void showError(CharSequence error) { mIcon.setImageResource(R.drawable.ic_fingerprint_error); mErrorTextView.setText(error); mErrorTextView.setTextColor( mErrorTextView.getResources().getColor(R.color.warning_color, null)); mErrorTextView.removeCallbacks(mResetErrorTextRunnable); mErrorTextView.postDelayed(mResetErrorTextRunnable, ERROR_TIMEOUT_MILLIS); } private Runnable mResetErrorTextRunnable = new Runnable() { @Override public void run() { mErrorTextView.setTextColor( mErrorTextView.getResources().getColor(R.color.hint_color, null)); mErrorTextView.setText( mErrorTextView.getResources().getString(R.string.fingerprint_hint)); mIcon.setImageResource(R.drawable.ic_fp_40px); } }; public interface Callback { void onAuthenticated(); void onError(); } }
mit
shvets/cafebabe
serfile/src/main/java/org/sf/serfile/BlockDataLongEntry.java
1510
// BlockDataLongEntry.java package org.sf.serfile; import java.io.IOException; import java.io.DataInput; import java.io.DataOutput; /** * * Abstract class for representing short block data * * blockdatalong: TC_BLOCKDATALONG (int)<size> (byte)[size] * * @version 1.0 05/25/2000 * @author Alexander Shvets */ public class BlockDataLongEntry extends BlockDataEntry { /** * Reads this entry from input stream. * * @param in input stream. * @exception IOException if an I/O error occurs. */ public void read(DataInput in) throws IOException { int size = in.readInt(); buffer = new byte[size]; in.readFully(buffer); } /** * Writes this entry to output stream. * * @param out output stream. * @exception IOException if an I/O error occurs. */ public void write(DataOutput out) throws IOException { out.writeByte(getTag()); int size = buffer.length; out.writeInt(size); out.write(buffer, 0, size); } /** * Gets the length of this entry in bytes * * @return the length of entry */ public long length() { return 1 + 4 + buffer.length; } /** * Gets the type of this entry. * * @return the type of entry */ public String getType() { return "Block Data Long"; } /** * Gets the tag of this entry. * * @return the tag for entry */ public byte getTag() { return TC_BLOCKDATALONG; } }
mit
PeterASteele/PracticeContestProblems
GoogleCodeJamStandingOvation.java
2902
import java.io.IOException; import java.util.Scanner; public class GoogleCodeJamStandingOvation { /* * Problem It's opening night at the opera, and your friend is the prima donna (the lead female singer). You will not be in the audience, but you want to make sure she receives a standing ovation -- with every audience member standing up and clapping their hands for her. Initially, the entire audience is seated. Everyone in the audience has a shyness level. An audience member with shyness level Si will wait until at least Si other audience members have already stood up to clap, and if so, she will immediately stand up and clap. If Si = 0, then the audience member will always stand up and clap immediately, regardless of what anyone else does. For example, an audience member with Si = 2 will be seated at the beginning, but will stand up to clap later after she sees at least two other people standing and clapping. You know the shyness level of everyone in the audience, and you are prepared to invite additional friends of the prima donna to be in the audience to ensure that everyone in the crowd stands up and claps in the end. Each of these friends may have any shyness value that you wish, not necessarily the same. What is the minimum number of friends that you need to invite to guarantee a standing ovation? Input The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with Smax, the maximum shyness level of the shyest person in the audience, followed by a string of Smax + 1 single digits. The kth digit of this string (counting starting from 0) represents how many people in the audience have shyness level k. For example, the string "409" would mean that there were four audience members with Si = 0 and nine audience members with Si = 2 (and none with Si = 1 or any other value). Note that there will initially always be between 0 and 9 people with each shyness level. The string will never end in a 0. Note that this implies that there will always be at least one person in the audience. Output For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the minimum number of friends you must invite. Limits 1 ≤ T ≤ 100. Small dataset 0 ≤ Smax ≤ 6. Large dataset 0 ≤ Smax ≤ 1000. */ public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); input.nextLine(); for(int a = 0; a < numberOfTestCases; a++){ int n = input.nextInt(); String inputData = ""; inputData = input.nextLine(); int sum = 0; int fake = 0; for(int b = 0; b < n; b++){ sum += Integer.parseInt("" + inputData.charAt(b+1)); if(sum < b+1){ fake = fake + b+1 - sum; sum = sum + b+1 - sum; } } System.out.println("Case #" + (a+1) + ": " + fake); } } }
mit
team1306/Robot2016
src/org/usfirst/frc/team1306/robot/commands/autonomous/DriveInRange.java
1198
package org.usfirst.frc.team1306.robot.commands.autonomous; import org.usfirst.frc.team1306.robot.Constants; import org.usfirst.frc.team1306.robot.commands.CommandBase; import org.usfirst.frc.team1306.robot.vision.Vision; import org.usfirst.frc.team1306.robot.vision.VisionStatus; //TODO Documentation public class DriveInRange extends CommandBase { public DriveInRange() { requires(drivetrain); } // Called just before this Command runs the first time @Override protected void initialize() { } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { drivetrain.driveTank(Constants.SLOW_DRIVE, Constants.SLOW_DRIVE); } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return Vision.getStatus().equals(VisionStatus.INRANGE); } // Called once after isFinished returns true @Override protected void end() { drivetrain.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { end(); } }
mit
bnguyen82/stuff-projects
sjcp/src/exams/thread/assessment/test1/ex03/Fabric.java
406
package exams.thread.assessment.test1.ex03; public class Fabric extends Thread { public static void main(String[] args) { Thread t = new Thread(new Fabric()); Thread t2 = new Thread(new Fabric()); t.start(); t2.start(); } public void run() { for(int i = 0; i < 2; i++) System.out.print(Thread.currentThread().getName() + " "); } }
mit
hiryou/MLPractice
HelloWorld/src/com/leetcode/LFUCache.java
5068
package com.leetcode; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * LFU Cache * https://leetcode.com/problems/lfu-cache/description/ */ public class LFUCache { public static void main(String[] args) { LFUCache cache = new LFUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.get(3); // returns 3. cache.put(4, 4); // evicts key 1. cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 } class Node { int freq; final Set<Integer> keys = new LinkedHashSet<>(); Node prev = null; Node next = null; public Node moveKeyToNextNode(int key) { // first of all this freq node no longer contains this key this.keys.remove(key); // if this now contains no key, remove it removeMySelfIfEmptyKeys(); // try look up the next freq + 1 node if exists or not if (this.next != null && this.next.freq == this.freq+1) { this.next.keys.add(key); return this.next; } // or else: has to create new node following this node Node node = new Node(); node.freq = this.freq + 1; node.keys.add(key); // linked list operations node.next = this.next; node.prev = this; if (this.next != null) { this.next.prev = node; } this.next = node; return node; } private void removeMySelfIfEmptyKeys() { if (this.keys.isEmpty()) { if (this.prev != null) { this.prev.next = this.next; } if (this.next != null) { this.next.prev = this.prev; } } } public int removeFrontKey() { int frontKey = this.keys.iterator().next(); this.keys.remove(frontKey); removeMySelfIfEmptyKeys(); return frontKey; } // add this new key, frequency = 1 public Node checkAndAddNewKey(int key) { if (this.freq == 1) { this.keys.add(key); return this; } // else: create new prev node with freq 1 Node prevNode = new Node(); prevNode.freq = 1; prevNode.keys.add(key); prevNode.next = this; this.prev = prevNode; return prevNode; } } Node head = null; // Node head contains lowest frequency, e.g. 1 -> 2 -> 5 -> ... final int capacity; final Map<Integer, Node> keyToNode = new HashMap<>(); final Map<Integer, Integer> keyToVal = new HashMap<>(); public LFUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (keyToVal.containsKey(key)) { Node node = keyToNode.get(key); keyToNode.remove(key); Node nextNode = node.moveKeyToNextNode(key); if (head == node && head.keys.isEmpty()) { head = nextNode; } keyToNode.put(key, nextNode); System.out.println("returns " + keyToVal.get(key)); return keyToVal.get(key); } System.out.println("returns -1"); return -1; } public void put(int key, int value) { if (capacity == 0) return; if (keyToVal.containsKey(key)) { keyToVal.put(key, value); Node node = keyToNode.get(key); keyToNode.remove(key); Node nextNode = node.moveKeyToNextNode(key); if (head == node && head.keys.isEmpty()) { head = nextNode; } keyToNode.put(key, nextNode); return; } // if a new key, remove if capacity is about to be reached if (keyToVal.size() == capacity) { int frontKey = head.removeFrontKey(); if (head.keys.isEmpty()) { head = head.next; } keyToVal.remove(frontKey); keyToNode.remove(frontKey); System.out.println("evicts key " + frontKey); } // add a new key / node keyToVal.put(key, value); Node node = checkAndAddNewKey(key); if (node != head) { // signal of a new head head = node; } keyToNode.put(key, node); } private Node checkAndAddNewKey(int key) { if (head != null) { Node node = head.checkAndAddNewKey(key); return node; } // if head is null / first time head = new Node(); head.freq = 1; head.keys.add(key); return head; } }
mit
AlienIdeology/J-Cord
src/main/java/org/alienideology/jcord/event/client/call/update/CallRegionUpdateEvent.java
662
package org.alienideology.jcord.event.client.call.update; import org.alienideology.jcord.event.client.call.CallUpdateEvent; import org.alienideology.jcord.handle.Region; import org.alienideology.jcord.handle.client.IClient; import org.alienideology.jcord.handle.client.call.ICall; /** * @author AlienIdeology */ public class CallRegionUpdateEvent extends CallUpdateEvent { private final Region oldRegion; public CallRegionUpdateEvent(IClient client, int sequence, ICall call, Region oldRegion) { super(client, sequence, call); this.oldRegion = oldRegion; } public Region getOldRegion() { return oldRegion; } }
mit
celestial-winter/vics
paf-client/src/main/java/com/infinityworks/pafclient/dto/GotvVoterRequest.java
609
package com.infinityworks.pafclient.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.immutables.value.Value; import java.util.List; @Value.Immutable @JsonIgnoreProperties(ignoreUnknown = true) @Value.Style(init = "with*", jdkOnly = true) @JsonDeserialize(as = ImmutableGotvVoterRequest.class) @JsonSerialize(as = ImmutableGotvVoterRequest.class) public interface GotvVoterRequest { List<PafStreetRequest> streets(); GotvFilter filter(); }
mit
bartekbp/programming_challenges_2
src/main/java/arithmeticandalgebra/primaryarithmetic/Main.java
2574
package arithmeticandalgebra.primaryarithmetic; import java.io.IOException; public class Main implements Runnable { static String readLn(int maxLength) { byte line[] = new byte[maxLength]; int length = 0; int input = -1; try { while (length < maxLength) { input = System.in.read(); if ((input < 0) || (input == '\n')) { break; } line[length++] += input; } if ((input < 0) && (length == 0)) { return null; } return new String(line, 0, length); } catch (IOException e) { return null; } } public static void main(String args[]) { Main myWork = new Main(); myWork.run(); } public void run() { new PrimaryArithmetic().run(); } } class PrimaryArithmetic implements Runnable { public void run() { while(true) { String line = Main.readLn(22); String numbers[] = line.split("\\s"); int firstNumber = Integer.valueOf(numbers[0]); int secondNumber = Integer.valueOf(numbers[1]); if(firstNumber == 0 && secondNumber == 0) { return; } int numberOfCarry = calculateResult(firstNumber, secondNumber); printResult(numberOfCarry); } } private void printResult(int numberOfCarry) { if(numberOfCarry == 0) { System.out.println("No carry operation."); } else if(numberOfCarry == 1) { System.out.println("1 carry operation."); } else { System.out.println(String.format("%d carry operations.", numberOfCarry)); } } private int calculateResult(int firstNumber, int secondNumber) { int totalCarry = 0; int currentCarry = 0; int firstShiftedNumber = firstNumber; int secondShiftedNumber = secondNumber; while(firstShiftedNumber != 0 || secondShiftedNumber != 0) { int firstShiftedNumberModTen = firstShiftedNumber % 10; int secondShiftedNumberModTen = secondShiftedNumber % 10; if(firstShiftedNumberModTen + secondShiftedNumberModTen + currentCarry > 9) { currentCarry = 1; } else { currentCarry = 0; } totalCarry += currentCarry; firstShiftedNumber /= 10; secondShiftedNumber /= 10; } return totalCarry; } }
mit
Sciss/JWave
src/main/java/jwave/transforms/wavelets/symlets/Symlet20.java
4133
/** * JWave is distributed under the MIT License (MIT); this file is part of. * * Copyright (c) 2008-2015 Christian Scheiblich (cscheiblich@gmail.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 jwave.transforms.wavelets.symlets; import jwave.transforms.wavelets.Wavelet; /** * Symlet20 filter: near symmetric, orthogonal (orthonormal), biorthogonal. * * @author Christian Scheiblich (cscheiblich@gmail.com) * @date 16.02.2014 13:47:56 */ public class Symlet20 extends Wavelet { /** * Already orthonormal coefficients taken from Filip Wasilewski's webpage * http://wavelets.pybytes.com/wavelet/sym20/ Thanks! * * @author Christian Scheiblich (cscheiblich@gmail.com) * @date 16.02.2014 13:47:56 */ public Symlet20( ) { _name = "Symlet 20"; // name of the wavelet _transformWavelength = 2; // minimal wavelength of input signal _motherWavelength = 40; // wavelength of mother wavelet _scalingDeCom = new double[ _motherWavelength ]; _scalingDeCom[ 0 ] = 3.695537474835221e-07; _scalingDeCom[ 1 ] = -1.9015675890554106e-07; _scalingDeCom[ 2 ] = -7.919361411976999e-06; _scalingDeCom[ 3 ] = 3.025666062736966e-06; _scalingDeCom[ 4 ] = 7.992967835772481e-05; _scalingDeCom[ 5 ] = -1.928412300645204e-05; _scalingDeCom[ 6 ] = -0.0004947310915672655; _scalingDeCom[ 7 ] = 7.215991188074035e-05; _scalingDeCom[ 8 ] = 0.002088994708190198; _scalingDeCom[ 9 ] = -0.0003052628317957281; _scalingDeCom[ 10 ] = -0.006606585799088861; _scalingDeCom[ 11 ] = 0.0014230873594621453; _scalingDeCom[ 12 ] = 0.01700404902339034; _scalingDeCom[ 13 ] = -0.003313857383623359; _scalingDeCom[ 14 ] = -0.031629437144957966; _scalingDeCom[ 15 ] = 0.008123228356009682; _scalingDeCom[ 16 ] = 0.025579349509413946; _scalingDeCom[ 17 ] = -0.07899434492839816; _scalingDeCom[ 18 ] = -0.02981936888033373; _scalingDeCom[ 19 ] = 0.4058314443484506; _scalingDeCom[ 20 ] = 0.75116272842273; _scalingDeCom[ 21 ] = 0.47199147510148703; _scalingDeCom[ 22 ] = -0.0510883429210674; _scalingDeCom[ 23 ] = -0.16057829841525254; _scalingDeCom[ 24 ] = 0.03625095165393308; _scalingDeCom[ 25 ] = 0.08891966802819956; _scalingDeCom[ 26 ] = -0.0068437019650692274; _scalingDeCom[ 27 ] = -0.035373336756604236; _scalingDeCom[ 28 ] = 0.0019385970672402002; _scalingDeCom[ 29 ] = 0.012157040948785737; _scalingDeCom[ 30 ] = -0.0006111263857992088; _scalingDeCom[ 31 ] = -0.0034716478028440734; _scalingDeCom[ 32 ] = 0.0001254409172306726; _scalingDeCom[ 33 ] = 0.0007476108597820572; _scalingDeCom[ 34 ] = -2.6615550335516086e-05; _scalingDeCom[ 35 ] = -0.00011739133516291466; _scalingDeCom[ 36 ] = 4.525422209151636e-06; _scalingDeCom[ 37 ] = 1.22872527779612e-05; _scalingDeCom[ 38 ] = -3.2567026420174407e-07; _scalingDeCom[ 39 ] = -6.329129044776395e-07; _buildOrthonormalSpace( ); } // Symlet20( } // Symlet20(
mit
kanonirov/lanb-client
src/main/java/ru/lanbilling/webservice/wsdl/InsupdDevice.java
2755
package ru.lanbilling.webservice.wsdl; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="isInsert" type="{http://www.w3.org/2001/XMLSchema}long"/&gt; * &lt;element name="val" type="{urn:api3}soapDeviceFull"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "isInsert", "val" }) @XmlRootElement(name = "insupdDevice") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class InsupdDevice { @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected long isInsert; @XmlElement(required = true) @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected SoapDeviceFull val; /** * Gets the value of the isInsert property. * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public long getIsInsert() { return isInsert; } /** * Sets the value of the isInsert property. * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setIsInsert(long value) { this.isInsert = value; } /** * Gets the value of the val property. * * @return * possible object is * {@link SoapDeviceFull } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public SoapDeviceFull getVal() { return val; } /** * Sets the value of the val property. * * @param value * allowed object is * {@link SoapDeviceFull } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setVal(SoapDeviceFull value) { this.val = value; } }
mit
OpenMods/OpenPeripheral-Integration
src/main/java/openperipheral/integration/thaumcraft/AdapterEssentiaTransport.java
2068
package openperipheral.integration.thaumcraft; import net.minecraftforge.common.util.ForgeDirection; import openperipheral.api.adapter.Asynchronous; import openperipheral.api.adapter.IPeripheralAdapter; import openperipheral.api.adapter.method.Arg; import openperipheral.api.adapter.method.ReturnType; import openperipheral.api.adapter.method.ScriptCallable; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.IEssentiaTransport; @Asynchronous public class AdapterEssentiaTransport implements IPeripheralAdapter { @Override public Class<?> getTargetClass() { return IEssentiaTransport.class; } @Override public String getSourceId() { return "thaumcraft_essentia_transport"; } @ScriptCallable(returnTypes = ReturnType.NUMBER, description = "Returns the amount of suction in the tube") public int getSuctionAmount(IEssentiaTransport pipe, @Arg(description = "Direction suction coming from", name = "direction") ForgeDirection direction) { return pipe.getSuctionAmount(direction); } @ScriptCallable(returnTypes = ReturnType.STRING, description = "Returns the type of essentia wished in the tube") public String getSuctionType(IEssentiaTransport pipe, @Arg(description = "Direction suction coming from", name = "direction") ForgeDirection direction) { Aspect asp = pipe.getSuctionType(direction); return (asp != null)? asp.getTag() : ""; } @ScriptCallable(returnTypes = ReturnType.NUMBER, description = "Returns the amount of essentia in the tube") public int getEssentiaAmount(IEssentiaTransport pipe, @Arg(description = "Direction suction coming from", name = "direction") ForgeDirection direction) { return pipe.getEssentiaAmount(direction); } @ScriptCallable(returnTypes = ReturnType.STRING, description = "Returns the type of essentia in the tube") public String getEssentiaType(IEssentiaTransport pipe, @Arg(description = "Direction suction coming from", name = "direction") ForgeDirection direction) { Aspect asp = pipe.getEssentiaType(direction); return (asp != null)? asp.getTag() : ""; } }
mit
Pumuckl007/WeaponsMod
WeaponsMod/weapons/client/rendering/entity/RenderSpeeder.java
1891
package weapons.client.rendering.entity; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; import weapons.client.models.ModelSpeeder; import weapons.entity.EntitySpeeder; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderSpeeder extends Render { protected ModelSpeeder model; public RenderSpeeder() { this.shadowSize = 0.5F; this.model = new ModelSpeeder(); } public void renderBoat(EntitySpeeder entity, double par2, double par4, double par6, float par8, float par9) { GL11.glPushMatrix(); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glTranslatef((float)par2, (float)par4, (float)par6); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(-(float)entity.renderrotationYaw, 0, 1, 0); GL11.glRotatef(-(float)entity.renderrotationPitch, 0, 0, 1); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc (GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); // Bind texture FMLClientHandler.instance().getClient().renderEngine.bindTexture("/mods/weapons/textures/models/speeder.png"); this.model.render(); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glPopMatrix(); } /** * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1, * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that. */ public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) { this.renderBoat((EntitySpeeder)par1Entity, par2, par4, par6, par8, par9); } }
mit
Team-IO/teamioutils
src/main/java/net/teamio/teamioutils/Hammer.java
8924
package net.teamio.teamioutils; import java.util.Set; import com.google.common.collect.Sets; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; public class Hammer extends ItemTool { private static final Set<Block> EFFECTIVE_ON = Sets.newHashSet(new Block[] { Blocks.dirt,Blocks.grass, Blocks.gravel, Blocks.coal_ore, Blocks.cobblestone, Blocks.diamond_block, Blocks.diamond_ore, Blocks.double_stone_slab, Blocks.gold_block, Blocks.gold_ore, Blocks.ice, Blocks.iron_block, Blocks.iron_ore, Blocks.lapis_block, Blocks.lapis_ore, Blocks.lit_redstone_ore, Blocks.mossy_cobblestone, Blocks.netherrack, Blocks.redstone_ore, Blocks.sandstone, Blocks.red_sandstone, Blocks.stone, Blocks.stone_slab, Blocks.nether_brick, Blocks.nether_brick_fence, Blocks.nether_brick_stairs}); private final float efficiencyOnProperMaterial = Float.MAX_VALUE; private boolean bigTime = true; public Hammer(){ super(2f, Item.ToolMaterial.EMERALD, EFFECTIVE_ON); this.setMaxStackSize(1); this.setMaxDamage(Integer.MAX_VALUE); this.setNoRepair(); this.setHarvestLevel("Diamond", Integer.MAX_VALUE); this.isDamageable(); } @Override public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { if(playerIn.isSneaking()) { updateGhostBlocks(playerIn, worldIn); }else{ if(worldIn.isRemote) { if(bigTime) { playerIn.addChatComponentMessage(new ChatComponentTranslation("msg.big_time.true.txt")); bigTime = false; }else{ playerIn.addChatComponentMessage(new ChatComponentTranslation("msg.big_time.false.txt")); bigTime = true; } } } return itemStackIn; } @Override public boolean onBlockDestroyed(ItemStack stack, World worldIn, Block blockIn, BlockPos pos, EntityLivingBase playerIn) { if (bigTime) { EntityPlayer player = (EntityPlayer) playerIn; return breakAOEBlocks(stack, pos,1, 0, player); }else{ return true; } } @Override public boolean canHarvestBlock(Block block) { return block.getBlockState().getBlock().hasTileEntity(block.getBlockState().getBaseState())? false: true; } public boolean breakAOEBlocks(ItemStack stack, BlockPos pos, int breakRadius, int breakDepth, EntityPlayer player) { //Map<Block, Integer> blockMap = new HashMap<Block, Integer>(); //Block block = player.worldObj.getBlockState(pos).getBlock(); //IBlockState meta = player.worldObj.getBlockState(pos); if(player.getEntityWorld().isRemote) { return false; } MovingObjectPosition mop = raytraceFromEntity(player.worldObj, player, 4.5d); if(mop == null) { updateGhostBlocks(player, player.worldObj); return true; } int sideHit = mop.sideHit.getIndex(); int xMax = breakRadius; int xMin = breakRadius; int yMax = breakRadius; int yMin = breakRadius; int zMax = breakRadius; int zMin = breakRadius; int yOffset = 0; switch (sideHit) { case 0: yMax = breakDepth; yMin = 0; zMax = breakRadius; break; case 1: yMin = breakDepth; yMax = 0; zMax = breakRadius; break; case 2: xMax = breakRadius; zMin = 0; zMax = breakDepth; yOffset = breakRadius - 1; break; case 3: xMax = breakRadius; zMax = 0; zMin = breakDepth; yOffset = breakRadius - 1; break; case 4: xMax = breakDepth; xMin = 0; zMax = breakRadius; yOffset = breakRadius - 1; break; case 5: xMin = breakDepth; xMax = 0; zMax = breakRadius; yOffset = breakRadius - 1; break; } for (int xPos = pos.getX() - xMin; xPos <= pos.getX() + xMax; xPos++) { for (int yPos = pos.getY() + yOffset - yMin; yPos <= pos.getY() + yOffset + yMax; yPos++) { for (int zPos = pos.getZ() - zMin; zPos <= pos.getZ() + zMax; zPos++) { BlockPos currentBlock = new BlockPos(xPos, yPos, zPos); if (player.worldObj.getBlockState(currentBlock).getBlock().hasTileEntity(player.worldObj.getBlockState(currentBlock))) { if (player.worldObj.isRemote) { player.addChatComponentMessage(new ChatComponentTranslation("msg.baseSafeAOW.txt")); } else ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(new S23PacketBlockChange(player.worldObj,currentBlock)); return true; } } } } for (int xPos = pos.getX() - xMin; xPos <= pos.getX() + xMax; xPos++) { for (int yPos = pos.getY() + yOffset - yMin; yPos <= pos.getY() + yOffset + yMax; yPos++) { for (int zPos = pos.getZ() - zMin; zPos <= pos.getZ() + zMax; zPos++) { if(!(Block.isEqualTo(player.getEntityWorld().getBlockState(pos).getBlock(), Blocks.bedrock))) { BlockPos blockPos = new BlockPos(xPos, yPos, zPos); player.getEntityWorld().destroyBlock(blockPos, true); } } } } return true; } public static MovingObjectPosition raytraceFromEntity(World world, Entity player, double range) { float f = 1.0F; float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double) f; double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) f; if (!world.isRemote && player instanceof EntityPlayer) d1 += 1.62D; double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double) f; Vec3 vec3 = new Vec3(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = range; if (player instanceof EntityPlayerMP && range < 10) { d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); } Vec3 vec31 = vec3.addVector((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); return world.rayTraceBlocks(vec3, vec31); } public static void updateGhostBlocks(EntityPlayer player, World world) { if (world.isRemote) return; int xPos = (int) player.posX; int yPos = (int) player.posY; int zPos = (int) player.posZ; for (int x = xPos - 6; x < xPos + 6; x++) { for (int y = yPos - 6; y < yPos + 6; y++) { for (int z = zPos - 6; z < zPos + 6; z++) { ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(new S23PacketBlockChange(world, new BlockPos(x, y, z))); //world.markBlockForUpdate(x, y, z); } } } } // protected void breakExtraBlock(ItemStack stack, World world, int x, int y, int z, int totalSize, EntityPlayer player, float refStrength, boolean breakSound, Map<Block, Integer> blockMap) // { // BlockPos pos = new BlockPos(x,y,z); // if (world.getBlockState(pos).getBlock().isAir(world, pos)) return; // // Block block = world.getBlockState(pos).getBlock(); // if (block.getMaterial() instanceof MaterialLiquid || (block.getBlockState().getBlock().getBlockHardness(world, pos)== -1 && !player.capabilities.isCreativeMode)) return; // // if (!world.isRemote) { // // block.onBlockHarvested(world, pos, block., player); // // if(block.removedByPlayer(world, player, x,y,z, true)) // { // block.onBlockDestroyedByPlayer(world, x,y,z, meta); // block.harvestBlock(world, player, x,y,z, meta); // player.addExhaustion(-0.025F); // if (block.getExpDrop(world, meta, EnchantmentHelper.getFortuneModifier(player)) > 0) player.addExperience(block.getExpDrop(world, meta, EnchantmentHelper.getFortuneModifier(player))); // } // // EntityPlayerMP mpPlayer = (EntityPlayerMP) player; // mpPlayer.playerNetServerHandler.sendPacket(new S23PacketBlockChange(x, y, z, world)); // } // else // { // if (breakSound) world.playAuxSFX(2001, x, y, z, Block.getIdFromBlock(block) + (meta << 12)); // if(block.removedByPlayer(world, player, x,y,z, true)) // { // block.onBlockDestroyedByPlayer(world, x,y,z, meta); // } // // Minecraft.getMinecraft().getNetHandler().addToSendQueue(new C07PacketPlayerDigging(, pos, Minecraft.getMinecraft().objectMouseOver.sideHit)); // } // } @Override public float getStrVsBlock(ItemStack stack, Block block) { return block.hasTileEntity(block.getDefaultState()) ? 0F : this.efficiencyOnProperMaterial; } }
mit
flow/nbt
src/main/java/com/flowpowered/nbt/LongTag.java
2055
/* * This file is part of Flow NBT, licensed under the MIT License (MIT). * * Copyright (c) 2011 Flow Powered <https://flowpowered.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.flowpowered.nbt; /** * The {@code TAG_Long} tag. */ public final class LongTag extends Tag<Long> { /** * The value. */ private final long value; /** * Creates the tag. * * @param name The name. * @param value The value. */ public LongTag(String name, long value) { super(TagType.TAG_LONG, name); this.value = value; } @Override public Long getValue() { return value; } @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Long" + append + ": " + value; } public LongTag clone() { return new LongTag(getName(), value); } }
mit
erwinvaneyk/Dragons-Arena
src/main/java/distributed/systems/network/services/HeartbeatService.java
2605
package distributed.systems.network.services; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import distributed.systems.core.LogType; import distributed.systems.core.Message; import distributed.systems.core.Socket; import distributed.systems.network.AbstractNode; import distributed.systems.network.NodeAddress; public abstract class HeartbeatService implements SocketService { public static final String MESSAGE_TYPE = "HEARTBEAT"; protected static final int TIMEOUT_DURATION = 10000; protected static final int CHECK_INTERVAL = 5000; protected final Map<NodeAddress, Integer> watchNodes = new ConcurrentHashMap<>(); protected final Socket socket; protected final AbstractNode me; public HeartbeatService(AbstractNode me, Socket socket) { this.socket = socket; this.me = me; } public HeartbeatService expectHeartbeatFrom(NodeAddress node) { watchNodes.put(node, TIMEOUT_DURATION / CHECK_INTERVAL); return this; } public HeartbeatService expectHeartbeatFrom(Collection<NodeAddress> nodes) { nodes.stream().forEach(this::expectHeartbeatFrom); return this; } public void run() { me.safeLogMessage("Starting heartbeat process...", LogType.DEBUG); try { while(!Thread.currentThread().isInterrupted()) { doHeartbeat(); checkHeartbeats(); Thread.sleep(CHECK_INTERVAL); } } catch (InterruptedException e) { socket.logMessage("Heartbeat service has been stopped", LogType.INFO); } } private void checkHeartbeats() { // Count down nodes watchNodes.entrySet().stream().forEach(node -> { if(node.getValue() < 0) { removeNode(node.getKey()); } else { watchNodes.put(node.getKey(), node.getValue() - 1); } }); } // TODO: do some cleanup, moving the clients of a disconnected server to other servers protected abstract void removeNode(NodeAddress address); public abstract void doHeartbeat(); @Override public Message onMessageReceived(Message message) throws RemoteException { NodeAddress origin = message.getOrigin(); watchNodes.entrySet().stream() .filter(node -> node.getKey().equals(origin)) .findAny() .ifPresent(node -> { node.setValue(TIMEOUT_DURATION / CHECK_INTERVAL); //socket.logMessage("Received a heartbeat from node `" + node.getKey().getName() + ".", LogType.DEBUG); }); return null; } @Override public String getMessageType() { return MESSAGE_TYPE; } public void remove(NodeAddress client) { watchNodes.remove(client); } }
mit
nico01f/z-pec
ZimbraSoap/src/java/com/zimbra/soap/mail/type/LegacyAppointmentData.java
913
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; public class LegacyAppointmentData extends LegacyCalendaringData { /** * no-argument constructor wanted by JAXB */ @SuppressWarnings("unused") private LegacyAppointmentData() { this((String) null, (String) null); } public LegacyAppointmentData(String xUid, String uid) { super(xUid, uid); } }
mit
StuffTheChickenMC/PattysMoreStuff
src/main/java/com/stc/pattysmorestuff/blocks/jar/BlockJar.java
4309
package com.stc.pattysmorestuff.blocks.jar; import com.stc.pattysmorestuff.init.ModTabs; import com.stc.pattysmorestuff.tileentity.jar.TileEntityJar; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; /** * Created by StuffTheChicken on 21/07/2017. */ public class BlockJar extends Block implements ITileEntityProvider { private static final AxisAlignedBB BOUNDING_BOX = new AxisAlignedBB(0.0625 * 4, 0, 0.0625 * 4, 0.0625 * 12, 0.0625 * 11, 0.0625 * 12); private static final AxisAlignedBB COLLISION_BOX = new AxisAlignedBB(0.0625 * 3, 0, 0.0625 * 3, 0.0625 * 11, 0.0625 * 10, 0.6025 * 11); public BlockJar(String name) { super(Material.GLASS); this.setHardness(0.5F); this.setSoundType(SoundType.GLASS); this.setUnlocalizedName(name); this.setRegistryName(name); this.setCreativeTab(ModTabs.tabPattysDecoration); } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return BOUNDING_BOX; } public static AxisAlignedBB getCollisionBox() { return COLLISION_BOX; } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof IInventory) { InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory)tileentity); worldIn.updateComparatorOutputLevel(pos, this); } super.breakBlock(worldIn, pos, state); } @Override public void onBlockDestroyedByPlayer(World world, BlockPos pos, IBlockState state) { if (!world.isRemote) { for (int i = 0; i < getMetaFromState(state); i++) { EntityItem cookie = new EntityItem(world, pos.getX() + 0.5, pos.getY() + 0.8, pos.getZ() + 0.5, new ItemStack(Items.COOKIE)); world.spawnEntity(cookie); } } } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { TileEntity tileEntity = worldIn.getTileEntity(pos); if(tileEntity instanceof TileEntityJar) { TileEntityJar jar = (TileEntityJar) tileEntity; if(!worldIn.isRemote) { if (playerIn.getHeldItem(hand).getItem() == Items.COOKIE) { if(jar.addCookie()) { playerIn.getHeldItem(hand).splitStack(1); } }else if(playerIn.isSneaking()) { jar.removeCookie(); } } } return true; } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityJar(); } @Override public int getComparatorInputOverride(IBlockState state, World world, BlockPos pos) { TileEntityJar jar = (TileEntityJar) world.getTileEntity(pos); return jar.getSize(); } public Item createItemBlock() { return new ItemBlock(this).setRegistryName(getRegistryName()); } }
mit
marciojrtorres/poo-2017-1
15-polimorfismo/src/pkg15/Pedido.java
810
package pkg15; public class Pedido { private final IList<Venda> lista; public Pedido(IList<Venda> lista) { this.lista = lista; } public double getTotal() { double total = 0.0; for (int i = 0; i < lista.count(); i++) { // Produto p = (Produto) lista.get(i); // com parâmetro de tipo // a coerção não é mais necessária total += lista.get(i).getPreco(); } return total; } @Override public String toString() { String s = ""; for (int i = 0; i < lista.count(); i++) { s += lista.get(i) + "\n"; } s += "--------------------\n"; s += "total: " + this.getTotal(); return s; } }
mit
rkq/jexp
ut/src/main/java/com/github/rkq/jexp/ut/Calculator.java
290
package com.github.rkq.jexp.ut; /** * Created by rick on 8/19/15. */ public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } }
mit
RoyPy/15201-bogush
CarFactory/src/ru/nsu/ccfit/bogush/view/ButtonPanel.java
2655
package ru.nsu.ccfit.bogush.view; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ru.nsu.ccfit.bogush.CarFactoryModel; import ru.nsu.ccfit.bogush.Pauser; import ru.nsu.ccfit.bogush.factory.Supplier; import javax.swing.*; import java.util.Arrays; class ButtonPanel extends JPanel { private static final String START = "start"; private static final String PAUSE = "pause"; private static final String RESUME = "resume"; private JPanel panel; private FactoryView mainView; private JButton startButton; private JButton resetButton; private JCheckBox logSalesCheckBox; private Pauser pauser; private static final String LOGGER_NAME = "ButtonPanel"; private static final Logger logger = LogManager.getLogger(LOGGER_NAME); public ButtonPanel(CarFactoryModel model, FactoryView mainView) { this.mainView = mainView; logger.traceEntry(); startButton.setActionCommand(START); startButton.addActionListener(e -> { logger.trace("Start button: action command '" + e.getActionCommand() + '\''); if (START.equals(e.getActionCommand())) { startButton.setActionCommand(PAUSE); startButton.setText("Pause"); Thread thread; thread = model.getEngineSupplier().getThread(); logger.trace("start " + thread.getName()); thread.start(); thread = model.getBodySupplier().getThread(); logger.trace("start " + thread.getName()); thread.start(); for (Supplier supplier : model.getAccessorySuppliers()) { thread = supplier.getThread(); logger.trace("start " + thread.getName()); thread.start(); } model.getStore().start(); model.getCarFactory().getThreadPool().start(); model.getCarStorageController().start(); } else if (PAUSE.equals(e.getActionCommand())) { startButton.setActionCommand(RESUME); startButton.setText("Resume"); pauser.pause(); } else if (RESUME.equals(e.getActionCommand())) { startButton.setActionCommand(PAUSE); startButton.setText("Pause"); pauser.resume(); } else { logger.error("Shouldn't get here"); System.exit(1); } }); resetButton.addActionListener(e -> mainView.getControlPanel().reset()); logSalesCheckBox.setSelected(model.isLoggingSales()); logSalesCheckBox.addActionListener(e -> { logger.trace("logSales checkbox action"); model.toggleLoggingSales(); }); pauser = new Pauser(); pauser.addPausable(model.getBodySupplier()); pauser.addPausable(model.getEngineSupplier()); pauser.addPausables(Arrays.asList(model.getAccessorySuppliers())); pauser.addPausables(Arrays.asList(model.getStore().getDealers())); logger.traceExit(); } }
mit
kayler-renslow/arma-intellij-plugin
src/com/kaylerrenslow/armaplugin/stringtable/KeyConverter.java
1475
package com.kaylerrenslow.armaplugin.stringtable; import com.intellij.psi.PsiElement; import com.intellij.util.xml.ConvertContext; import com.intellij.util.xml.ResolvingConverter; import com.kaylerrenslow.armaplugin.lang.PsiUtil; import com.kaylerrenslow.armaplugin.lang.sqf.SQFFileType; import com.kaylerrenslow.armaplugin.lang.sqf.psi.SQFString; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; /** * @author Kayler * @since 12/10/2017 */ public class KeyConverter extends ResolvingConverter<SQFString> { @Override public boolean isReferenceTo(@NotNull PsiElement element, String stringValue, @Nullable SQFString resolveResult, ConvertContext context) { if (resolveResult == null) { return false; } if (element == resolveResult) { return true; } if (element.getText().equals(resolveResult.getText())) { return true; } return false; } @Nullable @Override public SQFString fromString(@Nullable String s, ConvertContext context) { return PsiUtil.createElement(context.getProject(), "\"" + s + "\"", SQFFileType.INSTANCE, SQFString.class); } @Nullable @Override public String toString(@Nullable SQFString string, ConvertContext context) { return string == null ? "" : string.getNonQuoteText(); } @NotNull @Override public Collection<? extends SQFString> getVariants(ConvertContext context) { return Collections.emptyList(); } }
mit
DeathPluto/-
easyworkdivision/src/main/java/com/zyxf/workdivision/LoginActivity.java
13656
package com.zyxf.workdivision; import android.app.Dialog; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.StringRequest; import com.google.gson.Gson; import com.umeng.socialize.controller.UMServiceFactory; import com.umeng.socialize.controller.UMSocialService; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.sso.QZoneSsoHandler; import com.umeng.socialize.sso.SinaSsoHandler; import com.umeng.socialize.sso.TencentWBSsoHandler; import com.umeng.socialize.sso.UMQQSsoHandler; import com.umeng.socialize.weixin.controller.UMWXHandler; import com.zyxf.workdivision.application.HalcyonApplication; import com.zyxf.workdivision.base.BaseActivity; import com.zyxf.workdivision.bean.response.Check; import com.zyxf.workdivision.config.Constants; import com.zyxf.workdivision.http.Urls; import com.zyxf.workdivision.manager.DialogManager; import com.zyxf.workdivision.utils.BrowserUtils; import com.zyxf.workdivision.utils.LogUtils; import com.zyxf.workdivision.utils.PreferenceUtils; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; /** * Created by DeathPluto on 2015/5/17. */ public class LoginActivity extends BaseActivity { private EditText accountEt; private EditText passwordEt; private boolean hasLogin = false; private Dialog progressDialog; private final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share"); private Dialog loginProgressDialog; @Override protected void initView() { checkLogin(); if (hasLogin) { startActivity(MainActivity.class); finish(); } setContentView(R.layout.activity_login); accountEt = (EditText) this.findViewById(R.id.et_account); passwordEt = (EditText) this.findViewById(R.id.et_password); initShare(); } private void initShare() { mController.setShareContent("易工分,http://www.umeng.com/social"); mController.setShareMedia(new UMImage(this, R.drawable.ic_launcher)); String appID = "wx967daebe835fbeac"; String appSecret = "5fa9e68ca3970e87a1f83e563c8dcbce"; // 添加微信平台 UMWXHandler wxHandler = new UMWXHandler(this, appID, appSecret); wxHandler.addToSocialSDK(); // 添加微信朋友圈 UMWXHandler wxCircleHandler = new UMWXHandler(this, appID, appSecret); wxCircleHandler.setToCircle(true); wxCircleHandler.addToSocialSDK(); //参数1为当前Activity,参数2为开发者在QQ互联申请的APP ID,参数3为开发者在QQ互联申请的APP kEY. UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "100424468", "c7394704798a158208a74ab60104f0ba"); qqSsoHandler.addToSocialSDK(); //参数1为当前Activity,参数2为开发者在QQ互联申请的APP ID,参数3为开发者在QQ互联申请的APP kEY. QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468", "c7394704798a158208a74ab60104f0ba"); qZoneSsoHandler.addToSocialSDK(); //设置新浪SSO handler mController.getConfig().setSsoHandler(new SinaSsoHandler()); //设置腾讯微博SSO handler mController.getConfig().setSsoHandler(new TencentWBSsoHandler()); } private void checkLogin() { hasLogin = PreferenceUtils.getBoolean(getApplicationContext(), Constants.HAS_LOGIN, false); Check check = (Check) mCache.getAsObject(Constants.CHECK); if (check != null && check.logined == true) { hasLogin = true; } else { progressDialog = DialogManager.showProgressDialog(this, "检测登陆中..."); StringRequest request = new StringRequest(Request.Method.GET, Urls.URL_CHECK_LOGIN, new Response.Listener<String>() { @Override public void onResponse(String s) { Gson gson = new Gson(); Check check = gson.fromJson(s, Check.class); LogUtils.i(check.toString()); mCache.put(Constants.CHECK, check); if (check.logined == true) { PreferenceUtils.putBoolean(getApplicationContext(), Constants.HAS_LOGIN, true); } if (progressDialog.isShowing()) { progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) { LogUtils.i("未检查到登陆\n" + volleyError.toString()); } if (progressDialog.isShowing()) { progressDialog.dismiss(); } } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> map = new HashMap<>(); String cookie = PreferenceUtils.getString(HalcyonApplication.getApplication(), Constants.COOKIE, ""); map.put("Cookie", cookie); return map; } }; mQueue.add(request); } } @Override protected void setListeners() { this.findViewById(R.id.ll_introduction).setOnClickListener(this); this.findViewById(R.id.ll_contact_us).setOnClickListener(this); this.findViewById(R.id.ll_share).setOnClickListener(this); this.findViewById(R.id.ll_shop).setOnClickListener(this); this.findViewById(R.id.tv_login).setOnClickListener(this); this.findViewById(R.id.tv_find_pwd).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll_introduction: startActivity(IntroduceActivity.class); break; case R.id.ll_contact_us: startActivity(ContactUsActivity.class); break; case R.id.ll_share: mController.openShare(this, false); break; case R.id.ll_shop: BrowserUtils.openWebSite(getApplicationContext(), Urls.URL_JD); break; case R.id.tv_login: login(); break; case R.id.tv_find_pwd: Toast.makeText(this, "请联系 18588206413 找回密码!", Toast.LENGTH_LONG).show(); break; } } private void login() { loginProgressDialog = DialogManager.showProgressDialog(this, "登陆中..."); final String account = accountEt.getText().toString().trim(); final String password = passwordEt.getText().toString().trim(); boolean isIDNum = account.length() == 18 ? true : false; if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) { passwordEt.setText(""); Toast.makeText(this, "账号或者密码不能为空!", Toast.LENGTH_SHORT).show(); return; } StringRequest workerRequest = new StringRequest(Request.Method.POST, Urls.URL_LOGIN_WORKER, new Response.Listener<String>() { @Override public void onResponse(String s) { passwordEt.setText(""); jumpAfterCheck(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) { LogUtils.i("workerRequest\n" + volleyError.toString()); } passwordEt.setText(""); if (loginProgressDialog.isShowing()) { loginProgressDialog.dismiss(); } Toast.makeText(getApplicationContext(), "账号或者密码错误,请重试", Toast.LENGTH_SHORT).show(); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<>(); map.put("id_string", account); // test "36112319850226193X" map.put("password", password);// test "123456" return map; } @Override protected String getParamsEncoding() { return "utf-8"; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { try { Map<String, String> responseHeaders = response.headers; String cookie = responseHeaders.get("Set-Cookie"); HalcyonApplication.setCookie(cookie); PreferenceUtils.putString(HalcyonApplication.getApplication(), Constants.COOKIE, cookie); String dataString = new String(response.data, "UTF-8"); return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } }; StringRequest leaderRequest = new StringRequest(Request.Method.POST, Urls.URL_LOGIN_LEADER, new Response.Listener<String>() { @Override public void onResponse(String s) { passwordEt.setText(""); jumpAfterCheck(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) { LogUtils.i("workerRequest\n" + volleyError.toString()); } passwordEt.setText(""); if (loginProgressDialog.isShowing()) { loginProgressDialog.dismiss(); } Toast.makeText(getApplicationContext(), "账号或者密码错误,请重试", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<>(); map.put("username", account); // test "李四" or "test" map.put("password", password);// test "123456" return map; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { try { Map<String, String> responseHeaders = response.headers; String cookie = responseHeaders.get("Set-Cookie"); HalcyonApplication.setCookie(cookie); PreferenceUtils.putString(HalcyonApplication.getApplication(), Constants.COOKIE, cookie); String dataString = new String(response.data, "UTF-8"); return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } @Override protected String getParamsEncoding() { return "utf-8"; } }; if (isIDNum) { mQueue.add(workerRequest); } else { mQueue.add(leaderRequest); } } private void jumpAfterCheck() { StringRequest request = new StringRequest(Request.Method.GET, Urls.URL_CHECK_LOGIN, new Response.Listener<String>() { @Override public void onResponse(String s) { Gson gson = new Gson(); Check check = gson.fromJson(s, Check.class); LogUtils.i(check.toString()); mCache.put(Constants.CHECK, check); if (check.logined == true) { PreferenceUtils.putBoolean(getApplicationContext(), Constants.HAS_LOGIN, true); } if (loginProgressDialog.isShowing()) { loginProgressDialog.dismiss(); } startActivity(MainActivity.class); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) { LogUtils.i("未检查到登陆\n" + volleyError.toString()); } if (loginProgressDialog.isShowing()) { loginProgressDialog.dismiss(); } } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> map = new HashMap<>(); String cookie = PreferenceUtils.getString(HalcyonApplication.getApplication(), Constants.COOKIE, ""); map.put("Cookie", cookie); return map; } }; mQueue.add(request); } }
mit
asofdate/batch-scheduler
auth/src/main/java/com/asofdate/utils/factory/RetMsgFactory.java
292
package com.asofdate.utils.factory; import com.asofdate.utils.RetMsg; /** * Created by hzwy23 on 2017/6/27. */ public final class RetMsgFactory { public static RetMsg getRetMsg(Integer code, String message, Object details) { return new RetMsg(code, message, details); } }
mit
jenkinsci/plasticscm-plugin
src/main/java/com/codicesoftware/plugins/hudson/commands/FindChangesetCommand.java
1898
package com.codicesoftware.plugins.hudson.commands; import com.codicesoftware.plugins.hudson.commands.parsers.FindOutputParser; import com.codicesoftware.plugins.hudson.model.ChangeSet; import com.codicesoftware.plugins.hudson.util.DateUtil; import com.codicesoftware.plugins.hudson.util.MaskedArgumentListBuilder; import hudson.FilePath; import java.io.IOException; import java.io.Reader; import java.text.ParseException; import java.util.List; public class FindChangesetCommand implements ParseableCommand<ChangeSet>, Command { private final int csetId; private final String branch; private final String repository; private final FilePath xmlOutputPath; public FindChangesetCommand( int csetId, String branch, String repository, FilePath xmlOutputPath) { this.csetId = csetId; this.branch = branch; this.repository = repository; this.xmlOutputPath = xmlOutputPath; } public MaskedArgumentListBuilder getArguments() { MaskedArgumentListBuilder arguments = new MaskedArgumentListBuilder(); arguments.add("find"); arguments.add("changeset"); arguments.add("where"); arguments.add("branch='" + branch + "'"); arguments.add("and"); arguments.add("changesetid=" + csetId); arguments.add("on"); arguments.add("repository"); arguments.add("'" + repository + "'"); arguments.add("--xml"); arguments.add("--file=" + xmlOutputPath.getRemote()); arguments.add("--dateformat=" + DateUtil.ISO_DATE_TIME_OFFSET_CSHARP_FORMAT); return arguments; } public ChangeSet parse(Reader reader) throws IOException, ParseException { List<ChangeSet> csetList = FindOutputParser.parseReader(xmlOutputPath); if (!csetList.isEmpty()) { return csetList.get(0); } return null; } }
mit
gencer/idea-php-symfony2-plugin
tests/fr/adrienbrault/idea/symfony2plugin/tests/twig/utils/TwigBlockUtilTest.java
3935
package fr.adrienbrault.idea.symfony2plugin.tests.twig.utils; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.templating.dict.TwigBlock; import fr.adrienbrault.idea.symfony2plugin.templating.path.TwigNamespaceSetting; import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil; import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyTempCodeInsightFixtureTestCase; import fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author Daniel Espendiller <daniel@espendiller.net> * @see fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil */ public class TwigBlockUtilTest extends SymfonyTempCodeInsightFixtureTestCase { /** * fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil#collectParentBlocks */ public void testVisit() { // skip for no fully project if(true) { return; } VirtualFile file = createFile("res/foo.html.twig", "{% extends \"foo1.html.twig\" %}{% block foo %}{% endblock %}"); createFile("res/foo1.html.twig", "{% block foo1 %}{% endblock %}"); PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(file); Settings.getInstance(getProject()).twigNamespaces.addAll(Collections.singletonList( new TwigNamespaceSetting(TwigUtil.MAIN, "res", true, TwigUtil.NamespaceType.ADD_PATH, true) )); Collection<TwigBlock> walk = TwigBlockUtil.collectParentBlocks(true, psiFile); assertNotNull(walk.stream().filter(twigBlock -> "foo".equals(twigBlock.getName())).findFirst().get()); assertNotNull(walk.stream().filter(twigBlock -> "foo1".equals(twigBlock.getName())).findFirst().get()); } /** * fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil#collectParentBlocks */ public void testVisitNotForSelf() { // skip for no fully project if(true) { return; } VirtualFile file = createFile("res/foo.html.twig", "{% extends \"foo1.html.twig\" %}{% block foo %}{% endblock %}"); createFile("res/foo1.html.twig", "{% block foo1 %}{% endblock %}"); PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(file); Settings.getInstance(getProject()).twigNamespaces.addAll(Collections.singletonList( new TwigNamespaceSetting(TwigUtil.MAIN, "res", true, TwigUtil.NamespaceType.ADD_PATH, true) )); Collection<TwigBlock> walk = TwigBlockUtil.collectParentBlocks(false, psiFile); assertEquals(0, walk.stream().filter(twigBlock -> "foo".equals(twigBlock.getName())).count()); assertNotNull(walk.stream().filter(twigBlock -> "foo1".equals(twigBlock.getName())).findFirst().get()); } /** * fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil#collectParentBlocks */ public void testWalkWithSelf() { // skip for no fully project if(true) { return; } VirtualFile file = createFile("res/foo.html.twig", "{% extends \"foo1.html.twig\" %}{% block foo %}{% endblock %}"); createFile("res/foo1.html.twig", "{% block foo1 %}{% endblock %}"); PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(file); Settings.getInstance(getProject()).twigNamespaces.addAll(Collections.singletonList( new TwigNamespaceSetting(TwigUtil.MAIN, "res", true, TwigUtil.NamespaceType.ADD_PATH, true) )); Collection<TwigBlock> walk = TwigBlockUtil.collectParentBlocks(true, psiFile); assertEquals(1, walk.stream().filter(twigBlock -> "foo".equals(twigBlock.getName())).count()); assertNotNull(walk.stream().filter(twigBlock -> "foo1".equals(twigBlock.getName())).findFirst().get()); } }
mit
yogoloth/jmxtrans
jmxtrans-core/src/main/java/com/googlecode/jmxtrans/monitoring/ThreadPoolExecutorMXBean.java
1683
/** * The MIT License * Copyright (c) 2010 JmxTrans team * * 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.googlecode.jmxtrans.monitoring; import javax.management.ObjectName; public interface ThreadPoolExecutorMXBean { boolean allowsCoreThreadTimeOut(); int getActiveCount(); long getCompletedTaskCount(); int getCorePoolSize(); long getKeepAliveTimeSeconds(); int getLargestPoolSize(); int getMaximumPoolSize(); int getPoolSize(); long getTaskCount(); boolean isShutdown(); boolean isTerminated(); boolean isTerminating(); int workQueueRemainingCapacity(); int workQueueSize(); ObjectName getObjectName(); }
mit
spoluyan/brain-games
src/main/java/pw/spn/quizgame/repository/RightAnswerRepository.java
291
package pw.spn.quizgame.repository; import org.springframework.data.mongodb.repository.MongoRepository; import pw.spn.quizgame.domain.RightAnswer; public interface RightAnswerRepository extends MongoRepository<RightAnswer, String> { RightAnswer findByQuestionId(String questionId); }
mit
pablopdomingos/nfse
nfse-bh/src/main/java/com/pablodomingos/classes/rps/builders/TomadorCpfCnpjBuilder.java
710
package com.pablodomingos.classes.rps.builders; import com.pablodomingos.classes.rps.RpsTomadorCpfCnpj; public class TomadorCpfCnpjBuilder extends AbstractBuilder<RpsTomadorCpfCnpj>{ private String cpf; private String cnpj; public TomadorCpfCnpjBuilder() {} public TomadorCpfCnpjBuilder comDocumento(String documento) { if(documento.length() == 11){ this.cpf = documento; }else{ this.cnpj = documento; } return this; } @Override protected RpsTomadorCpfCnpj buildInternal() { return new RpsTomadorCpfCnpj(this); } public String getCpf() { return cpf; } public String getCnpj() { return cnpj; } }
mit
KROKIteam/KROKI-CERIF-Model
CerifModel/WebApp/src_gen/ejb_generated/CfIndicConstraints.java
290
package ejb_generated; import adapt.exceptions.InvariantException; public class CfIndicConstraints extends CfIndic{ private String objectName; public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } }
mit
DanielsCodeStash/Fyrchan
src/util/ResourceUtil.java
562
package util; import javafx.scene.image.Image; import java.io.InputStream; public class ResourceUtil { public static Image getImage(String filename) { boolean runningFromJar = ResourceUtil.class.getResource("ResourceUtil.class").toString().startsWith("jar:"); if (runningFromJar) { InputStream iconStream = ResourceUtil.class.getResourceAsStream("/res/" + filename); return new Image(iconStream); } else { return new Image("file:res/" + filename); } } }
mit
NucleusPowered/QuickStartModuleLoader
src/main/java/uk/co/drnaylor/quickstart/exceptions/MultiException.java
1099
/* * This file is part of QuickStart Module Loader, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package uk.co.drnaylor.quickstart.exceptions; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class MultiException extends Exception { private final List<Exception> exceptionList; public MultiException(Exception... exceptions) { this(Arrays.asList(exceptions)); } public MultiException(List<Exception> exceptionList) { this.exceptionList = exceptionList; } @Override public String getMessage() { return this.exceptionList.stream().map(Throwable::getMessage).collect(Collectors.joining(System.lineSeparator())); } @Override public void printStackTrace(PrintStream s) { this.exceptionList.forEach(x -> x.printStackTrace(s)); } @Override public void printStackTrace(PrintWriter s) { this.exceptionList.forEach(x -> x.printStackTrace(s)); } }
mit
lichader/Alfred
src/main/java/com/lichader/alfred/metroapi/v3/model/DisruptionDirection.java
456
package com.lichader.alfred.metroapi.v3.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by lichader on 14/6/17. */ public class DisruptionDirection { @JsonProperty("route_direction_id") public int RouteDirectionId; @JsonProperty("direction_id") public int DirectionId; @JsonProperty("direction_name") public String DirectionName; @JsonProperty("service_time") public String ServiceTime; }
mit
teamnovember/CareersFromHere
app/helpers/AdminHelpers.java
2010
package helpers; import models.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by el on 21/02/15. */ public abstract class AdminHelpers { public static Map<String, Boolean> ConstructDiscriminatorMap(String currentDiscriminator,String authorisation) { Map<String, Boolean> discrMap = new HashMap<String, Boolean>(); discrMap.put("student", "student".equals(currentDiscriminator)); discrMap.put("alumni", "alumni".equals(currentDiscriminator)); discrMap.put("admin", "admin".equals(currentDiscriminator)); if(authorisation.equals("superadmin")) { discrMap.put("superadmin", "superadmin".equals(currentDiscriminator)); } return discrMap; } public static Map<String, Boolean> ConstructSchoolMap(String selectedSchoolName,boolean authorisation) { Map<String, Boolean> schoolMap = new HashMap<String, Boolean>(); SchoolDAO dao = new SchoolDAO(); for(School school : dao.getAllSchool()) { if(school.getId() != 0 || authorisation) { //this is to hide the default school when we don't want to see it (i.e everywhere where we can add users to it) schoolMap.put(school.getName(), school.getName().equals(selectedSchoolName)); } } return schoolMap; } public static Map<String, Boolean> ConstructCategoryMap(List<Category> existingCats) { Map<String, Boolean> catMap = new HashMap<String, Boolean>(); CategoryDAO cdao = new CategoryDAO(); for(Category c : cdao.getAllCategories()) { catMap.put(c.getName(), existingCats.contains(c)); } return catMap; } public static boolean CategoryContains(List<Category> cats, Category cat) { if(cats == null || cat == null) return false; for(Category c : cats) { if(cat.getName().equals(c.getName())) return true; } return false; } }
mit
nishimotz/caststudio
src/com/nishimotz/mmm/cuesheet/CueSheet.java
9868
/* * $Id: CueSheet.java,v 1.2 2009/05/18 01:30:28 nishi Exp $ */ package com.nishimotz.mmm.cuesheet; //TODO: fade-in/fade-out操作 //TODO: sheet 本体と clock の実装の分離? //TODO: 複数のキューシートのデータモデルを切り替えできる? //TODO: キューシートの分割?階層化、入れ子にする? // CueSheetData 内の MediaItem の描画は CastStudio が行っている import java.awt.Graphics; import java.util.ArrayList; //import java.util.Collections; //import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Queue; //import java.util.logging.Logger; import com.nishimotz.mmm.caster.SystemTimeProvider; import com.nishimotz.mmm.mediaitem.MediaItem; import com.nishimotz.mmm.porter.Porter; import com.nishimotz.mmm.sheet.AbstractSheet; import com.nishimotz.util.StringUtil; public class CueSheet extends AbstractSheet { // protected Logger logger = CastStudio.logger; private CueSheetData data; private boolean cueSheetPlaying = false; private double totalDuration = 0.0; private double currentCueSheetTime = 0.0; private double startedTime = 0.0; private double finishTime = 0.0; private Porter recycler; private Porter stickerHolder; private Queue<MediaItem> mediaItemQueue = new LinkedList<MediaItem>(); private MediaItem currMediaItem = null; private MediaItem prevMediaItem = null; private double currMediaItemFinishTime = 0.0; private boolean loopMode; private boolean needRepaint = false; /** */ public CueSheet() { super(); view = new CueSheetView(); data = new CueSheetData(); } public void setRecycler(Porter r) { recycler = r; } public void setStickerHolder(Porter s) { stickerHolder = s; } private boolean isMediaItemsNull() { return (data.getMediaItems() == null); } private void clearMediaItems() { data.getMediaItems().clear(); } private void addMediaItems(MediaItem mi) { data.getMediaItems().add(mi); } private int sizeMediaItems() { return data.getMediaItems().size(); } private MediaItem getMediaItem(int n) { return data.getMediaItems().get(n); } // Y座標でソートして Play List を作る public synchronized void updateTotalTime(List<MediaItem> castStudioMediaItems) { if (isMediaItemsNull()) return; // Iterator の同期化 synchronized (castStudioMediaItems) { totalDuration = 0.0; // mediaItems.clear(); clearMediaItems(); for (MediaItem mi : castStudioMediaItems) { if (view.isInside(mi)) { // mediaItems.add(mi); addMediaItems(mi); totalDuration += mi.getMediaDuration(); } } } sortMediaItems(); } public String getClockMessage1() { double remainSec = 0.0; if (cueSheetPlaying) { remainSec = Math.ceil(finishTime) - Math.floor(currentCueSheetTime); } else { remainSec = Math.ceil(totalDuration); } if (remainSec < 0.0) { remainSec = 0.0; } String msg = StringUtil.formatTime(remainSec); if (loopMode) { msg += "L"; } return msg; } public String getClockMessage2() { double erapsedSec = Math.floor(currentCueSheetTime) - Math.floor(startedTime); if (erapsedSec < 0.0) { erapsedSec = 0.0; } double totalSec = 0.0; if (cueSheetPlaying) { totalSec = Math.ceil(finishTime) - Math.floor(startedTime); } else { totalSec = Math.ceil(totalDuration); } if (totalSec < 0.0) { totalSec = 0.0; } String msg = StringUtil.formatTime(erapsedSec) + " / " + StringUtil.formatTime(totalSec); return msg; } // syncStart をかける private synchronized void playCueSheet() { if (! isCueSheetPlaying()) { setCueSheetPlaying(true); startedTime = SystemTimeProvider.getSystemTime(); totalDuration = 0.0; double start = startedTime; logger.info("syncStart now = " + startedTime); for (int size = sizeMediaItems(), i = 0; i < size; i++) { MediaItem mi = getMediaItem(i); double duration = mi.getMediaDuration(); mediaItemQueue.offer(mi); // 可能な場合、要素をキューに挿入 start += duration; totalDuration += duration; } finishTime = startedTime + totalDuration; } } private synchronized void stopCueSheet() { if (isMediaItemsNull()) return; if (isCueSheetPlaying()) { if (currMediaItem != null) { currMediaItem.stop(); currMediaItemFinishTime = 0.0; currMediaItem = null; } mediaItemQueue.clear(); startedTime = 0.0; finishTime = 0.0; currentCueSheetTime = 0.0; logger.info("stopCueSheet done."); setCueSheetPlaying(false); needRepaint = true; } } private void sortMediaItems() { data.sortMediaItemsByPosY(); } public boolean isCueSheetPlaying() { return cueSheetPlaying; } public void setCueSheetPlaying(boolean cueSheetPlaying) { this.cueSheetPlaying = cueSheetPlaying; if (cueSheetPlaying == false) { if (currMediaItem != null) { currMediaItem.stop(); } currMediaItemFinishTime = 0.0; prevMediaItem = currMediaItem; currMediaItem = null; } } public double getTotalDuration() { return totalDuration; } public void drawCueSheet(Graphics ct) { ((CueSheetView) view).drawSheet(this, ct); } @Override public void onClick() { if (isCueSheetPlaying()) { stopCueSheet(); } else { if (sizeMediaItems() > 0) { playCueSheet(); } } } public void onClickByRightButton() { if (loopMode) { loopMode = false; } else { loopMode = true; } } public synchronized void finishCueSheet() { for (int size = sizeMediaItems(), i = 0; i < size; i++) { MediaItem mi = getMediaItem(i); mi.stop(); removeMediaItem(mi); } startedTime = 0.0; currentCueSheetTime = 0.0; totalDuration = 0.0; finishTime = 0.0; setCueSheetPlaying(false); ArrayList<MediaItem> stickers = new ArrayList<MediaItem>(); ArrayList<MediaItem> messages = new ArrayList<MediaItem>(); for (int size = sizeMediaItems(), i = 0; i < size; i++) { MediaItem mi = getMediaItem(i); mi.resetCastDone(); if (mi.isSticker()) { stickers.add(mi); } else { messages.add(mi); } } stickerHolder.doLayoutMediaItems(stickers); recycler.doLayoutMediaItems(messages); // recycler.unloadMediaItems(messages); clearMediaItems(); } private synchronized void restartCueSheet() { currentCueSheetTime = 0.0; startedTime = SystemTimeProvider.getSystemTime(); totalDuration = 0.0; double start = startedTime; logger.info("syncStart now = " + startedTime); for (int size = sizeMediaItems(), i = 0; i < size; i++) { MediaItem mi = getMediaItem(i); double duration = mi.getMediaDuration(); mediaItemQueue.offer(mi); // 可能な場合、要素をキューに挿入 start += duration; totalDuration += duration; } finishTime = startedTime + totalDuration; } public synchronized void doTimerTask() { if (cueSheetPlaying) { // update currentCueSheetTime currentCueSheetTime = SystemTimeProvider.getSystemTime(); // finish last item if (currMediaItem != null) { logger.info("doTimerTask : finishTime=" + currMediaItemFinishTime + " cueSheetTime=" + currentCueSheetTime); if (currMediaItemFinishTime < currentCueSheetTime) { currMediaItem.stop(); currMediaItemFinishTime = 0.0; prevMediaItem = currMediaItem; currMediaItem = null; } } // play next item if (currMediaItem == null) { currMediaItem = mediaItemQueue.poll(); // キューの先頭を取得および削除 if (currMediaItem != null) { currMediaItemFinishTime = currentCueSheetTime + currMediaItem.getMediaDuration(); currMediaItem.syncStart(currentCueSheetTime); } } if (mediaItemQueue.isEmpty() && currMediaItem == null) { logger.info("CueSheet mediaItemQueue.isEmpty && currMediaItem == null"); if (prevMediaItem.isCastDone()) { logger.info("CueSheet lastItemDone"); prevMediaItem.resetCastDone(); if (loopMode) { restartCueSheet(); } else { finishCueSheet(); } } needRepaint = true; } } else { currentCueSheetTime = 0.0; } } // public synchronized boolean isAddMediaItemAllowed(MediaItem mi) { // if (cueSheetPlaying) { // if (currMediaItem.getPosY() < mi.getPosY()) { // return true; // } else { // return false; // } // } // return true; // } public synchronized void addMediaItem(MediaItem mi) { logger.info("addMediaItem : " + mi.toString()); if (cueSheetPlaying) { if (currMediaItem == null) { logger.info("currMediaItem == null"); return; } if (currMediaItem.getPosY() < mi.getPosY()) { MediaItem mi1; while((mi1 = mediaItemQueue.poll()) != null) { totalDuration -= mi1.getMediaDuration(); finishTime -= mi1.getMediaDuration(); } mediaItemQueue.clear(); sortMediaItems(); for (int size = sizeMediaItems(), i = 0; i < size; i++) { MediaItem mi2 = getMediaItem(i); if (currMediaItem.getPosY() < mi2.getPosY()) { mediaItemQueue.offer(mi2); totalDuration += mi2.getMediaDuration(); finishTime += mi2.getMediaDuration(); } } } else { // 挿入失敗にするべき? } } } public synchronized void removeMediaItem(MediaItem mi) { logger.info("removeMediaItem : " + mi.toString()); if (cueSheetPlaying && mediaItemQueue.contains(mi)) { mediaItemQueue.remove(mi); totalDuration -= mi.getMediaDuration(); finishTime -= mi.getMediaDuration(); } } public void setHoverMode(int x, int y) { view.setHoverMode(x,y); } public void resetHoverMode() { view.resetHoverMode(); } public boolean needRepaint() { if (this.cueSheetPlaying || this.needRepaint) { this.needRepaint = false; return true; } return false; } }
mit
ajitsing/RubyGemsAndroidApp
app/src/main/java/com/singhajit/rubygems/core/StringResolver.java
407
package com.singhajit.rubygems.core; import android.content.Context; import android.support.annotation.StringRes; public class StringResolver { private final Context context; public StringResolver(Context context) { this.context = context; } public String getString(@StringRes int resourceId, Object... args) { Object[] arg = args; return context.getString(resourceId, args); } }
mit
RodrigoQuesadaDev/XGen4J
xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/organization/packages/packagesForErrorsAreGeneratedFromErrorNames_specialCases/Information.java
10077
package com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases; import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.ErrorInfo.CustomMessageGeneratorErrorDescription; import com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.ErrorInfo.PlainTextErrorDescription; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; /** * Autogenerated by XGen4J on January 1, 0001. */ public class Information { private static List<ErrorInfo> errorInfoList; private static Map<String, ErrorInfo> idToErrorInfoMap; private static final AtomicBoolean loaded = new AtomicBoolean(); private static void load() { if (loaded.compareAndSet(false, true)) { errorInfoList = new ArrayList<>(); idToErrorInfoMap = new HashMap<>(); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameError.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameException.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.RootNameError.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.ErrorName1Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.ErrorName2Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_1_.Error_Name_9_Name3_1_Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_2_.Error_Name_9_Name3_2_Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_3__.Error__Name__9__Name3_3__Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error__name__9__name3_4__.Error__Name__9__Name3_4__Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error___name___9___name3_5___.Error___Name___9___Name3_5___Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_6.Error_name_9_name3_6Error.CODE, false )); errorInfoList.add(new ErrorInfo( com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Error.class, new ExceptionInfo(com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Exception.TYPE, com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Exception.class), com.rodrigodev.xgen4j.test.organization.packages.packagesForErrorsAreGeneratedFromErrorNames_specialCases.error_name1.error_name2.error_name_9_name3_7.Error_name_9_name3_7Error.CODE, false )); errorInfoList = Collections.unmodifiableList(errorInfoList); for (ErrorInfo errorInfo : errorInfoList) { idToErrorInfoMap.put(errorInfo.code().id(), errorInfo); } loaded.set(true); } } public static List<ErrorInfo> list() { load(); return errorInfoList; } public static ErrorInfo forId(String id) { if (id == null) throw new IllegalArgumentException("id"); load(); return idToErrorInfoMap.get(id); } }
mit
liufeiit/mysql-binlog-connector-java
src/test/java/com/mysql/binlog/CountDownEventListener.java
4054
/* * Copyright 2013 Stanley Shyiko * * 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.mysql.binlog; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import com.mysql.binlog.event.Event; import com.mysql.binlog.event.EventData; import com.mysql.binlog.event.EventType; /** * @author <a href="mailto:stanley.shyiko@gmail.com">Stanley Shyiko</a> */ public class CountDownEventListener implements BinaryLogClient.EventListener { private final Map<EventType, AtomicInteger> countersByType = new HashMap<EventType, AtomicInteger>(); private final Map<Class<? extends EventData>, AtomicInteger> countersByDataClass = new HashMap<Class<? extends EventData>, AtomicInteger>(); @Override public void onEvent(Event event) { incrementCounter(getCounter(countersByType, event.getHeader().getEventType())); EventData data = event.getData(); if (data != null) { incrementCounter(getCounter(countersByDataClass, data.getClass())); } } private <K> AtomicInteger getCounter(Map<K, AtomicInteger> counterMap, K key) { synchronized (counterMap) { AtomicInteger counter = counterMap.get(key); if (counter == null) { counterMap.put(key, counter = new AtomicInteger()); } return counter; } } private void incrementCounter(AtomicInteger counter) { synchronized (counter) { if (counter.incrementAndGet() == 0) { counter.notify(); } } } public void waitFor(EventType eventType, int numberOfEvents, long timeoutInMilliseconds) throws TimeoutException, InterruptedException { waitForCounterToGetZero(eventType.name(), getCounter(countersByType, eventType), numberOfEvents, timeoutInMilliseconds); } public void waitFor(Class<? extends EventData> dataClass, int numberOfEvents, long timeoutInMilliseconds) throws TimeoutException, InterruptedException { waitForCounterToGetZero(dataClass.getSimpleName(), getCounter(countersByDataClass, dataClass), numberOfEvents, timeoutInMilliseconds); } private void waitForCounterToGetZero(String counterName, AtomicInteger counter, int numberOfExpectedEvents, long timeoutInMilliseconds) throws TimeoutException, InterruptedException { synchronized (counter) { counter.set(counter.get() - numberOfExpectedEvents); if (counter.get() != 0) { counter.wait(timeoutInMilliseconds); if (counter.get() != 0) { throw new TimeoutException("Received " + (numberOfExpectedEvents + counter.get()) + " " + counterName + " event(s) instead of expected " + numberOfExpectedEvents); } } } } public void reset() { synchronized (countersByType) { countersByType.clear(); } synchronized (countersByDataClass) { countersByDataClass.clear(); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("CountDownEventListener"); sb.append("{countersByType=").append(countersByType); sb.append(", countersByDataClass=").append(countersByDataClass); sb.append('}'); return sb.toString(); } }
mit
oneill011990/FastTravelReborn
src/main/java/de/germanspacebuild/plugins/fasttravel/data/FastTravelSign.java
5866
/* * The MIT License (MIT) * * Copyright (c) 2011-2016 CraftyCreeper, minebot.net, oneill011990 * * 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 de.germanspacebuild.plugins.fasttravel.data; import de.germanspacebuild.plugins.fasttravel.util.BlockUtil; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.material.Sign; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by oneill011990 on 03.03.2016 * for FastTravelReborn * * @author oneill011990 */ public class FastTravelSign implements Comparable<FastTravelSign> { private String name; private Location tpLoc; private Location signLoc; private Boolean automatic = false; private double price; private int range; private UUID creator; private List<UUID> players; private Boolean marker = false; /** * Constructor for sign without price. * * @param name Name of sign. * @param creator Lame of creator. * @param block Location of sign. */ public FastTravelSign(String name, UUID creator, Block block) { this.name = name; this.creator = creator; this.price = 0; this.range = 0; this.players = new ArrayList<>(); this.setAutomatic(false); this.signLoc = block.getLocation(); Sign s = (Sign) block.getState().getData(); this.signLoc.setYaw((float) BlockUtil.getYawForFace(s.getFacing())); this.tpLoc = signLoc; } /** * Constructor for sign with price. * * @param name Name of sign. * @param creator Name of creator. * @param price Price for travel. * @param location Location of sign. * @param tpLoc Travel destination. * @param automatic Accessible for all players? * @param players Players that can use this sign. */ public FastTravelSign(String name, UUID creator, double price, Location location, Location tpLoc, boolean automatic, int range, boolean marker, List<UUID> players) { this.name = name; this.creator = creator; this.price = price; this.range = range; this.players = players; this.setAutomatic(automatic); this.signLoc = location; this.tpLoc = tpLoc; this.marker = marker; } public void addPlayer(UUID player) { players.add(player); FastTravelDB.save(); } public void clearPlayers() { players.clear(); FastTravelDB.save(); } public void removePlayer(UUID player) { players.remove(player); FastTravelDB.save(); } public boolean foundBy(UUID player) { return players.contains(player); } @Override public int compareTo(FastTravelSign sign) { return this.name.toLowerCase().compareTo(sign.getName().toLowerCase()); } public String getName() { return name; } public void setName(String name) { this.name = name; FastTravelDB.save(); } public Location getTPLocation() { return tpLoc; } public void setTPLocation(Location tpLoc) { this.tpLoc = tpLoc; FastTravelDB.save(); } public Location getSignLocation() { return signLoc; } public void setSignLocation(Location signLoc) { this.signLoc = signLoc; FastTravelDB.save(); } public Boolean isAutomatic() { return automatic; } public void setAutomatic(Boolean automatic) { this.automatic = automatic; FastTravelDB.save(); } public double getPrice() { return price; } public void setPrice(float price) { this.price = price; FastTravelDB.save(); } public int getRange() { return range; } public void setRange(int range) { this.range = range; FastTravelDB.save(); } public UUID getCreator() { return creator; } public void setCreator(UUID creator) { this.creator = creator; FastTravelDB.save(); } public List<UUID> getPlayers() { return players; } public Boolean hasMarker() { return marker; } public void setMarked(Boolean marker) { this.marker = marker; FastTravelDB.save(); } @Override public String toString() { return "FastTravelSign{" + "name='" + name + '\'' + ", tpLoc=" + tpLoc + ", signLoc=" + signLoc + ", automatic=" + automatic + ", price=" + price + ", range=" + range + ", creator=" + creator + ", players=" + players + ", marker=" + marker + '}'; } }
mit
alexeytokar/rainbow-rest
filters/src/main/java/ua/net/tokar/json/rainbowrest/Include.java
1474
package ua.net.tokar.json.rainbowrest; import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.stream.Collectors; public class Include { private final String includeFieldName; private final Collection<Param> requestParams = new ArrayList<>(); public Include( String includeFieldName, String requestParams ) { this.includeFieldName = includeFieldName; if ( StringUtils.isNotEmpty( requestParams ) ) { this.requestParams.addAll( parseRequestParamsFromInclude( requestParams ) ); } } private Collection<Param> parseRequestParamsFromInclude( String requestParams ) { return Arrays.stream( requestParams.split( "," ) ) .map( param -> { String[] nameValue = param.split( ":" ); if ( nameValue.length != 2 ) { return null; } return new Param( nameValue[0], nameValue[1] ); } ) .filter( Objects::nonNull ) .collect( Collectors.toList() ); } public String getIncludeFieldName() { return includeFieldName; } public Collection<Param> getRequestParams() { return Collections.unmodifiableCollection( requestParams ); } }
mit
santiwst/thinkinjava
src/main/java/com/thinkinjava/holding/AddingGroups.java
741
package com.thinkinjava.holding; import java.util.*; public class AddingGroups { public static void main(String[] args) { Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1, 3, 5, 7)); Integer[] moreInts = {4, 5, 6}; collection.addAll(Arrays.asList(moreInts)); System.out.println(collection); Collections.addAll(collection, 20, 21); Collections.addAll(collection, new Integer[]{7, 8, 9}); System.out.println(collection); List<Integer> list = Arrays.asList(moreInts); System.out.println(list); list.set(0, 10); System.out.println(list); // RuntimeError: UnsupportedOperationException // list.add(41); } }
mit
akiress/compilers
prog5/Tree/CJUMP.java
925
package Tree; import Temp.Temp; import Temp.Label; public class CJUMP extends Stm { public int relop; public Exp left, right; public Label iftrue, iffalse; public CJUMP(int rel, Exp l, Exp r, Label t, Label f) { relop=rel; left=l; right=r; iftrue=t; iffalse=f; } public final static int EQ=0, NE=1, LT=2, GT=3, LE=4, GE=5, ULT=6, ULE=7, UGT=8, UGE=9; public ExpList kids() {return new ExpList(left, new ExpList(right,null));} public Stm build(ExpList kids) { return new CJUMP(relop,kids.head,kids.tail.head,iftrue,iffalse); } public static int notRel(int relop) { switch (relop) { case EQ: return NE; case NE: return EQ; case LT: return GE; case GE: return LT; case GT: return LE; case LE: return GT; case ULT: return UGE; case UGE: return ULT; case UGT: return ULE; case ULE: return UGT; default: throw new Error("bad relop in CJUMP.notRel"); } } }
mit
reactivesw/customer_server
src/main/java/io/reactivesw/order/cart/infrastructure/enums/InventoryMode.java
914
package io.reactivesw.order.cart.infrastructure.enums; /** * Values of the InventoryMode enumeration: * Created by umasuo on 16/11/17. */ public enum InventoryMode { /** * Orders are tracked on inventory. That means, ordering a LineItem will decrement the available * quantity on the respective InventoryEntry. Creating an order will succeed even if the line * item’s available quantity is zero or negative. But creating an order will fail with an * OutOfStock error if no matching inventory entry exists for a line item. */ TrackOnly, /** * Creating an order will fail with an OutOfStock error if an unavailable line item exists. Line * items in the cart are only reserved for the duration of the ordering transaction. */ ReserveOnOrder, /** * Adding items to cart and ordering is independent of inventory. No inventory checks or * modifications. */ None; }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/fluent/models/MicrosoftGraphInternetMessageHeader.java
3263
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.authorization.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.HashMap; import java.util.Map; /** internetMessageHeader. */ @Fluent public final class MicrosoftGraphInternetMessageHeader { @JsonIgnore private final ClientLogger logger = new ClientLogger(MicrosoftGraphInternetMessageHeader.class); /* * Represents the key in a key-value pair. */ @JsonProperty(value = "name") private String name; /* * The value in a key-value pair. */ @JsonProperty(value = "value") private String value; /* * internetMessageHeader */ @JsonIgnore private Map<String, Object> additionalProperties; /** * Get the name property: Represents the key in a key-value pair. * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: Represents the key in a key-value pair. * * @param name the name value to set. * @return the MicrosoftGraphInternetMessageHeader object itself. */ public MicrosoftGraphInternetMessageHeader withName(String name) { this.name = name; return this; } /** * Get the value property: The value in a key-value pair. * * @return the value value. */ public String value() { return this.value; } /** * Set the value property: The value in a key-value pair. * * @param value the value value to set. * @return the MicrosoftGraphInternetMessageHeader object itself. */ public MicrosoftGraphInternetMessageHeader withValue(String value) { this.value = value; return this; } /** * Get the additionalProperties property: internetMessageHeader. * * @return the additionalProperties value. */ @JsonAnyGetter public Map<String, Object> additionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: internetMessageHeader. * * @param additionalProperties the additionalProperties value to set. * @return the MicrosoftGraphInternetMessageHeader object itself. */ public MicrosoftGraphInternetMessageHeader withAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; return this; } @JsonAnySetter void withAdditionalProperties(String key, Object value) { if (additionalProperties == null) { additionalProperties = new HashMap<>(); } additionalProperties.put(key, value); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
graphiq-data/pdi-uniquelist-plugin
test-src/com/graphiq/kettle/steps/uniquelist/TestUtilities.java
12320
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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.graphiq.kettle.steps.uniquelist; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.Random; import org.pentaho.di.core.Const; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.core.plugins.StepPluginType; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.dummytrans.DummyTransMeta; import org.pentaho.di.trans.steps.injector.InjectorMeta; import org.pentaho.di.trans.steps.sort.SortRowsMeta; public class TestUtilities { private static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; /** * Return the end of line character based on value returned by getFileFormat. * * @return the end of line character sequence */ public static String getEndOfLineCharacters() { return ( getFileFormat().equalsIgnoreCase( "DOS" ) ? "\r\n" : "\n" ); } /** * Return the file format based on the OS type. We set the file format to DOS if it is Windows since that is the only * Windows file type that shows up in the TextFileInput dialog. * * @return String the file format */ public static String getFileFormat() { if ( System.getProperty( "os.name" ).startsWith( "Windows" ) ) { return "DOS"; } else { return "Unix"; } } /** * Check the 2 lists comparing the rows in order. If they are not the same fail the test. * * @param rows1 set 1 of rows to compare * @param rows2 set 2 of rows to compare * @throws TestFailedException */ public static void checkRows( List<RowMetaAndData> rows1, List<RowMetaAndData> rows2 ) throws TestFailedException { // we call this passing in -1 as the fileNameColumn checkRows( rows1, rows2, -1 ); } /** * Check the 2 lists comparing the rows in order. If they are not the same fail the test. * * @param rows1 set 1 of rows to compare * @param rows2 set 2 of rows to compare * @param fileNameColumn Number of the column containing the filename. This is only checked for being non-null (some * systems maybe canonize names differently than we input). */ public static void checkRows( List<RowMetaAndData> rows1, List<RowMetaAndData> rows2, int fileNameColumn ) throws TestFailedException { int idx = 1; if ( rows1.size() != rows2.size() ) { throw new TestFailedException( "Number of rows is not the same: " + rows1.size() + " and " + rows2.size() ); } Iterator<RowMetaAndData> itrRows1 = rows1.iterator(); Iterator<RowMetaAndData> itrRows2 = rows2.iterator(); while ( itrRows1.hasNext() && itrRows2.hasNext() ) { RowMetaAndData rowMetaAndData1 = itrRows1.next(); RowMetaAndData rowMetaAndData2 = itrRows2.next(); RowMetaInterface rowMetaInterface1 = rowMetaAndData1.getRowMeta(); Object[] rowObject1 = rowMetaAndData1.getData(); Object[] rowObject2 = rowMetaAndData2.getData(); if ( rowMetaAndData1.size() != rowMetaAndData2.size() ) { throw new TestFailedException( "row number " + idx + " is not equal" ); } int[] fields = new int[ rowMetaInterface1.size() ]; for ( int ydx = 0; ydx < rowMetaInterface1.size(); ydx++ ) { fields[ ydx ] = ydx; } if ( fileNameColumn > 0 ) { try { rowObject1[ fileNameColumn ] = rowObject2[ fileNameColumn ]; if ( rowMetaAndData1.getRowMeta().compare( rowObject1, rowObject2, fields ) != 0 ) { throw new TestFailedException( "row nr " + idx + " is not equal" ); } } catch ( KettleValueException e ) { throw new TestFailedException( "row nr " + idx + " is not equal" ); } } idx++; } } /** * Creates a dummy * * @param name * @param pluginRegistry * @return StepMata */ public static synchronized StepMeta createDummyStep( String name, PluginRegistry pluginRegistry ) { DummyTransMeta dummyTransMeta = new DummyTransMeta(); String dummyPid = pluginRegistry.getPluginId( StepPluginType.class, dummyTransMeta ); StepMeta dummyStep = new StepMeta( dummyPid, name, dummyTransMeta ); return dummyStep; } /** * Create an injector step. * * @param name * @param pluginRegistry * @return StepMeta */ public static synchronized StepMeta createInjectorStep( String name, PluginRegistry pluginRegistry ) { // create an injector step... InjectorMeta injectorMeta = new InjectorMeta(); // Set the information of the injector String injectorPid = pluginRegistry.getPluginId( StepPluginType.class, injectorMeta ); StepMeta injectorStep = new StepMeta( injectorPid, name, injectorMeta ); return injectorStep; } /** * Create an empty temp file and return it's absolute path. * * @param fileName * @return * @throws IOException */ public static synchronized String createEmptyTempFile( String fileName ) throws IOException { return createEmptyTempFile( fileName, null ); } /** * Create an empty temp file and return it's absolute path. * * @param fileName * @param suffix A suffix to add at the end of the file name * @return * @throws IOException */ public static synchronized String createEmptyTempFile( String fileName, String suffix ) throws IOException { File tempFile = File.createTempFile( fileName, ( Const.isEmpty( suffix ) ? "" : suffix ) ); tempFile.deleteOnExit(); return tempFile.getAbsolutePath(); } /** * Creates a the folder folderName under the java io temp directory. We suffix the file with ??? * * @param folderName * @return */ public static synchronized String createTempFolder( String folderName ) { String absoluteFolderPath = System.getProperty( "java.io.tmpdir" ) + "/" + folderName + "_" + System.currentTimeMillis(); if ( new File( absoluteFolderPath ).mkdir() ) { return absoluteFolderPath; } else { return null; } } /** * Returns the current date using this classes DATE_FORMAT_NOW format string. * * @return */ public static String now() { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat( DATE_FORMAT_NOW ); return sdf.format( cal.getTime() ); } /** * Write the file to be used as input (as a temporary file). * * @return Absolute file name/path of the created file. * @throws IOException UPON */ public static String writeTextFile( String folderName, String fileName, String delimiter ) throws IOException { String absolutePath = null; File file = new File( folderName + "/" + fileName + ".txt" ); absolutePath = file.getAbsolutePath(); String endOfLineCharacters = TestUtilities.getEndOfLineCharacters(); FileWriter fout = new FileWriter( file ); fout.write( "A" + delimiter + "B" + delimiter + "C" + delimiter + "D" + delimiter + "E" + endOfLineCharacters ); fout.write( "1" + delimiter + "b1" + delimiter + "c1" + delimiter + "d1" + delimiter + "e1" + endOfLineCharacters ); fout.write( "2" + delimiter + "b2" + delimiter + "c2" + delimiter + "d2" + delimiter + "e2" + endOfLineCharacters ); fout.write( "3" + delimiter + "b3" + delimiter + "c3" + delimiter + "d3" + delimiter + "e3" + endOfLineCharacters ); fout.close(); return absolutePath; } /** * Create and return a SortRows step. * * @param name * @param sortFields [] Fields to sort by * @param ascending [] Boolean indicating whether the corresponding field is to be sorted in ascending or * descending order. * @param caseSensitive [] Boolean indicating whether the corresponding field is to have case as a factor in the * sort. * @param directory The directory in the file system where the sort is to take place if it can't fit into * memory? * @param sortSize ??? * @param pluginRegistry The environment's Kettle plugin registry. * @return */ public static synchronized StepMeta createSortRowsStep( String name, String[] sortFields, boolean[] ascending, boolean[] caseSensitive, String directory, int sortSize, PluginRegistry pluginRegistry ) { SortRowsMeta sortRowsMeta = new SortRowsMeta(); sortRowsMeta.setSortSize( Integer.toString( sortSize / 10 ) ); sortRowsMeta.setFieldName( sortFields ); sortRowsMeta.setAscending( ascending ); sortRowsMeta.setCaseSensitive( caseSensitive ); sortRowsMeta.setDirectory( directory ); String sortRowsStepPid = pluginRegistry.getPluginId( StepPluginType.class, sortRowsMeta ); StepMeta sortRowsStep = new StepMeta( sortRowsStepPid, name, sortRowsMeta ); return sortRowsStep; } /** * 65-90 = big, 97-122 - small * * @param rng * @param characters * @param length * @return */ public static String generateString( Random rng, int length ) { char[] text = new char[ length ]; for ( int i = 0; i < length; i++ ) { int ch = -1; double db = rng.nextDouble(); if ( rng.nextInt() % 2 == 0 ) { ch = 65 + (int) ( db * 26 ); } else { ch = 97 + (int) ( db * 26 ); } text[ i ] = (char) ch; } return new String( text ); } public static String getStringFromInput( InputStream in ) throws IOException { StringBuilder sb = new StringBuilder(); InputStreamReader is = null; BufferedReader br = null; try { is = new InputStreamReader( in ); br = new BufferedReader( is ); String read = br.readLine(); while ( read != null ) { sb.append( read ); read = br.readLine(); } } finally { if ( is != null ) { try { is.close(); } catch ( IOException e ) { // Suppress } } if ( br != null ) { try { br.close(); } catch ( IOException e ) { // Suppress } } } return sb.toString(); } public static Trans loadAndRunTransformation( String path, Object... parameters ) throws Exception { TransMeta transMeta = new TransMeta( path ); transMeta.setTransformationType( TransMeta.TransformationType.Normal ); Trans trans = new Trans( transMeta ); if ( parameters != null ) { if ( parameters.length % 2 == 1 ) { throw new IllegalArgumentException( "Parameters should be an array of pairs 'parameter'-'value'-..." ); } for ( int i = 0; i < parameters.length; i += 2 ) { Object parameter = parameters[ i ]; Object value = parameters[i + 1]; trans.setParameterValue( parameter.toString(), value.toString() ); } } trans.prepareExecution( null ); trans.startThreads(); trans.waitUntilFinished(); return trans; } }
mit
Caellian/FlowAPI
src/main/java/hr/caellian/flow/data/Flux.java
3418
/* * The MIT License (MIT) * Flow API, API for managing transfer of abstract data. * Copyright (c) 2017 Tin Švagelj <tin.svagelj.email@gmail.com> a.k.a. Caellian * * 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 hr.caellian.flow.data; import java.io.Externalizable; /** * Flux is a representation of transferable unit. * It extends {@link PropertyManager} allowing users to store unit related * {@link Property Properties} and manage them easily. * * @param <S> class of {@link FluxType Flux Type}. * @author Caellian * @since 1.0.0 */ public interface Flux<S extends FluxType> extends Externalizable, PropertyManager { /** * @return ID of this unit. */ default String getID() { return getType().getID(); } /** * @return parent {@link FluxType Flux Type}. */ S getType(); /** * Adds argument flux to this object. * * @param other flux object to add to this one. * @return this object or {@code null} if given flux object couldn't be * added to this one. */ Flux<S> add(Flux<FluxType> other); /** * Creates a new flux object of same type as this object with properties * dependant on argument properties. * * @param subtract properties which should be subtracted from this object. * @param clone properties which should be cloned from this object. * @return constructed flux object. */ Flux<S> take(Property[] subtract, String[] clone); /** * Default equals implementation. * * @param o unit to compare to this one. * @return {@code true} if this unit is equal to argument one, {@code false} * otherwise. */ default boolean equals(Flux<FluxType> o) { boolean ret = this.sameType(o); if (ret) { for (String key : getProperties().keySet()) { Property ours = this.getProperty(key); Property theirs = this.getProperty(key); ret = ret && ours.equals(theirs); } } return ret; } /** * @param o unit type of which to compare to type of this unit. * @return {@code true} if type of this unit is equal to type argument one, * {@code false} otherwise. */ default boolean sameType(Flux<FluxType> o) { return o != null && this.getType() == o.getType(); } }
mit
widmofazowe/cyfronoid-core
src/eu/cyfronoid/core/types/Complex.java
2951
package eu.cyfronoid.core.types; import static java.lang.Math.*; public class Complex { public double re; public double im; public Complex() { re = 0; im = 0; } public Complex(double re, double im) { this.re = re; this.im = im; } public Complex add(Complex cpx) { Complex tmp = new Complex(); tmp.re = re + cpx.re; tmp.im = im + cpx.im; return tmp; } public Complex substract(Complex cpx) { Complex tmp = new Complex(); tmp.re = re - cpx.re; tmp.im = im - cpx.im; return tmp; } public Complex multiply(double x) { return multiply(new Complex(x, 0.0d)); } public Complex multiply(Complex cpx) { Complex tmp = new Complex(); tmp.re = re * cpx.re - im * cpx.im; tmp.im = re * cpx.im + cpx.re * im; return tmp; } public Complex divide(double x) { return divide(new Complex(x, 0.0d)); } public Complex divide(Complex cpx) { Complex tmp = new Complex(); double tm = cpx.re * cpx.re + cpx.im * cpx.im; tmp.re = (re * cpx.re + im * cpx.im)/tm; tmp.im = (im * cpx.re - re * cpx.im)/tm; return tmp; } public double absolute() { return sqrt(re*re + im*im); } public double angle() { double tmp; if(im == 0) { return PI/2; } tmp = atan(im/re); if(re < 0) { tmp = (im > 0) ? tmp + PI : tmp - PI; } return tmp; } public Complex conjugate() { Complex tmp = new Complex(); tmp.re = re; tmp.im = -im; return tmp; } public static double rad2deg(double x) { return x*180/PI; } public static double deg2rad(double x) { return x*PI/180; } public static Complex buildComplex(double mag, double angle) { Complex tmp = new Complex(); tmp.re = mag*cos(angle); tmp.im = mag*sin(angle); return tmp; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(im); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(re); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Complex other = (Complex) obj; if (Double.doubleToLongBits(im) != Double.doubleToLongBits(other.im)) { return false; } if (Double.doubleToLongBits(re) != Double.doubleToLongBits(other.re)) { return false; } return true; } }
mit
wasiuva/cs6501-004project
src/edu/virginia/cs/similarities/OkapiBM25.java
1133
package edu.virginia.cs.similarities; import org.apache.lucene.search.similarities.BasicStats; import org.apache.lucene.search.similarities.SimilarityBase; public class OkapiBM25 extends SimilarityBase { double k1 = 1.2; // range 1.2 - 2 double k2 = 750; // range 0 - 1000 double b = 0.75; // range 0.75 - 1.2 /** * Returns a score for a single term in the document. * * @param stats Provides access to corpus-level statistics * @param termFreq * @param docLength */ @Override protected float score(BasicStats stats, float termFreq, float docLength) { float relevance; float part1 = (float) (Math.log((stats.getNumberOfDocuments() - stats.getDocFreq() + 0.5) / (stats.getDocFreq() + 0.5)) / Math.log(Math.E)); float part2 = (float) (((k1 + 1) * termFreq) / ((k1 * (1 - b + b * (docLength / stats.getAvgFieldLength()))) + termFreq)); float part3 = (float) (((k2 + 1) * 1) / (k2 + 1)); relevance = part1 * part2 * part3; return relevance; } @Override public String toString() { return "Okapi BM25"; } }
mit
kristianmandrup/emberjs-plugin
src/org/emberjs/EmberJSTargetElementEvaluator.java
1694
package org.emberjs; import com.intellij.codeInsight.TargetElementEvaluator; import com.intellij.lang.javascript.psi.JSCallExpression; import com.intellij.lang.javascript.psi.JSExpression; import com.intellij.lang.javascript.psi.JSReferenceExpression; import com.intellij.lang.javascript.psi.impl.JSTextReference; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import org.emberjs.index.EmberIndexUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Kristian Mandrup */ public class EmberJSTargetElementEvaluator implements TargetElementEvaluator { @Override public boolean includeSelfInGotoImplementation(@NotNull PsiElement element) { return false; } @Nullable @Override public PsiElement getElementByReference(@NotNull PsiReference ref, int flags) { if (ref instanceof JSTextReference) { final PsiElement element = ref.getElement(); final JSCallExpression call = PsiTreeUtil.getParentOfType(element, JSCallExpression.class); final JSExpression expression = call != null ? call.getMethodExpression() : null; if (expression instanceof JSReferenceExpression) { JSReferenceExpression callee = (JSReferenceExpression)expression; JSExpression qualifier = callee.getQualifier(); if (qualifier != null && "component".equals(callee.getReferencedName()) && EmberIndexUtil.hasEmberJS(element.getProject())) { return element; } } } return null; } }
mit
moegyver/mJeliot
Model/src/org/mJeliot/protocol/Route.java
495
package org.mJeliot.protocol; import org.mJeliot.model.Lecture; import org.mJeliot.model.User; /** * @author Moritz Rogalli * Interface to provide functions to route messages and send them */ public interface Route { /** * Sends an answer back to the source. The Route has to make sure that the * message reaches its destination. * @param message */ public void sendMessage(String message); public Lecture getLecture(); public User getUser(); public int getDestination(); }
mit
kveskimae/pdfextractor
services/src/main/java/org/pdfextractor/services/config/InitializationAttributes.java
1567
/* * Copyright (c) 2016 Kristjan Veskimae * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.pdfextractor.services.config; /** * Make sure properties file specified by {@link BaseServicesConfig#APPLICATION_PROPERTIES_FILE_NAME} is available on class path and contains all the properties. */ public interface InitializationAttributes { String SELF_HOST_ADDRESS = "SELF_HOST_ADDRESS", SAVE_INVOICES = "SAVE_INVOICES", SAVE_LOCATION = "SAVE_LOCATION"; }
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/bar/markPoint/itemStyle/normal/OpacityNumber.java
364
package cn.edu.gdut.zaoying.Option.series.bar.markPoint.itemStyle.normal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface OpacityNumber { double value() default 0; }
mit
selvasingh/azure-sdk-for-java
sdk/cosmos/mgmt-v2020_06_01_preview/src/main/java/com/microsoft/azure/management/cosmosdb/v2020_06_01_preview/SqlTriggerResource.java
3179
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.cosmosdb.v2020_06_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; /** * Cosmos DB SQL trigger resource object. */ public class SqlTriggerResource { /** * Name of the Cosmos DB SQL trigger. */ @JsonProperty(value = "id", required = true) private String id; /** * Body of the Trigger. */ @JsonProperty(value = "body") private String body; /** * Type of the Trigger. Possible values include: 'Pre', 'Post'. */ @JsonProperty(value = "triggerType") private TriggerType triggerType; /** * The operation the trigger is associated with. Possible values include: * 'All', 'Create', 'Update', 'Delete', 'Replace'. */ @JsonProperty(value = "triggerOperation") private TriggerOperation triggerOperation; /** * Get name of the Cosmos DB SQL trigger. * * @return the id value */ public String id() { return this.id; } /** * Set name of the Cosmos DB SQL trigger. * * @param id the id value to set * @return the SqlTriggerResource object itself. */ public SqlTriggerResource withId(String id) { this.id = id; return this; } /** * Get body of the Trigger. * * @return the body value */ public String body() { return this.body; } /** * Set body of the Trigger. * * @param body the body value to set * @return the SqlTriggerResource object itself. */ public SqlTriggerResource withBody(String body) { this.body = body; return this; } /** * Get type of the Trigger. Possible values include: 'Pre', 'Post'. * * @return the triggerType value */ public TriggerType triggerType() { return this.triggerType; } /** * Set type of the Trigger. Possible values include: 'Pre', 'Post'. * * @param triggerType the triggerType value to set * @return the SqlTriggerResource object itself. */ public SqlTriggerResource withTriggerType(TriggerType triggerType) { this.triggerType = triggerType; return this; } /** * Get the operation the trigger is associated with. Possible values include: 'All', 'Create', 'Update', 'Delete', 'Replace'. * * @return the triggerOperation value */ public TriggerOperation triggerOperation() { return this.triggerOperation; } /** * Set the operation the trigger is associated with. Possible values include: 'All', 'Create', 'Update', 'Delete', 'Replace'. * * @param triggerOperation the triggerOperation value to set * @return the SqlTriggerResource object itself. */ public SqlTriggerResource withTriggerOperation(TriggerOperation triggerOperation) { this.triggerOperation = triggerOperation; return this; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/implementation/VpnSiteLinkConnectionsInner.java
8479
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_04_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.CloudException; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in VpnSiteLinkConnections. */ public class VpnSiteLinkConnectionsInner { /** The Retrofit service to perform REST calls. */ private VpnSiteLinkConnectionsService service; /** The service client containing this operation class. */ private NetworkManagementClientImpl client; /** * Initializes an instance of VpnSiteLinkConnectionsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public VpnSiteLinkConnectionsInner(Retrofit retrofit, NetworkManagementClientImpl client) { this.service = retrofit.create(VpnSiteLinkConnectionsService.class); this.client = client; } /** * The interface defining all the services for VpnSiteLinkConnections to be * used by Retrofit to perform actually REST calls. */ interface VpnSiteLinkConnectionsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_04_01.VpnSiteLinkConnections get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}") Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Path("linkConnectionName") String linkConnectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Retrieves the details of a vpn site link connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param linkConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnSiteLinkConnectionInner object if successful. */ public VpnSiteLinkConnectionInner get(String resourceGroupName, String gatewayName, String connectionName, String linkConnectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, linkConnectionName).toBlocking().single().body(); } /** * Retrieves the details of a vpn site link connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param linkConnectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnSiteLinkConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName, String linkConnectionName, final ServiceCallback<VpnSiteLinkConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, linkConnectionName), serviceCallback); } /** * Retrieves the details of a vpn site link connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param linkConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnSiteLinkConnectionInner object */ public Observable<VpnSiteLinkConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName, String linkConnectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, linkConnectionName).map(new Func1<ServiceResponse<VpnSiteLinkConnectionInner>, VpnSiteLinkConnectionInner>() { @Override public VpnSiteLinkConnectionInner call(ServiceResponse<VpnSiteLinkConnectionInner> response) { return response.body(); } }); } /** * Retrieves the details of a vpn site link connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param linkConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnSiteLinkConnectionInner object */ public Observable<ServiceResponse<VpnSiteLinkConnectionInner>> getWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName, String linkConnectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } if (linkConnectionName == null) { throw new IllegalArgumentException("Parameter linkConnectionName is required and cannot be null."); } final String apiVersion = "2020-04-01"; return service.get(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, linkConnectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnSiteLinkConnectionInner>>>() { @Override public Observable<ServiceResponse<VpnSiteLinkConnectionInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VpnSiteLinkConnectionInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VpnSiteLinkConnectionInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VpnSiteLinkConnectionInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VpnSiteLinkConnectionInner>() { }.getType()) .registerError(CloudException.class) .build(response); } }
mit
wakarimasenco/ChanExplorer
src/co/wakarimasen/chanexplorer/MultiSelectListPreference.java
2755
package co.wakarimasen.chanexplorer; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.preference.ListPreference; import android.util.AttributeSet; public class MultiSelectListPreference extends ListPreference { private boolean[] mClickedDialogEntryIndices; // Need to make sure the SEPARATOR is unique and weird enough that it // doesn't match one of the entries. // Not using any fancy symbols because this is interpreted as a regex for // splitting strings. private static final String SEPARATOR = ","; public MultiSelectListPreference(Context context) { super(context); } public MultiSelectListPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onPrepareDialogBuilder(Builder builder) { CharSequence[] entries = getEntries(); CharSequence[] entryValues = getEntryValues(); if (entries == null || entryValues == null || entries.length != entryValues.length) { throw new IllegalStateException( "ListPreference requires an entries array and an entryValues array which are both the same length"); } mClickedDialogEntryIndices = new boolean[entryValues.length]; restoreCheckedEntries(); builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean val) { mClickedDialogEntryIndices[which] = val; } }); } public static String[] parseStoredValue(CharSequence val) { if ("".equals(val) || val == null) return null; else return ((String) val).split(SEPARATOR); } private void restoreCheckedEntries() { CharSequence[] entryValues = getEntryValues(); String[] vals = parseStoredValue(getValue()); if (vals != null) { for (int j = 0; j < vals.length; j++) { String val = vals[j].trim(); for (int i = 0; i < entryValues.length; i++) { CharSequence entry = entryValues[i]; if (entry.equals(val)) { mClickedDialogEntryIndices[i] = true; break; } } } } } @Override protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); CharSequence[] entryValues = getEntryValues(); if (positiveResult && entryValues != null) { StringBuffer value = new StringBuffer(); for (int i = 0; i < entryValues.length; i++) { if (mClickedDialogEntryIndices[i]) { value.append(entryValues[i]).append(SEPARATOR); } } if (callChangeListener(value)) { String val = value.toString(); if (val.length() > 0) val = val.substring(0, val.length() - SEPARATOR.length()); setValue(val); } } } }
mit
ComMouse/SE228-Answers
src/iteration2/src/com/bookstore/controller/user/OrderController.java
1728
package com.bookstore.controller.user; import com.bookstore.bean.Book; import com.bookstore.bean.Order; import com.bookstore.bean.OrderBook; import com.bookstore.controller.order.BaseOrderController; import com.bookstore.dao.BookDAO; import com.bookstore.dao.OrderBookDAO; import com.bookstore.dao.OrderDAO; import com.bookstore.util.DbUtil; import com.bookstore.util.UserUtil; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Class OrderController */ @WebServlet("/users/orders") public class OrderController extends BaseOrderController { @Override protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int page = 1; int perPage = 10; if (request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } UserUtil userUtil = new UserUtil(request.getSession()); OrderDAO orderDAO = DbUtil.getDAO(OrderDAO.class); List<Order> orderList = orderDAO.findAllByUser(userUtil.getUser().getId(), (page - 1) * perPage, perPage); int orderCount = orderDAO.countByUser(userUtil.getUser().getId()); // Set order books and book detail setOrderDetail(orderList); request.setAttribute("userOrderList", orderList); request.setAttribute("userOrderPage", page); request.setAttribute("userOrderPageCount", (int)Math.ceil((double)orderCount / perPage)); forward(request, response, "/users/order.jsp"); } }
mit
I-Al-Istannen/Bukkit-Command-System
BukkitUtil/src/me/ialistannen/bukkitutil/commandsystem/base/CommandInformationKey.java
1043
package me.ialistannen.bukkitutil.commandsystem.base; /** * The keys for information about a command */ public enum CommandInformationKey { /** * The usage of a command */ USAGE("usage"), /** * The description of a command */ DESCRIPTION("description"), /** * The name of the command */ NAME("name"), /** * The keyword of the command, to insert on tab complete */ KEYWORD("keyword"), /** * The pattern to match, in oder for the command to be recognized */ PATTERN("pattern"); private final String key; /** * Creates this enum entry and sets the key * * @param key The key */ @SuppressWarnings("unused") CommandInformationKey(String key) { this.key = key; } /** * Returns the key * * @return The key for the information */ private String getKey() { return key; } /** * Applies the key to the base key (separation by '_') * * @param baseKey The base key * * @return The combined key */ public String applyTo(String baseKey) { return baseKey + "_" + getKey(); } }
mit
heisedebaise/ranch
ranch-group/src/test/java/org/lpw/ranch/group/member/QueryByGroupTest.java
4393
package org.lpw.ranch.group.member; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.junit.Assert; import org.junit.Test; import org.lpw.ranch.group.GroupModel; import org.lpw.tephra.ctrl.validate.Validators; import java.util.Comparator; /** * @author lpw */ public class QueryByGroupTest extends TestSupport { // @Test public void queryByGroup() { String[] groups = new String[2]; for (int i = 0; i < groups.length; i++) { GroupModel group = new GroupModel(); group.setOwner("owner " + i); group.setCreate(dateTime.now()); liteOrm.save(group); groups[i] = group.getId(); for (int j = 0; j < 5; j++) create(group.getId(), i, j); } mockCarousel.reset(); mockHelper.reset(); mockHelper.mock("/group/member/query-by-group"); JSONObject object = mockHelper.getResponse().asJson(); Assert.assertEquals(1728, object.getIntValue("code")); Assert.assertEquals(message.get(Validators.PREFIX + "illegal-id", message.get(MemberModel.NAME + ".group")), object.getString("message")); mockHelper.reset(); mockHelper.getRequest().addParameter("group", "group id"); mockHelper.mock("/group/member/query-by-group"); object = mockHelper.getResponse().asJson(); Assert.assertEquals(1728, object.getIntValue("code")); Assert.assertEquals(message.get(Validators.PREFIX + "illegal-id", message.get(MemberModel.NAME + ".group")), object.getString("message")); mockHelper.reset(); mockHelper.getRequest().addParameter("group", generator.uuid()); mockHelper.mock("/group/member/query-by-group"); object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); Assert.assertTrue(object.getJSONArray("data").isEmpty()); mockCarousel.register("ranch.user.get", (key, header, parameter, cacheTime) -> { JSONObject json = new JSONObject(); json.put("code", 0); JSONObject data = new JSONObject(); String id = parameter.get("ids"); JSONObject user = new JSONObject(); user.put("id", id); user.put("name", "name " + id); data.put(id, user); json.put("data", data); return json.toJSONString(); }); for (int i = 0; i < 2; i++) { if (i == 1) for (int j = 0; j < 2; j++) create(groups[j], j, 5); for (int j = 0; j < 2; j++) success(groups, j, 4); } for (String group : groups) cache.remove(MemberModel.NAME + ".service.group:" + group); for (int i = 0; i < 2; i++) success(groups, i, 5); } private void create(String group, int i, int j) { MemberModel member = new MemberModel(); member.setGroup(group); member.setUser("user " + i + j); member.setNick("nick " + i + j); member.setType(j); member.setJoin(dateTime.now()); liteOrm.save(member); } private void success(String[] groups, int i, int size) { mockHelper.reset(); mockHelper.getRequest().addParameter("group", groups[i]); mockHelper.mock("/group/member/query-by-group"); JSONObject object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); JSONArray data = object.getJSONArray("data"); Assert.assertEquals(size, data.size()); data.sort(Comparator.comparingInt((obj) -> ((JSONObject) obj).getIntValue("type"))); for (int j = 0; j < size; j++) equals(data.getJSONObject(j), i, j + 1); } private void equals(JSONObject object, int i, int j) { Assert.assertTrue(object.containsKey("id")); JSONObject user = object.getJSONObject("user"); Assert.assertEquals("user " + i + j, user.getString("id")); Assert.assertEquals("name user " + i + j, user.getString("name")); Assert.assertEquals("nick " + i + j, object.getString("nick")); Assert.assertEquals(j, object.getIntValue("type")); Assert.assertTrue(System.currentTimeMillis() - dateTime.toDate(object.getString("join")).getTime() < 2000L); } }
mit
samuelfac/portalunico.siscomex.gov.br
src/main/java/br/gov/siscomex/portalunico/due/model/Recolhimento.java
5991
package br.gov.siscomex.portalunico.due.model; import java.math.BigDecimal; import java.time.OffsetDateTime; import javax.validation.Valid; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Recolhimento", propOrder = { "dataDoPagamento", "dataDoRegistro", "valorDaMulta", "valorDoImpostoRecolhido", "valorDoJurosMora" }) @XmlRootElement(name="Recolhimento") public class Recolhimento { @XmlElement(name="dataDoPagamento") @ApiModelProperty(example = "2019-09-20T14:13:46.966Z", value = "Data do pagamento<br />Formato:'yyyy-MM-dd'T'HH:mm:ss.SSSZ'") /** * Data do pagamento<br />Formato:'yyyy-MM-dd'T'HH:mm:ss.SSSZ' **/ private OffsetDateTime dataDoPagamento = null; @XmlElement(name="dataDoRegistro") @ApiModelProperty(example = "2019-09-20T14:13:46.966Z", value = "Data do Registro<br />Formato:'yyyy-MM-dd'T'HH:mm:ss.SSSZ'") /** * Data do Registro<br />Formato:'yyyy-MM-dd'T'HH:mm:ss.SSSZ' **/ private OffsetDateTime dataDoRegistro = null; @XmlElement(name="valorDaMulta") @ApiModelProperty(value = "Valor da multa<br />Tamanho: 7,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto.") @Valid /** * Valor da multa<br />Tamanho: 7,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto. **/ private BigDecimal valorDaMulta = null; @XmlElement(name="valorDoImpostoRecolhido") @ApiModelProperty(value = "Valor do imposto recolhido<br />Tamanho: 15,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto.") @Valid /** * Valor do imposto recolhido<br />Tamanho: 15,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto. **/ private BigDecimal valorDoImpostoRecolhido = null; @XmlElement(name="valorDoJurosMora") @ApiModelProperty(value = "Valor do Juros de Mora<br />Tamanho: 7,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto.") @Valid /** * Valor do Juros de Mora<br />Tamanho: 7,2<br />Formato: Decimal, com até 2 casas decimais separadas por ponto. **/ private BigDecimal valorDoJurosMora = null; /** * Data do pagamento&lt;br /&gt;Formato:&#39;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#39; * @return dataDoPagamento **/ @JsonProperty("dataDoPagamento") public OffsetDateTime getDataDoPagamento() { return dataDoPagamento; } public void setDataDoPagamento(OffsetDateTime dataDoPagamento) { this.dataDoPagamento = dataDoPagamento; } public Recolhimento dataDoPagamento(OffsetDateTime dataDoPagamento) { this.dataDoPagamento = dataDoPagamento; return this; } /** * Data do Registro&lt;br /&gt;Formato:&#39;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#39; * @return dataDoRegistro **/ @JsonProperty("dataDoRegistro") public OffsetDateTime getDataDoRegistro() { return dataDoRegistro; } public void setDataDoRegistro(OffsetDateTime dataDoRegistro) { this.dataDoRegistro = dataDoRegistro; } public Recolhimento dataDoRegistro(OffsetDateTime dataDoRegistro) { this.dataDoRegistro = dataDoRegistro; return this; } /** * Valor da multa&lt;br /&gt;Tamanho: 7,2&lt;br /&gt;Formato: Decimal, com até 2 casas decimais separadas por ponto. * @return valorDaMulta **/ @JsonProperty("valorDaMulta") public BigDecimal getValorDaMulta() { return valorDaMulta; } public void setValorDaMulta(BigDecimal valorDaMulta) { this.valorDaMulta = valorDaMulta; } public Recolhimento valorDaMulta(BigDecimal valorDaMulta) { this.valorDaMulta = valorDaMulta; return this; } /** * Valor do imposto recolhido&lt;br /&gt;Tamanho: 15,2&lt;br /&gt;Formato: Decimal, com até 2 casas decimais separadas por ponto. * @return valorDoImpostoRecolhido **/ @JsonProperty("valorDoImpostoRecolhido") public BigDecimal getValorDoImpostoRecolhido() { return valorDoImpostoRecolhido; } public void setValorDoImpostoRecolhido(BigDecimal valorDoImpostoRecolhido) { this.valorDoImpostoRecolhido = valorDoImpostoRecolhido; } public Recolhimento valorDoImpostoRecolhido(BigDecimal valorDoImpostoRecolhido) { this.valorDoImpostoRecolhido = valorDoImpostoRecolhido; return this; } /** * Valor do Juros de Mora&lt;br /&gt;Tamanho: 7,2&lt;br /&gt;Formato: Decimal, com até 2 casas decimais separadas por ponto. * @return valorDoJurosMora **/ @JsonProperty("valorDoJurosMora") public BigDecimal getValorDoJurosMora() { return valorDoJurosMora; } public void setValorDoJurosMora(BigDecimal valorDoJurosMora) { this.valorDoJurosMora = valorDoJurosMora; } public Recolhimento valorDoJurosMora(BigDecimal valorDoJurosMora) { this.valorDoJurosMora = valorDoJurosMora; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Recolhimento {\n"); sb.append(" dataDoPagamento: ").append(toIndentedString(dataDoPagamento)).append("\n"); sb.append(" dataDoRegistro: ").append(toIndentedString(dataDoRegistro)).append("\n"); sb.append(" valorDaMulta: ").append(toIndentedString(valorDaMulta)).append("\n"); sb.append(" valorDoImpostoRecolhido: ").append(toIndentedString(valorDoImpostoRecolhido)).append("\n"); sb.append(" valorDoJurosMora: ").append(toIndentedString(valorDoJurosMora)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
mit
kyawswa/myanmarlottery
src/main/java/com/hyurumi/fb_bot_boilerplate/models/common/Welcome.java
640
/* * 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 com.hyurumi.fb_bot_boilerplate.models.common; import com.google.gson.annotations.SerializedName; /** * * @author Kyawswa */ public class Welcome { @SerializedName("setting_type") public String settingType = "greeting"; @SerializedName("greeting") public Greeting greeting; public Welcome(String settingType, Greeting greeting) { this.settingType = settingType; this.greeting = greeting; } }
mit
ismailsimsek/schemaspy
src/main/java/org/schemaspy/view/SqlAnalyzer.java
8169
/* * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier * This file is a part of the SchemaSpy project (http://schemaspy.org). * * SchemaSpy 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 2.1 of the License, or (at your option) any later version. * * SchemaSpy 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.schemaspy.view; import org.schemaspy.model.Database; import org.schemaspy.model.Table; import org.schemaspy.util.CaseInsensitiveMap; import java.sql.DatabaseMetaData; import java.util.*; /** * * @author John Currier */ public class SqlAnalyzer { private Set<String> keywords; private Map<String, Table> tablesByPossibleNames; private static final String TOKENS = " \t\n\r\f()<>|,"; /** * Returns a {@link Set} of tables/views that are possibly referenced * by the specified SQL. * * @param sql * @param db * @return */ public Set<Table> getReferencedTables(String sql, Database db) { Set<Table> referenced = new HashSet<Table>(); Map<String, Table> tables = getTableMap(db); @SuppressWarnings("hiding") Set<String> keywords = getKeywords(db.getMetaData()); StringTokenizer tokenizer = new StringTokenizer(sql, TOKENS, true); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!keywords.contains(token.toUpperCase())) { Table t = tables.get(token); if (t == null) { int lastDot = token.lastIndexOf('.'); if (lastDot != -1) { t = tables.get(token.substring(0, lastDot)); } } if (t != null) { referenced.add(t); } } } return referenced; } /** * Returns a {@link Map} of all tables/views in the database * keyed by several possible ways to refer to the table. * * @param db * @return */ private Map<String, Table> getTableMap(Database db) { if (tablesByPossibleNames == null) { tablesByPossibleNames = new CaseInsensitiveMap<Table>(); tablesByPossibleNames.putAll(getTableMap(db.getTables())); tablesByPossibleNames.putAll(getTableMap(db.getViews())); } return tablesByPossibleNames; } /** * Returns a {@link Map} of the specified tables/views * keyed by several possible ways to refer to the table. * * @param tables * @return */ private Map<String, Table> getTableMap(Collection<? extends Table> tables) { Map<String, Table> map = new CaseInsensitiveMap<Table>(); for (Table t : tables) { String name = t.getName(); String container = t.getContainer(); map.put(name, t); map.put("`" + name + "`", t); map.put("'" + name + "'", t); map.put("\"" + name + "\"", t); map.put(container + "." + name, t); map.put("`" + container + "`.`" + name + "`", t); map.put("'" + container + "'.'" + name + "'", t); map.put("\"" + container + "\".\"" + name + "\"", t); map.put("`" + container + '.' + name + "`", t); map.put("'" + container + '.' + name + "'", t); map.put("\"" + container + '.' + name + "\"", t); } return map; } /** * @param meta * @return */ private Set<String> getKeywords(DatabaseMetaData meta) { if (keywords == null) { keywords = new HashSet<String>(Arrays.asList(new String[] { "ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR_LENGTH", "CHARACTER_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP", "ELSE", "END", "END - EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IMMEDIATE", "IN", "INDICATOR", "INITIALLY", "INNER", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION", "JOIN", "KEY", "LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER", "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NOT", "NULL", "NULLIF", "NUMERIC", "OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS", "PAD", "PARTIAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK", "ROWS", "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION", "SESSION_USER", "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SQL", "SQLCODE", "SQLERROR", "SQLSTATE", "SUBSTRING", "SUM", "SYSTEM_USER", "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRIM", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE", "YEAR", "ZONE" })); try { String keywordsArray[] = new String[] { meta.getSQLKeywords(), meta.getSystemFunctions(), meta.getNumericFunctions(), meta.getStringFunctions(), meta.getTimeDateFunctions() }; for (String aKeywordsArray : keywordsArray) { StringTokenizer tokenizer = new StringTokenizer(aKeywordsArray.toUpperCase(), ","); while (tokenizer.hasMoreTokens()) { keywords.add(tokenizer.nextToken().trim()); } } } catch (Exception exc) { // don't totally fail just because we can't extract these details... System.err.println(exc); } } return keywords; } }
mit
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/config/blockchain/MordenConfig.java
2008
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.config.blockchain; import java.math.BigInteger; public class MordenConfig { private static final BigInteger NONSE = BigInteger.valueOf(0x100000); public static class Frontier extends FrontierConfig { public Frontier() { super(new FrontierConstants() { @Override public BigInteger getInitialNonce() { return NONSE; } }); } } public static class Homestead extends HomesteadConfig { public Homestead() { super(new HomesteadConstants() { @Override public BigInteger getInitialNonce() { return NONSE; } }); } } }
mit
fujibee/hudson
core/src/main/java/hudson/util/ForkOutputStream.java
2078
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson.util; import java.io.IOException; import java.io.OutputStream; /** * @author Kohsuke Kawaguchi */ public class ForkOutputStream extends OutputStream { private final OutputStream lhs; private final OutputStream rhs; public ForkOutputStream(OutputStream lhs, OutputStream rhs) { this.lhs = lhs; this.rhs = rhs; } public void write(int b) throws IOException { lhs.write(b); rhs.write(b); } public void write(byte[] b) throws IOException { lhs.write(b); rhs.write(b); } public void write(byte[] b, int off, int len) throws IOException { lhs.write(b, off, len); rhs.write(b, off, len); } public void flush() throws IOException { lhs.flush(); rhs.flush(); } public void close() throws IOException { lhs.close(); rhs.close(); } }
mit
thezelus/dogTracker
viewServer/src/main/java/com/dogTracker/viewServer/web/AcceptRequestInterceptor.java
844
package com.dogTracker.viewServer.web; import org.springframework.http.HttpRequest; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; public class AcceptRequestInterceptor implements ClientHttpRequestInterceptor { private final MediaType mediaType; public AcceptRequestInterceptor(MediaType mediaType) { this.mediaType = mediaType; } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().add("Accept", mediaType.getType()); return execution.execute(request,body); } }
mit
spapageo/jannel
src/main/java/com/github/spapageo/jannel/exception/InvalidUUIDException.java
1597
/* * The MIT License (MIT) * Copyright (c) 2016 Spyros Papageorgiou * * 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.github.spapageo.jannel.exception; /** * Exception when the input buffer is an invalid UUID octet string */ public class InvalidUUIDException extends BadMessageException { /** * Constructs an exception with the specified message * @param msg the exception message * @param cause the cause of the exception */ public InvalidUUIDException(String msg, Throwable cause) { super(msg, cause); } }
mit
darkfireworld/java-fast-framework
src/main/java/org/darkgem/web/support/handler/Token.java
324
package org.darkgem.web.support.handler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * token标记 */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface Token { }
mit
IgorVieira/FirstClass
Felipe Medeiros/Lista de Exercicios 1/src/Numero20/Ex20.java
48
package Numero20; public class Ex20 { }
mit
Kasekopf/kolandroid
app/src/main/java/com/github/kolandroid/kol/android/util/searchlist/SerializableSelector.java
174
package com.github.kolandroid.kol.android.util.searchlist; import java.io.Serializable; public interface SerializableSelector<E> extends ListSelector<E>, Serializable { }
mit
RaphaelCojocaru/interview-prep
HackerRank/Algorithms/Search/icecream-parlor/Solution.java
1624
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; // https://www.hackerrank.com/challenges/icecream-parlor public class Solution { static class Pair { private int index1, index2; public Pair(int i1, int i2) { index1 = i1; index2 = i2; } public String toString() { return (index1 + " " + index2); } } public static Pair getPairWithSum(int m, int n, int[] costs) { Pair result; boolean found = false; int i = 0, j = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) if (costs[i] + costs[j] == m && i != j) { found = true; break; } if (found == true) break; } result = new Pair(Math.min(i + 1, j + 1), Math.max(i + 1, j + 1)); return result; } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); int money, n; int[] costs; for (int i = 0; i < tests; i++) { money = sc.nextInt(); n = sc.nextInt(); costs = new int[n]; for (int j = 0; j < n; j++) costs[j] = sc.nextInt(); System.out.println(getPairWithSum(money, n, costs)); } } }
mit
NestedWorld/NestedWorld-Android
app/src/main/java/com/nestedworld/nestedworld/events/http/OnShopItemsUpdated.java
86
package com.nestedworld.nestedworld.events.http; public class OnShopItemsUpdated { }
mit
harme199497/IntegratedDynamics
src/main/java/org/cyclops/integrateddynamics/part/aspect/write/AspectWriteBase.java
2843
package org.cyclops.integrateddynamics.part.aspect.write; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.cyclops.cyclopscore.helper.MinecraftHelpers; import org.cyclops.integrateddynamics.api.evaluate.variable.IValue; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType; import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable; import org.cyclops.integrateddynamics.api.network.IPartNetwork; import org.cyclops.integrateddynamics.api.part.IPartState; import org.cyclops.integrateddynamics.api.part.IPartType; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.api.part.aspect.IAspectWrite; import org.cyclops.integrateddynamics.api.part.write.IPartStateWriter; import org.cyclops.integrateddynamics.api.part.write.IPartTypeWriter; import org.cyclops.integrateddynamics.part.aspect.AspectBase; import org.cyclops.integrateddynamics.part.aspect.Aspects; /** * Base class for write aspects. * @author rubensworks */ public abstract class AspectWriteBase<V extends IValue, T extends IValueType<V>> extends AspectBase<V, T> implements IAspectWrite<V, T> { public AspectWriteBase() { if(MinecraftHelpers.isClientSide()) { registerModelResourceLocation(); } } @SuppressWarnings("unchecked") @Override public <P extends IPartType<P, S>, S extends IPartState<P>> void update(IPartNetwork network, P partType, PartTarget target, S state) { if(partType instanceof IPartTypeWriter && state instanceof IPartStateWriter && ((IPartStateWriter) state).getActiveAspect() == this) { IVariable variable = ((IPartTypeWriter) partType).getActiveVariable(network, target, (IPartStateWriter) state); if(variable != null && ((IPartStateWriter) state).getActiveAspect().getValueType().correspondsTo(variable.getType())) { write((IPartTypeWriter) partType, target, (IPartStateWriter) state, variable); } else if(!((IPartStateWriter) state).isDeactivated()) { ((IPartStateWriter) state).getActiveAspect().onDeactivate((IPartTypeWriter) partType, target, (IPartStateWriter) state); } } } @Override public <P extends IPartTypeWriter<P, S>, S extends IPartStateWriter<P>> void onDeactivate(P partType, PartTarget target, S state) { state.setDeactivated(true); } protected String getUnlocalizedType() { return "write"; } @SideOnly(Side.CLIENT) protected void registerModelResourceLocation() { Aspects.REGISTRY.registerAspectModel(this, new ResourceLocation(getModId() + ":aspect/" + getUnlocalizedType().replaceAll("\\.", "/"))); } }
mit
fh-pear/fh-rcon-client
src/Version.java
96
public interface Version { String VERSION = "1.2a"; String CLIENT_VERSION = "1.5a"; }
mit
jeozey/XmppServerTester
xmpp-core/src/main/java/rocks/xmpp/core/stream/model/errors/ResourceConstraint.java
2027
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Christian Schudt * * 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 rocks.xmpp.core.stream.model.errors; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * The implementation of the {@code <resource-constraint/>} stream error. * <blockquote> * <p><cite><a href="http://xmpp.org/rfcs/rfc6120.html#streams-error-conditions-resource-constraint">4.9.3.17. resource-constraint</a></cite></p> * <p>The server lacks the system resources necessary to service the stream.</p> * </blockquote> * This class is a singleton. * * @see #RESOURCE_CONSTRAINT */ @XmlRootElement(name = "resource-constraint") @XmlType(factoryMethod = "create") final class ResourceConstraint extends Condition { ResourceConstraint() { } private static ResourceConstraint create() { return (ResourceConstraint) RESOURCE_CONSTRAINT; } }
mit
color-coding/ibas-framework
bobas.businessobjectscommon/src/test/java/org/colorcoding/ibas/bobas/test/bo/SalesOrder2.java
1656
package org.colorcoding.ibas.bobas.test.bo; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import org.colorcoding.ibas.bobas.core.IPropertyInfo; import org.colorcoding.ibas.bobas.mapping.DbField; import org.colorcoding.ibas.bobas.mapping.DbFieldType; public class SalesOrder2 extends SalesOrder { private static final long serialVersionUID = -243448784277376241L; /** * 当前类型 */ private final static Class<?> MY_CLASS = SalesOrder2.class; /** * 属性名称-凭证编号 */ private static final String PROPERTY_DOCENTRY2_NAME = "DocEntry2"; /** * 凭证编号 属性 */ @DbField(name = "DocEntry2", type = DbFieldType.NUMERIC, table = DB_TABLE_NAME, primaryKey = true) public static final IPropertyInfo<Integer> PROPERTY_DOCENTRY2 = registerProperty(PROPERTY_DOCENTRY2_NAME, Integer.class, MY_CLASS); /** * 获取-凭证编号 * * @return 值 */ @XmlElement(name = PROPERTY_DOCENTRY2_NAME) public final Integer getDocEntry2() { return this.getProperty(PROPERTY_DOCENTRY2); } /** * 设置-凭证编号 * * @param value * 值 */ public final void setDocEntry2(Integer value) { this.setProperty(PROPERTY_DOCENTRY2, value); } @Override @XmlElementWrapper(name = "SalesOrderItems") @XmlElement(name = "SalesOrderItem", type = SalesOrderItem2.class, required = true) public ISalesOrderItems getSalesOrderItems() { return this.getProperty(PROPERTY_SALESORDERITEMS); } /** * 初始化数据 */ @Override protected void initialize() { this.setSalesOrderItems(new SalesOrderItems2(this)); super.initialize(); } }
mit
alexsalo/algorithms_java
src/number_theory/IntegerPartiotion.java
810
package number_theory; import java.util.Arrays; public class IntegerPartiotion { public static void printAllIntegerPartitions(int N) { int[] a = new int[N]; for (int i = 0; i < N; i++) a[i] = 0; a[0] = N; System.out.println(Arrays.toString(a)); while (a[0] != 1) { // case 1 decrease // find last int pos = 0; while (a[pos] != 0) pos++; int last = pos--; // find back last bigger than 0 while (a[pos] <= 1) pos--; a[pos]--; a[last] = 1; System.out.println(Arrays.toString(a)); } } public static void main(String[] args) { printAllIntegerPartitions(4); } }
mit
tsdl2013/SimpleFlatMapper
sfm/src/main/java/org/sfm/csv/DefaultFieldAppenderFactory.java
6268
package org.sfm.csv; import org.sfm.csv.impl.writer.*; //IFJAVA8_START import org.sfm.csv.impl.writer.time.JavaTimeFormattingAppender; import org.sfm.map.column.time.JavaDateTimeFormatterProperty; import java.time.temporal.TemporalAccessor; //IFJAVA8_END import org.sfm.map.column.joda.JodaDateTimeFormatterProperty; import org.sfm.map.mapper.ColumnDefinition; import org.sfm.map.FieldMapper; import org.sfm.map.MappingContext; import org.sfm.map.column.DateFormatProperty; import org.sfm.map.column.EnumOrdinalFormatProperty; import org.sfm.map.column.FormatProperty; import org.sfm.map.mapper.PropertyMapping; import org.sfm.map.context.MappingContextFactoryBuilder; import org.sfm.map.impl.JodaTimeClasses; import org.sfm.map.impl.fieldmapper.*; import org.sfm.reflect.Getter; import org.sfm.reflect.Setter; import org.sfm.reflect.TypeHelper; import org.sfm.reflect.primitive.*; import org.sfm.utils.Supplier; import java.lang.reflect.Type; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class DefaultFieldAppenderFactory { private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final DefaultFieldAppenderFactory DEFAULT_FIELD_APPENDER_FACTORY = new DefaultFieldAppenderFactory(); @SuppressWarnings("unchecked") public static DefaultFieldAppenderFactory instance() { return DEFAULT_FIELD_APPENDER_FACTORY; } public DefaultFieldAppenderFactory() { } @SuppressWarnings("unchecked") public <T, P> FieldMapper<T, Appendable> newFieldAppender( PropertyMapping<T, P, CsvColumnKey, ? extends ColumnDefinition<CsvColumnKey, ?>> pm, CellWriter cellWriter, MappingContextFactoryBuilder builder) { if (pm == null) throw new NullPointerException("pm is null"); Type type = pm.getPropertyMeta().getPropertyType(); Getter<T, ? extends P> getter = pm.getPropertyMeta().getGetter(); ColumnDefinition<CsvColumnKey, ?> columnDefinition = pm.getColumnDefinition(); if (TypeHelper.isPrimitive(type) && !columnDefinition.has(FormatProperty.class)) { if (getter instanceof BooleanGetter) { return new BooleanFieldMapper<T, Appendable>((BooleanGetter) getter, new BooleanAppendableSetter(cellWriter)); } else if (getter instanceof ByteGetter) { return new ByteFieldMapper<T, Appendable>((ByteGetter) getter, new ByteAppendableSetter(cellWriter)); } else if (getter instanceof CharacterGetter) { return new CharacterFieldMapper<T, Appendable>((CharacterGetter) getter, new CharacterAppendableSetter(cellWriter)); } else if (getter instanceof ShortGetter) { return new ShortFieldMapper<T, Appendable>((ShortGetter) getter, new ShortAppendableSetter(cellWriter)); } else if (getter instanceof IntGetter) { return new IntFieldMapper<T, Appendable>((IntGetter) getter, new IntegerAppendableSetter(cellWriter)); } else if (getter instanceof LongGetter) { return new LongFieldMapper<T, Appendable>((LongGetter) getter, new LongAppendableSetter(cellWriter)); } else if (getter instanceof FloatGetter) { return new FloatFieldMapper<T, Appendable>((FloatGetter) getter, new FloatAppendableSetter(cellWriter)); } else if (getter instanceof DoubleGetter) { return new DoubleFieldMapper<T, Appendable>((DoubleGetter) getter, new DoubleAppendableSetter(cellWriter)); } } Setter<Appendable, ? super P> setter = null; if (TypeHelper.isEnum(type) && columnDefinition.has(EnumOrdinalFormatProperty.class)) { setter = (Setter) new EnumOrdinalAppendableSetter(cellWriter); } Format format = null; if (columnDefinition.has(FormatProperty.class)) { format = columnDefinition.lookFor(FormatProperty.class).format(); } else if (TypeHelper.areEquals(type, Date.class)) { String df = DEFAULT_DATE_FORMAT; DateFormatProperty dfp = columnDefinition.lookFor(DateFormatProperty.class); if (dfp != null) { df = dfp.getPattern(); } format = new SimpleDateFormat(df); } //IFJAVA8_START else if (TypeHelper.isAssignable(TemporalAccessor.class, type) && columnDefinition.has(JavaDateTimeFormatterProperty.class)) { return new JavaTimeFormattingAppender<T>((Getter<T, ? extends TemporalAccessor>) getter, columnDefinition.lookFor(JavaDateTimeFormatterProperty.class).getFormatter(), cellWriter); } //IFJAVA8_END else if (JodaTimeClasses.isJoda(type)) { if (columnDefinition.has(JodaDateTimeFormatterProperty.class)) { return new JodaTimeFormattingAppender<T>(getter, columnDefinition.lookFor(JodaDateTimeFormatterProperty.class).getFormatter(), cellWriter); } else if (columnDefinition.has(DateFormatProperty.class)) { return new JodaTimeFormattingAppender<T>(getter, columnDefinition.lookFor(DateFormatProperty.class).getPattern(), cellWriter); } } if (format != null) { final Format f = format; builder.addSupplier(pm.getColumnKey().getIndex(), new Supplier<Format>() { @Override public Format get() { return (Format) f.clone(); } }); return new FormattingAppender<T>(getter, new MappingContextFormatGetter<T>(pm.getColumnKey().getIndex()), cellWriter); } if (setter == null) { setter = new ObjectAppendableSetter(cellWriter); } return new FieldMapperImpl<T, Appendable, P>(getter, setter); } private static class MappingContextFormatGetter<T> implements Getter<MappingContext<? super T>, Format> { private final int index; public MappingContextFormatGetter(int index) { this.index = index; } @Override public Format get(MappingContext<? super T> target) throws Exception { return target.context(index); } } }
mit
percenuage/virtualOS
src/fr/eseo/os/command/CommandMKDIR.java
349
package fr.eseo.os.command; import fr.eseo.os.User; /** * Created by axel on 12/12/15. */ public class CommandMKDIR implements Command { private User user; public CommandMKDIR(User user) { this.user = user; } @Override public String execute(String... args) { return user.executeCommandMKDIR(args); } }
mit
littcai/littcore-license
src/main/java/com/litt/core/security/license/gui/DecryptPanel.java
4506
package com.litt.core.security.license.gui; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.security.NoSuchAlgorithmException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import com.litt.core.security.Algorithm; import com.litt.core.security.DecryptFailedException; import com.litt.core.security.ISecurity; import com.litt.core.security.algorithm.DESTool; /** * * 证书解密. * * <pre><b>Description:</b> * 通过DES算法解密整个证书文件内容 * </pre> * * <pre><b>Changelog:</b> * * </pre> * * @author <a href="mailto:littcai@hotmail.com">Bob.cai</a> * @since 2012-6-12 * @version 1.0 */ public class DecryptPanel extends JPanel { private JTextArea textArea_encrypt; private JTextArea textArea_decrypt; private JTextField textField_licenseId; /** * Create the panel. */ public DecryptPanel() { GridBagLayout gbl_decryptPanel = new GridBagLayout(); gbl_decryptPanel.columnWidths = new int[]{0, 0, 0}; gbl_decryptPanel.rowHeights = new int[]{0, 0, 0, 0, 0}; gbl_decryptPanel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_decryptPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; this.setLayout(gbl_decryptPanel); JLabel lblid = new JLabel("证书ID:"); GridBagConstraints gbc_lblid = new GridBagConstraints(); gbc_lblid.anchor = GridBagConstraints.EAST; gbc_lblid.insets = new Insets(0, 0, 5, 5); gbc_lblid.gridx = 0; gbc_lblid.gridy = 0; add(lblid, gbc_lblid); textField_licenseId = new JTextField(); GridBagConstraints gbc_textField_licenseId = new GridBagConstraints(); gbc_textField_licenseId.insets = new Insets(0, 0, 5, 0); gbc_textField_licenseId.fill = GridBagConstraints.HORIZONTAL; gbc_textField_licenseId.gridx = 1; gbc_textField_licenseId.gridy = 0; add(textField_licenseId, gbc_textField_licenseId); textField_licenseId.setColumns(10); JLabel label_20 = new JLabel("加密内容:"); GridBagConstraints gbc_label_20 = new GridBagConstraints(); gbc_label_20.insets = new Insets(0, 0, 5, 5); gbc_label_20.anchor = GridBagConstraints.EAST; gbc_label_20.gridx = 0; gbc_label_20.gridy = 1; this.add(label_20, gbc_label_20); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.insets = new Insets(0, 0, 5, 0); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 1; gbc_scrollPane.gridy = 1; this.add(scrollPane, gbc_scrollPane); textArea_encrypt = new JTextArea(); textArea_encrypt.setRows(8); textArea_encrypt.setLineWrap(true); scrollPane.setViewportView(textArea_encrypt); JLabel label_21 = new JLabel("解密内容:"); GridBagConstraints gbc_label_21 = new GridBagConstraints(); gbc_label_21.insets = new Insets(0, 0, 5, 5); gbc_label_21.gridx = 0; gbc_label_21.gridy = 2; this.add(label_21, gbc_label_21); JScrollPane scrollPane2 = new JScrollPane(); GridBagConstraints gbc_scrollPane2 = new GridBagConstraints(); gbc_scrollPane2.insets = new Insets(0, 0, 5, 0); gbc_scrollPane2.fill = GridBagConstraints.BOTH; gbc_scrollPane2.gridx = 1; gbc_scrollPane2.gridy = 2; this.add(scrollPane2, gbc_scrollPane2); textArea_decrypt = new JTextArea(); textArea_decrypt.setRows(8); textArea_decrypt.setLineWrap(true); scrollPane2.setViewportView(textArea_decrypt); JButton button_4 = new JButton("解密"); button_4.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { //用DES算法进行解密 try { ISecurity security = new DESTool(textField_licenseId.getText(), Algorithm.BLOWFISH); textArea_decrypt.setText(security.decrypt(textArea_encrypt.getText())); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(e.getComponent(), e1.getMessage()); } catch (DecryptFailedException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(e.getComponent(), e1.getMessage()); } } }); GridBagConstraints gbc_button_4_1 = new GridBagConstraints(); gbc_button_4_1.gridx = 1; gbc_button_4_1.gridy = 3; this.add(button_4, gbc_button_4_1); } }
mit
ferzerkerx/album-finder
src/test/java/com/ferzerkerx/albumfinder/config/DbTestConfig.java
358
package com.ferzerkerx.albumfinder.config; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; @TestConfiguration @PropertySource("classpath:test_application.properties") @Import({DbConfig.class}) public class DbTestConfig { }
mit
mattjlewis/diozero
diozero-core/src/main/java/com/diozero/devices/motor/DualMotor.java
4162
package com.diozero.devices.motor; /* * #%L * Organisation: diozero * Project: diozero - Core * Filename: DualMotor.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2021 diozero * %% * 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. * #L% */ import org.tinylog.Logger; import com.diozero.api.DeviceInterface; import com.diozero.api.RuntimeIOException; /** * Generic dual bi-directional motor driver. Assumes that the motors are * arranged in a left / right orientation. */ public class DualMotor implements DeviceInterface { private MotorInterface motorA; private MotorInterface motorB; public DualMotor(MotorInterface motorA, MotorInterface motorB) { this.motorA = motorA; this.motorB = motorB; } @Override public void close() { Logger.trace("close()"); if (motorA != null) { motorA.close(); } if (motorB != null) { motorB.close(); } } public float[] getValues() throws RuntimeIOException { return new float[] { motorA.getValue(), motorB.getValue() }; } /** * Set the speed and direction for both motors (clockwise / counter-clockwise) * * @param leftValue Range -1 .. 1. Positive numbers for clockwise, Negative * numbers for counter clockwise * @param rightValue Range -1 .. 1. Positive numbers for clockwise, Negative * numbers for counter clockwise * @throws RuntimeIOException if an I/O error occurs */ public void setValues(float leftValue, float rightValue) throws RuntimeIOException { motorA.setValue(leftValue); motorB.setValue(rightValue); } public void forward(float speed) throws RuntimeIOException { motorA.forward(speed); motorB.forward(speed); } public void backward(float speed) throws RuntimeIOException { motorA.backward(speed); motorB.backward(speed); } public void rotateLeft(float speed) throws RuntimeIOException { motorA.backward(speed); motorB.forward(speed); } public void rotateRight(float speed) throws RuntimeIOException { motorA.forward(speed); motorB.backward(speed); } public void forwardLeft(float speed) throws RuntimeIOException { motorA.stop(); motorB.forward(speed); } public void forwardRight(float speed) throws RuntimeIOException { motorA.forward(speed); motorB.stop(); } public void backwardLeft(float speed) throws RuntimeIOException { motorA.stop(); motorB.backward(speed); } public void backwardRight(float speed) throws RuntimeIOException { motorA.backward(speed); motorB.stop(); } public void reverseDirection() throws RuntimeIOException { motorA.reverseDirection(); motorB.reverseDirection(); } public void circleLeft(float speed, float turnRate) { setValues(speed, speed - turnRate); } public void circleRight(float speed, float turnRate) { setValues(speed - turnRate, speed); } public void stop() throws RuntimeIOException { motorA.stop(); motorB.stop(); } public MotorInterface getMotorA() { return motorA; } public MotorInterface getMotorB() { return motorA; } }
mit
CS2103AUG2016-W09-C1/main
src/test/java/seedu/oneline/testutil/TestUtil.java
12476
package seedu.oneline.testutil; import com.google.common.io.Files; import guitests.guihandles.TaskCardHandle; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import junit.framework.AssertionFailedError; import org.loadui.testfx.GuiTest; import org.testfx.api.FxToolkit; import seedu.oneline.TestApp; import seedu.oneline.commons.exceptions.IllegalValueException; import seedu.oneline.commons.util.FileUtil; import seedu.oneline.commons.util.XmlUtil; import seedu.oneline.model.TaskBook; import seedu.oneline.model.tag.Tag; import seedu.oneline.model.tag.TagColorMap; import seedu.oneline.model.tag.UniqueTagList; import seedu.oneline.model.task.*; import seedu.oneline.storage.XmlSerializableTaskBook; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * A utility class for test cases. */ public class TestUtil { public static String LS = System.lineSeparator(); public static void assertThrows(Class<? extends Throwable> expected, Runnable executable) { try { executable.run(); } catch (Throwable actualException) { if (!actualException.getClass().isAssignableFrom(expected)) { String message = String.format("Expected thrown: %s, actual: %s", expected.getName(), actualException.getClass().getName()); throw new AssertionFailedError(message); } else return; } throw new AssertionFailedError( String.format("Expected %s to be thrown, but nothing was thrown.", expected.getName())); } /** * Folder used for temp files created during testing. Ignored by Git. */ public static String SANDBOX_FOLDER = FileUtil.getPath("./src/test/data/sandbox/"); public static final Task[] sampleTaskData = getSampleTaskData(); private static Task[] getSampleTaskData() { try { return new Task[]{ new Task(TypicalTestTasks.event1), new Task(TypicalTestTasks.event2), new Task(TypicalTestTasks.event3), new Task(TypicalTestTasks.todo1), new Task(TypicalTestTasks.todo2), new Task(TypicalTestTasks.todo3), new Task(TypicalTestTasks.float1), new Task(TypicalTestTasks.float2), new Task(TypicalTestTasks.float3) }; } catch (IllegalValueException e) { e.printStackTrace(); assert false; } return null; } public static final Tag[] sampleTagData = getSampleTagData(); private static Tag[] getSampleTagData() { try { return new Tag[]{ Tag.getTag("relatives"), Tag.getTag("friends") }; } catch (IllegalValueException e) { assert false; return null; //not possible } } public static List<Task> generateSampleTaskData() { return Arrays.asList(sampleTaskData); } /** * Appends the file name to the sandbox folder path. * Creates the sandbox folder if it doesn't exist. * @param fileName * @return */ public static String getFilePathInSandboxFolder(String fileName) { try { FileUtil.createDirs(new File(SANDBOX_FOLDER)); } catch (IOException e) { throw new RuntimeException(e); } return SANDBOX_FOLDER + fileName; } // public static void createDataFileWithSampleData(String filePath) { // createDataFileWithData(generateSampleStorageTaskBook(), filePath); // } public static <T> void createDataFileWithData(T data, String filePath) { try { File saveFileForTesting = new File(filePath); FileUtil.createIfMissing(saveFileForTesting); XmlUtil.saveDataToFile(saveFileForTesting, data); } catch (Exception e) { throw new RuntimeException(e); } } // public static void main(String... s) { // createDataFileWithSampleData(TestApp.SAVE_LOCATION_FOR_TESTING); // } public static TaskBook generateEmptyTaskBook() { return new TaskBook(new UniqueTaskList(), new UniqueTagList(), new TagColorMap()); } // public static XmlSerializableTaskBook generateSampleStorageTaskBook() { // return new XmlSerializableTaskBook(generateEmptyTaskBook()); // } // /** // * Tweaks the {@code keyCodeCombination} to resolve the {@code KeyCode.SHORTCUT} to their // * respective platform-specific keycodes // */ // public static KeyCode[] scrub(KeyCodeCombination keyCodeCombination) { // List<KeyCode> keys = new ArrayList<>(); // if (keyCodeCombination.getAlt() == KeyCombination.ModifierValue.DOWN) { // keys.add(KeyCode.ALT); // } // if (keyCodeCombination.getShift() == KeyCombination.ModifierValue.DOWN) { // keys.add(KeyCode.SHIFT); // } // if (keyCodeCombination.getMeta() == KeyCombination.ModifierValue.DOWN) { // keys.add(KeyCode.META); // } // if (keyCodeCombination.getControl() == KeyCombination.ModifierValue.DOWN) { // keys.add(KeyCode.CONTROL); // } // keys.add(keyCodeCombination.getCode()); // return keys.toArray(new KeyCode[]{}); // } // // public static boolean isHeadlessEnvironment() { // String headlessProperty = System.getProperty("testfx.headless"); // return headlessProperty != null && headlessProperty.equals("true"); // } // // public static void captureScreenShot(String fileName) { // File file = GuiTest.captureScreenshot(); // try { // Files.copy(file, new File(fileName + ".png")); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public static String descOnFail(Object... comparedObjects) { // return "Comparison failed \n" // + Arrays.asList(comparedObjects).stream() // .map(Object::toString) // .collect(Collectors.joining("\n")); // } // // public static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException{ // field.setAccessible(true); // // remove final modifier from field // Field modifiersField = Field.class.getDeclaredField("modifiers"); // modifiersField.setAccessible(true); // // ~Modifier.FINAL is used to remove the final modifier from field so that its value is no longer // // final and can be changed // modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); // field.set(null, newValue); // } // // public static void initRuntime() throws TimeoutException { // FxToolkit.registerPrimaryStage(); // FxToolkit.hideStage(); // } // // public static void tearDownRuntime() throws Exception { // FxToolkit.cleanupStages(); // } // // /** // * Gets private method of a class // * Invoke the method using method.invoke(objectInstance, params...) // * // * Caveat: only find method declared in the current Class, not inherited from supertypes // */ // public static Method getPrivateMethod(Class objectClass, String methodName) throws NoSuchMethodException { // Method method = objectClass.getDeclaredMethod(methodName); // method.setAccessible(true); // return method; // } // // public static void renameFile(File file, String newFileName) { // try { // Files.copy(file, new File(newFileName)); // } catch (IOException e1) { // e1.printStackTrace(); // } // } /** * Gets mid point of a node relative to the screen. * @param node * @return */ public static Point2D getScreenMidPoint(Node node) { double x = getScreenPos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; double y = getScreenPos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; return new Point2D(x,y); } // /** // * Gets mid point of a node relative to its scene. // * @param node // * @return // */ // public static Point2D getSceneMidPoint(Node node) { // double x = getScenePos(node).getMinX() + node.getLayoutBounds().getWidth() / 2; // double y = getScenePos(node).getMinY() + node.getLayoutBounds().getHeight() / 2; // return new Point2D(x,y); // } /** * Gets the bound of the node relative to the parent scene. * @param node * @return */ // public static Bounds getScenePos(Node node) { // return node.localToScene(node.getBoundsInLocal()); // } public static Bounds getScreenPos(Node node) { return node.localToScreen(node.getBoundsInLocal()); } // public static double getSceneMaxX(Scene scene) { // return scene.getX() + scene.getWidth(); // } // // public static double getSceneMaxY(Scene scene) { // return scene.getX() + scene.getHeight(); // } // // public static Object getLastElement(List<?> list) { // return list.get(list.size() - 1); // } /** * Removes a subset from the list of tasks. * @param tasks The list of tasks * @param tasksToRemove The subset of tasks. * @return The modified tasks after removal of the subset from tasks. */ public static TestTask[] removeTasksFromList(final TestTask[] tasks, TestTask... tasksToRemove) { List<TestTask> listOfTasks = asList(tasks); listOfTasks.removeAll(asList(tasksToRemove)); return listOfTasks.toArray(new TestTask[listOfTasks.size()]); } /** * Returns a copy of the list with the task at specified index removed. * @param list original list to copy from * @param targetIndexInOneIndexedFormat e.g. if the first element to be removed, 1 should be given as index. */ public static TestTask[] removeTaskFromList(final TestTask[] list, int targetIndexInOneIndexedFormat) { return removeTasksFromList(list, list[targetIndexInOneIndexedFormat-1]); } // /** // * Replaces tasks[i] with a task. // * @param tasks The array of tasks. // * @param task The replacement task // * @param index The index of the task to be replaced. // * @return // */ // public static TestTask[] replaceTaskFromList(TestTask[] tasks, TestTask task, int index) { // tasks[index] = task; // return tasks; // } /** * Appends tasks to the array of tasks. * @param tasks A array of tasks. * @param tasksToAdd The tasks that are to be appended behind the original array. * @return The modified array of tasks. */ public static TestTask[] addTasksToList(final TestTask[] tasks, TestTask... tasksToAdd) { List<TestTask> listOfTasks = asList(tasks); listOfTasks.addAll(asList(tasksToAdd)); return listOfTasks.toArray(new TestTask[listOfTasks.size()]); } private static <T> List<T> asList(T[] objs) { List<T> list = new ArrayList<>(); for(T obj : objs) { list.add(obj); } return list; } public static boolean compareCardAndTask(TaskCardHandle card, ReadOnlyTask task) { return card.isSameTask(task); } // public static Tag[] getTagList(String tags) { // // if (tags.equals("")) { // return new Tag[]{}; // } // // final String[] split = tags.split(", "); // // final List<Tag> collect = Arrays.asList(split).stream().map(e -> { // try { // return Tag.getTag(e.replaceFirst("Tag: ", "")); // } catch (IllegalValueException e1) { // //not possible // assert false; // return null; // } // }).collect(Collectors.toList()); // // return collect.toArray(new Tag[split.length]); // } }
mit
maxdemarzi/neo_airlines
src/main/java/com/maxdemarzi/Expanders/NonStopExpander.java
1581
package com.maxdemarzi.Expanders; import com.maxdemarzi.Helpers.RelationshipTypes; import org.neo4j.graphdb.*; import org.neo4j.graphdb.traversal.BranchState; import java.util.ArrayList; import java.util.Collections; public class NonStopExpander extends BaseExpander { public NonStopExpander(ArrayList<String> destinations, RelationshipType[] relationshipTypes, long stopTime) { super(destinations, relationshipTypes, stopTime); } @Override public Iterable<Relationship> expand(Path path, BranchState state) { if (System.currentTimeMillis() < stopTime) { switch (path.length()) { case 0: return path.endNode().getRelationships(Direction.OUTGOING, RelationshipTypes.HAS_DESTINATION); case 1: { Node lastNode = path.endNode(); if (destinations.contains((String) lastNode.getProperty("code"))) { return path.endNode().getRelationships(Direction.OUTGOING, relationshipTypes); } else { return Collections.emptyList(); } } case 2: case 3: { return path.endNode().getRelationships(Direction.OUTGOING, relationshipTypes); } default: return Collections.emptyList(); } } else { return Collections.emptyList(); } } @Override public PathExpander reverse() { return null; } }
mit
hivsuper/study
design-pattern/src/main/java/org/lxp/design/pattern/chain/responsibility/AbstractInterviewHandler.java
1296
package org.lxp.design.pattern.chain.responsibility; public abstract class AbstractInterviewHandler implements IHandler { public static final int LEVEL_COMMON_EMPLOYEE = 0; public static final int LEVEL_TEAM_LEADER = 1; public static final int LEVEL_MANAGER = 2; public static final int LEVEL_CEO = 3; private String name; private IHandler nextHandler; public AbstractInterviewHandler(String name) { this.name = name; } @Override public void handle(UserInterview application) { if (application.getLevel() >= LEVEL_CEO) { System.out.println("Sorry, no position found for " + application); } else { if (getLevel() > application.getLevel()) { application.approve(name); } if (this.nextHandler != null) { this.nextHandler.handle(application); } else { if (application.isApproved()) { System.out.println("Send an offer for " + application); } else { throw new IllegalAccessError(); } } } } public void setNextHandler(IHandler nextHandler) { this.nextHandler = nextHandler; } public abstract int getLevel(); }
mit
acmi/L2crypt
src/main/java/acmi/l2/clientmod/crypt/rsa/L2Ver41xInputStream.java
5497
/* * Copyright (c) 2021 acmi * * 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 acmi.l2.clientmod.crypt.rsa; import acmi.l2.clientmod.crypt.CryptoException; import javax.crypto.Cipher; import java.io.DataInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.spec.RSAPrivateKeySpec; import java.util.Objects; import java.util.zip.InflaterInputStream; public final class L2Ver41xInputStream extends FilterInputStream implements L2Ver41x { private final int size; public L2Ver41xInputStream(InputStream input, BigInteger modulus, BigInteger exponent) throws IOException, CryptoException { super(null); RSAInputStream rsaInputStream = new RSAInputStream(Objects.requireNonNull(input, "stream"), Objects.requireNonNull(modulus, "modulus"), Objects.requireNonNull(exponent, "exponent")); size = Integer.reverseBytes(new DataInputStream(rsaInputStream).readInt()); in = new InflaterInputStream(rsaInputStream); } public int getSize() { return size; } public static class RSAInputStream extends InputStream { private final DataInputStream input; private final Cipher cipher; private final byte[] buffer = new byte[128]; private int startPosition; private int position; private int size; private boolean closed; public RSAInputStream(InputStream input, BigInteger modulus, BigInteger exponent) throws CryptoException { this.input = new DataInputStream(input); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent); cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(keySpec)); } catch (GeneralSecurityException e) { throw new CryptoException(e); } } private void ensureOpen() throws IOException { if (closed) { throw new IOException("Stream closed"); } } private boolean ensureFilled() throws IOException { if (position == size) { int remaining = buffer.length; while (remaining > 0) { int count = input.read(buffer, buffer.length - remaining, remaining); if (count < 0) { return false; } remaining -= count; } try { cipher.doFinal(buffer, 0, 128, buffer); } catch (GeneralSecurityException e) { throw new CryptoException(e); } size = buffer[3] & 0xff; if (size > 124) { throw new IllegalStateException("block data size too large"); } startPosition = 128 - size - ((124 - size) % 4); position = 0; } return true; } @Override public int read() throws IOException { ensureOpen(); if (!ensureFilled()) { return -1; } return buffer[startPosition + position++] & 0xFF; } @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } ensureOpen(); if (!ensureFilled()) { return -1; } int read = Math.min(len, available()); System.arraycopy(buffer, startPosition + position, b, off, read); position += read; return read; } @Override public int available() throws IOException { ensureOpen(); return size - position; } @Override public void close() throws IOException { if (!closed) { closed = true; input.close(); } } } }
mit
fvm/slackey
service/src/main/java/com/github/fvm/slackey/service/api/v1/commands/ping/domain/entities/Ping.java
354
package com.github.fvm.slackey.service.api.v1.commands.ping.domain.entities; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import lombok.Builder; import lombok.Value; @Value @Builder(toBuilder = true) public class Ping { public final String ping; @JsonPOJOBuilder public static class PingBuilder { /**/ } }
mit
igvteam/igv
src/main/java/org/broad/igv/batch/CommandListener.java
17444
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.broad.igv.batch; import biz.source_code.base64Coder.Base64Coder; import org.broad.igv.logging.LogManager; import org.broad.igv.logging.Logger; import org.broad.igv.Globals; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.google.OAuthUtils; import org.broad.igv.prefs.Constants; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.UIUtilities; import org.broad.igv.util.StringUtils; import java.awt.*; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.URLDecoder; import java.nio.channels.ClosedByInterruptException; import java.security.NoSuchAlgorithmException; import java.util.*; public class CommandListener implements Runnable { public static final String OK = "OK"; // when the listener is successfully started, set this to true. // set this back to false when the listener closes dwm08 private static boolean isListening = false; public static int currentListenerPort = -1; private static Logger log = LogManager.getLogger(CommandListener.class); private static CommandListener listener; private static final String CRLF = "\r\n"; private int port = -1; private ServerSocket serverSocket = null; private Socket clientSocket = null; private Thread listenerThread; boolean halt = false; /** * Different keys which can be used to specify a file to load */ public static Set<String> fileParams; public static Set<String> indexParams; static { String[] fps = new String[]{"file", "bigDataURL", "sessionURL", "dataURL"}; fileParams = new LinkedHashSet<String>(Arrays.asList(fps)); fileParams = Collections.unmodifiableSet(fileParams); indexParams = new HashSet<String>(Arrays.asList("index")); } public static synchronized void start() { start(PreferencesManager.getPreferences().getAsInt(Constants.PORT_NUMBER)); } public static synchronized void start(int port) { try { listener = new CommandListener(port); listener.listenerThread.start(); } catch (Exception e) { listener.closeSockets(); listener = null; log.error(e); } } public static synchronized void halt() { if (listener != null) { listener.halt = true; listener.listenerThread.interrupt(); listener.closeSockets(); listener = null; } } private CommandListener(int port) { this.port = port; listenerThread = new Thread(this); } /** * Return true if the listener is currently enabled * * @return state of listener */ public static boolean isListening() { return listener != null; } /** * Loop forever, processing client requests synchronously. The server is single threaded. * dwm08 - set isListening appropriately */ public void run() { try { CommandExecutor cmdExe = new CommandExecutor(IGV.getInstance()); serverSocket = new ServerSocket(port); log.info("Listening on port " + port); currentListenerPort = port; while (!halt) { clientSocket = serverSocket.accept(); processClientSession(cmdExe); if (clientSocket != null) { try { clientSocket.close(); clientSocket = null; // We do NOT set isListening = false here, otherwise logout/login state change falls back to OOB } catch (IOException e) { log.error("Error in client socket loop", e); } } } } catch (java.net.BindException e) { log.error(e); currentListenerPort = -1; listener = null; } catch (ClosedByInterruptException e) { log.error(e); listener = null; } catch (IOException e) { listener = null; if (!halt) { log.error("IO Error on port socket ", e); } } } /** * Process a client session. Loop continuously until client sends the "halt" message, or closes the connection. * * @param cmdExe * @throws IOException */ private void processClientSession(CommandExecutor cmdExe) throws IOException { PrintWriter out = null; BufferedReader in = null; try { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while (!halt && (inputLine = in.readLine()) != null) { String cmd = inputLine; if(!cmd.contains("/oauthCallback")) { log.info(cmd); } boolean isHTTP = cmd.startsWith("OPTIONS") || cmd.startsWith("HEAD") || cmd.startsWith("GET"); if (isHTTP) { if (cmd.startsWith("OPTIONS")) { sendHTTPOptionsResponse(out); } else { String result = null; String command = null; Map<String, String> params = null; String[] tokens = inputLine.split(" "); if (tokens.length < 2) { result = "ERROR unexpected command line: " + inputLine; } else { String[] parts = tokens[1].split("\\?"); command = parts[0]; params = parts.length < 2 ? new HashMap() : parseParameters(parts[1]); } // Consume the remainder of the request, if any. This is important to free the connection. Map<String, String> headers = new HashMap<>(); String nextLine = in.readLine(); while (nextLine != null && nextLine.length() > 0) { nextLine = in.readLine(); String[] headerTokens = Globals.colonPattern.split(nextLine, 2); if (headerTokens.length == 2) { headers.put(headerTokens[0].trim(), headerTokens[1].trim()); } } if (cmd.startsWith("HEAD")) { sendHTTPResponse(out, result, "text/html", "HEAD"); } else { if (command != null) { // Detect google oauth callback if (command.equals("/oauthCallback")) { if (params.containsKey("code")) { OAuthUtils.getInstance().setAuthorizationCode(params); } else if (params.containsKey("token")) { OAuthUtils.getInstance().setAccessToken(params); } sendTextResponse(out, "SUCCESS"); if(PreferencesManager.getPreferences().getAsBoolean(Constants.PORT_ENABLED) == false) { // Turn off port halt(); } } else { // Process the request. result = processGet(command, params, cmdExe); // Send no response if result is "OK". if ("OK".equals(result)) result = null; sendTextResponse(out, result); } } } } // http sockets are used for one request only => return will close the socket return; } else { // Port command try { Globals.setBatch(true); String finalInputLine = inputLine; PrintWriter finalOut = out; UIUtilities.invokeAndWaitOnEventThread(() -> { final String response = cmdExe.execute(finalInputLine); finalOut.println(response); finalOut.flush(); }); } finally { Globals.setBatch(false); } } } } catch (IOException e) { log.error("Error processing client session", e); } finally { Globals.setSuppressMessages(false); Globals.setBatch(false); if (out != null) out.close(); if (in != null) in.close(); } } private void closeSockets() { if (clientSocket != null) { try { clientSocket.close(); clientSocket = null; } catch (IOException e) { log.error("Error closing clientSocket", e); } } if (serverSocket != null) { try { serverSocket.close(); serverSocket = null; } catch (IOException e) { log.error("Error closing server socket", e); } } } private static final String HTTP_RESPONSE = "HTTP/1.1 200 OK"; private static final String HTTP_NO_RESPONSE = "HTTP/1.1 204 No Response"; private static final String CONNECTION_CLOSE = "Connection: close"; private static final String NO_CACHE = "Cache-Control: no-cache, no-store"; private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin: *"; private void sendTextResponse(PrintWriter out, String result) { sendHTTPResponse(out, result, "text/html", "GET"); } private void sendHTTPResponse(PrintWriter out, String result, String contentType, String method) { out.print(result == null ? HTTP_NO_RESPONSE : HTTP_RESPONSE); out.print(CRLF); out.print(ACCESS_CONTROL_ALLOW_ORIGIN); out.print(CRLF); if (result != null) { out.print("Content-Type: " + contentType); out.print(CRLF); out.print("Content-Length: " + (result.length())); out.print(CRLF); out.print(NO_CACHE); out.print(CRLF); out.print(CONNECTION_CLOSE); out.print(CRLF); if (!method.equals("HEAD")) { out.print(CRLF); out.print(result); out.print(CRLF); } } out.close(); } private void sendHTTPOptionsResponse(PrintWriter out) { out.print(HTTP_NO_RESPONSE); out.print(CRLF); out.print(ACCESS_CONTROL_ALLOW_ORIGIN); out.print(CRLF); out.println("Access-Control-Allow-Methods: HEAD, GET, OPTIONS"); out.print(CRLF); out.close(); } /** * Process an http get request. */ private String processGet(String command, Map<String, String> params, CommandExecutor cmdExe) throws IOException { String result = OK; final Frame mainFrame = IGV.getInstance().getMainFrame(); // Trick to force window to front, the setAlwaysOnTop works on a Mac, toFront() does nothing. mainFrame.toFront(); mainFrame.setAlwaysOnTop(true); mainFrame.setAlwaysOnTop(false); if (command.equals("/load")) { String file = null; for (String fp : fileParams) { file = params.get(fp); if (file != null) break; } String genome = params.get("genome"); if (genome == null) { genome = params.get("db"); // <- UCSC track line param } if (genome != null) { GenomeManager.getInstance().loadGenomeById(genome); } if (file != null) { String mergeValue = params.get("merge"); if (mergeValue != null) mergeValue = URLDecoder.decode(mergeValue, "UTF-8"); // Default for merge is "false" for session files, "true" otherwise boolean merge; if (mergeValue != null) { // Explicit setting merge = mergeValue.equalsIgnoreCase("true"); } else if (file.endsWith(".xml") || file.endsWith(".php") || file.endsWith(".php3")) { // Session file merge = false; } else { // Data file merge = true; } String name = params.get("name"); String format = params.get("format"); String locus = params.get("locus"); String index = params.get("index"); String coverage = params.get("coverage"); String sort = params.get("sort"); String sortTag = params.get("sortTag"); result = cmdExe.loadFiles(file, index, coverage, name, format, locus, merge, params, sort, sortTag); } else { result = "OK"; // No files, perhaps genome only } } else if (command.equals("/reload") || command.equals("/goto")) { String locus = params.get("locus"); IGV.getInstance().goToLocus(locus); } else if (command.equals("/execute")) { String param = StringUtils.decodeURL(params.get("command")); return cmdExe.execute(param); } else { return ("ERROR Unknown command: " + command); } return result; } /** * Parse the html parameter string into a set of key-value pairs. Parameter values are * url decoded with the exception of the "locus" parameter. * * @param parameterString * @return */ private Map<String, String> parseParameters(String parameterString) { // Do a partial decoding now (ampersands only) parameterString = parameterString.replace("&amp;", "&"); HashMap<String, String> params = new HashMap(); String[] kvPairs = parameterString.split("&"); for (String kvString : kvPairs) { // Split on the first "=", all others are part of the parameter value String[] kv = kvString.split("=", 2); if (kv.length == 1) { params.put(kv[0], null); } else { String key = StringUtils.decodeURL(kv[0]); //This might look backwards, but it isn't. //Parameters must be URL encoded, including the file parameter //CommandExecutor URL-decodes the file parameter sometimes, but not always //So we URL-decode iff CommandExecutor doesn't boolean cmdExeWillDecode = (fileParams.contains(key) || indexParams.contains(key)) && CommandExecutor.needsDecode(kv[1]); String value = cmdExeWillDecode ? kv[1] : StringUtils.decodeURL(kv[1]); params.put(kv[0], value); } } return params; } /** * Compute a socket key according to the WebSocket RFC. This method is here because this is the only class that uses it. * * @param input * @return * @throws NoSuchAlgorithmException */ static String computeResponseKey(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException { java.security.MessageDigest digest = null; digest = java.security.MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(input.getBytes("UTF-8")); return new String(Base64Coder.encode(digest.digest())); } }
mit
kostadin-kar/test-repository
Spring_Data_exam/src/main/java/hiberspring/repository/TownRepository.java
345
package hiberspring.repository; import hiberspring.domain.entities.Town; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface TownRepository extends JpaRepository<Town, Integer> { Optional<Town> findByName(String name); }
mit
berryma4/diirt
pvmanager/datasource-timecache/src/main/java/org/diirt/datasource/timecache/util/IntervalsList.java
14233
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.timecache.util; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import org.diirt.util.time.TimeDuration; import org.diirt.util.time.TimeInterval; import org.diirt.util.time.Timestamp; /** * This class represents an intervals list. <p> An interval list represent a * list of contiguous regions on the real line. All intervals of the list are * disjoints to each other, they are stored in ascending order. </p> <p> The * class supports the main set operations like union and intersection. </p> * @author Fred Arnaud (Sopra Group) - ITER */ public class IntervalsList { public static final TimeDuration minDuration = TimeDuration.ofNanos(1); /** The list of intervals. */ private List<TimeInterval> intervals; /** * Build an empty intervals list. */ public IntervalsList() { intervals = new ArrayList<TimeInterval>(); } /** * Build an intervals list containing only one interval. * @param i interval */ public IntervalsList(TimeInterval i) { intervals = new ArrayList<TimeInterval>(); i = CacheHelper.arrange(i); intervals.add(i); } /** * Build an intervals list containing two intervals. * @param i1 first interval * @param i2 second interval */ public IntervalsList(TimeInterval i1, TimeInterval i2) { intervals = new ArrayList<TimeInterval>(); i1 = CacheHelper.arrange(i1); i2 = CacheHelper.arrange(i2); if (CacheHelper.intersects(i1, i2)) { intervals.add(TimeInterval.between( CacheHelper.min(i1.getStart(), i2.getStart()), CacheHelper.max(i1.getEnd(), i2.getEnd()))); } else if (i1.getEnd().compareTo(i2.getStart()) < 0) { intervals.add(i1); intervals.add(i2); } else { intervals.add(i2); intervals.add(i1); } } /** * Copy constructor. <p> The copy operation is a deep copy: the underlying * intervals are independant of the instances of the copied list. </p> * @param list intervals list to copy */ public IntervalsList(IntervalsList list) { intervals = new ArrayList<TimeInterval>(list.intervals.size()); for (Iterator<TimeInterval> iterator = list.intervals.iterator(); iterator .hasNext();) { TimeInterval ti = (TimeInterval) iterator.next(); intervals.add(TimeInterval.between(ti.getStart(), ti.getEnd())); } } /** * Check if the instance is empty. * @return true if the instance is empty */ public boolean isEmpty() { return intervals.isEmpty(); } /** * Check if the instance is connected. <p> An interval list is connected if * it contains only one interval. </p> * @return true is the instance is connected */ public boolean isConnex() { return intervals.size() == 1; } /** * Get the lower bound of the list. * @return lower bound of the list or null if the list does not contain any * interval */ public Timestamp getStart() { return intervals.isEmpty() ? null : intervals.get(0).getStart(); } /** * Get the upper bound of the list. * @return upper bound of the list or null if the list does not contain any * interval */ public Timestamp getEnd() { return intervals.isEmpty() ? null : intervals.get(intervals.size() - 1) .getEnd(); } /** * Get the number of intervals of the list. * @return number of intervals in the list */ public int getSize() { return intervals.size(); } /** * Get an interval from the list. * @param i index of the interval * @return interval at index i */ public TimeInterval getTimeInterval(int i) { return intervals.get(i); } /** * Get the ordered list of disjoints intervals. * @return list of disjoints intervals in ascending order */ public List<TimeInterval> getIntervals() { return intervals; } /** * Check if the list contains a point. * @param t point to check * @return true if the list contains t */ public boolean contains(Timestamp t) { if (t == null) return false; for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) if (iterator.next().contains(t)) return true; return false; } /** * Check if the list contains an interval. * @param i interval to check * @return true if i is completely included in the instance */ public boolean contains(TimeInterval i) { if (i == null) return false; for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) if (CacheHelper.contains(iterator.next(), i)) return true; return false; } /** * Check if an interval intersects the instance. * @param i interval to check * @return true if i intersects the instance */ public boolean intersects(TimeInterval i) { if (i == null) return false; for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) if (CacheHelper.intersects(iterator.next(), i)) return true; return false; } /** * Add an interval to the instance. <p> This method expands the instance. * </p> <p> This operation is a union operation. The number of intervals in * the list can decrease if the interval fills some holes between existing * intervals in the list. </p> * @param i interval to add to the instance */ public void addToSelf(TimeInterval i) { if (i == null) return; if (isConnex() && getStart() == null && getEnd() == null) return; if (i.getStart() == null || i.getEnd() == null) { handleAddNull(i); return; } i = CacheHelper.arrange(i); List<TimeInterval> newIntervals = new ArrayList<TimeInterval>(); Timestamp inf = null; Timestamp sup = null; boolean pending = false; boolean processed = false; for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) { TimeInterval local = iterator.next(); if (local.getEnd() != null && local.getEnd().compareTo(i.getStart()) < 0) { newIntervals.add(local); } else if (local.getStart() == null || local.getStart().compareTo(i.getEnd()) <= 0) { if (!pending) { inf = CacheHelper.min(local.getStart(), i.getStart()); pending = true; processed = true; } sup = CacheHelper.max(local.getEnd(), i.getEnd()); } else { if (pending) { newIntervals.add(TimeInterval.between(inf, sup)); pending = false; } else if (!processed) { newIntervals.add(i); } processed = true; newIntervals.add(local); } } if (pending) { newIntervals.add(TimeInterval.between(inf, sup)); } else if (!processed) { newIntervals.add(i); } intervals = mergeAllLimits(newIntervals); } private void handleAddNull(TimeInterval i) { List<TimeInterval> newIntervals = new ArrayList<TimeInterval>(); if (i.getStart() == null && i.getEnd() == null) { newIntervals.add(TimeInterval.between(null, null)); } else if (i.getStart() == null && i.getEnd() != null) { Timestamp sup = i.getEnd(); for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) { TimeInterval local = iterator.next(); if (local.getStart() == null || local.getStart().compareTo(i.getEnd()) <= 0) sup = CacheHelper.max(local.getEnd(), sup); else newIntervals.add(local); } newIntervals.add(TimeInterval.between(null, sup)); } else if (i.getStart() != null && i.getEnd() == null) { Timestamp inf = i.getStart(); for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) { TimeInterval local = iterator.next(); if (local.getEnd() == null || local.getEnd().compareTo(i.getStart()) >= 0) inf = CacheHelper.min(local.getStart(), inf); else newIntervals.add(local); } newIntervals.add(TimeInterval.between(inf, null)); } intervals = newIntervals; } private List<TimeInterval> mergeAllLimits(List<TimeInterval> intervals) { List<TimeInterval> newIntervals = new ArrayList<TimeInterval>(); Iterator<TimeInterval> iterator = intervals.iterator(); TimeInterval previous = null; TimeInterval current = null; if (iterator.hasNext()) current = iterator.next(); while (iterator.hasNext()) { previous = current; current = iterator.next(); if (previous.getEnd().plus(minDuration).equals(current.getStart())) { TimeInterval merged = TimeInterval.between(previous.getStart(), current.getEnd()); current = merged; } else { newIntervals.add(previous); } } if (current != null) newIntervals.add(current); return newIntervals; } /** * Add an intervals list and an interval. * @param list intervals list * @param i interval * @return a new intervals list which is the union of list and i */ public static IntervalsList add(IntervalsList list, TimeInterval i) { IntervalsList copy = new IntervalsList(list); copy.addToSelf(i); return copy; } /** * Remove an interval from the list. <p> This method reduces the instance. * This operation is defined in terms of points set operation. As an * example, if the [2, 3] interval is subtracted from the list containing * only the [0, 10] interval, the result will be the [0, 2] U [3, 10] * intervals list. </p> * @param i interval to remove */ public void subtractFromSelf(TimeInterval i) { if (i == null) return; if (i.getStart() == null && i.getEnd() == null) { intervals.clear(); return; } IntervalsList inversedIntervals = new IntervalsList(); if (i.getStart() == null && i.getEnd() != null) { inversedIntervals.addToSelf(TimeInterval.between(i.getEnd().plus(minDuration), null)); } else if (i.getStart() != null && i.getEnd() == null) { inversedIntervals.addToSelf(TimeInterval.between(null, i.getStart().minus(minDuration))); } else { i = CacheHelper.arrange(i); inversedIntervals.addToSelf(TimeInterval.between(null, i.getStart().minus(minDuration))); inversedIntervals.addToSelf(TimeInterval.between(i.getEnd().plus(minDuration), null)); } intersectSelf(inversedIntervals); } /** * Remove an interval from a list. * @param list intervals list * @param i interval to remove * @return a new intervals list */ public static IntervalsList subtract(IntervalsList list, TimeInterval i) { IntervalsList copy = new IntervalsList(list); copy.subtractFromSelf(i); return copy; } /** * Intersects the instance and an interval. * @param i interval */ public void intersectSelf(TimeInterval i) { List<TimeInterval> newIntervals = new ArrayList<TimeInterval>(); for (Iterator<TimeInterval> iterator = intervals.iterator(); iterator .hasNext();) { TimeInterval local = iterator.next(); if (CacheHelper.intersects(local, i)) { newIntervals.add(CacheHelper.intersection(local, i)); } } intervals = newIntervals; } /** * Intersect a list and an interval. * @param list intervals list * @param i interval * @return the intersection of list and i */ public static IntervalsList intersection(IntervalsList list, TimeInterval i) { IntervalsList copy = new IntervalsList(list); copy.intersectSelf(i); return copy; } /** * Add an intervals list to the instance. <p> This method expands the * instance. </p> <p> This operation is a union operation. The number of * intervals in the list can decrease if the list fills some holes between * existing intervals in the instance. </p> * @param list intervals list to add to the instance */ public void addToSelf(IntervalsList list) { if (list == null) return; for (Iterator<TimeInterval> iterator = list.intervals.iterator(); iterator .hasNext();) { addToSelf(iterator.next()); } } /** * Add two intervals lists. * @param list1 first intervals list * @param list2 second intervals list * @return a new intervals list which is the union of list1 and list2 */ public static IntervalsList add(IntervalsList list1, IntervalsList list2) { IntervalsList copy = new IntervalsList(list1); copy.addToSelf(list2); return copy; } /** * Remove an intervals list from the instance. * @param list intervals list to remove */ public void subtractFromSelf(IntervalsList list) { if (list == null) return; for (Iterator<TimeInterval> iterator = list.intervals.iterator(); iterator .hasNext();) { subtractFromSelf(iterator.next()); } } /** * Remove an intervals list from another one. * @param list1 intervals list * @param list2 intervals list to remove * @return a new intervals list */ public static IntervalsList subtract(IntervalsList list1, IntervalsList list2) { IntervalsList copy = new IntervalsList(list1); copy.subtractFromSelf(list2); return copy; } /** * Intersect the instance and another intervals list. * @param list list to intersect with the instance */ public void intersectSelf(IntervalsList list) { intervals = intersection(this, list).intervals; } /** * Intersect two intervals lists. * @param list1 first intervals list * @param list2 second intervals list * @return a new list which is the intersection of list1 and list2 */ public static IntervalsList intersection(IntervalsList list1, IntervalsList list2) { IntervalsList list = new IntervalsList(); for (Iterator<TimeInterval> iterator = list2.intervals.iterator(); iterator .hasNext();) { list.addToSelf(intersection(list1, iterator.next())); } return list; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("IntervalsList [intervals="); for (TimeInterval ti : intervals) { sb.append(CacheHelper.format(ti)); sb.append(", "); } if (intervals.size() > 0) sb.delete(sb.length() - 2, sb.length()); sb.append("]"); return sb.toString(); } }
mit
pram/puzzles
src/main/java/com/naughtyzombie/ci/dataandstrings/matrixsetzero/MatrixSetZero.java
1172
package com.naughtyzombie.ci.dataandstrings.matrixsetzero; import com.naughtyzombie.ci.lib.AssortedMethods; /** * Created by pram on 02/07/2015. */ public class MatrixSetZero { public static void main(String[] args) { int[][] matrix = AssortedMethods.randomMatrix(5, 5, 0, 9); AssortedMethods.printMatrix(matrix); matrixSetZero(matrix); System.out.println(); AssortedMethods.printMatrix(matrix); } private static void matrixSetZero(int[][] matrix) { int rows = matrix.length; boolean[] zeroRows = new boolean[rows]; int columns = matrix[0].length; boolean[] zeroColumns = new boolean[columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { if (matrix[r][c] == 0) { zeroRows[r] = true; zeroColumns[c] = true; } } } for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { if (zeroRows[r] || zeroColumns[c]) { matrix[r][c] = 0; } } } } }
mit
akkirilov/SoftUniProject
04_DB Frameworks_Hibernate+Spring Data/01_Java basics/src/ChangeToUppercase.java
594
import java.util.Scanner; public class ChangeToUppercase { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); StringBuffer sb = new StringBuffer(scanner.nextLine()); scanner.close(); int start; int end; String word; while (sb.toString().contains("<upcase>")) { start = sb.indexOf("<upcase>"); end = sb.indexOf("</upcase>"); word = sb.substring(start + 8, end).toUpperCase(); sb.replace(start + 8, end, word); sb.delete(start, start + 8); sb.delete(end - 8, end + 1); } System.out.printf("%s%n", sb); } }
mit