blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
52165e8daf8187005c0bf4ae20eb9b2d6e550a3d
8228efa27043e0a236ca8003ec0126012e1fdb02
/L2JOptimus_Core/java/net/sf/l2j/gameserver/scripting/quests/Q050_LanoscosSpecialBait.java
a470f8965cb2ab4927539aac7a41e7fd1c4714b8
[]
no_license
wan202/L2JDeath
9982dfce14ae19a22392955b996b42dc0e8cede6
e0ab026bf46ac82c91bdbd048a0f50dc5213013b
refs/heads/master
2020-12-30T12:35:59.808276
2017-05-16T18:57:25
2017-05-16T18:57:25
91,397,726
0
1
null
null
null
null
UTF-8
Java
false
false
2,297
java
package net.sf.l2j.gameserver.scripting.quests; import net.sf.l2j.gameserver.model.actor.Npc; import net.sf.l2j.gameserver.model.actor.instance.Player; import net.sf.l2j.gameserver.scripting.Quest; import net.sf.l2j.gameserver.scripting.QuestState; import net.sf.l2j.gameserver.scripting.quests.audio.Sound; public class Q050_LanoscosSpecialBait extends Quest { private static final String qn = "Q050_LanoscosSpecialBait"; // Item private static final int ESSENCE_OF_WIND = 7621; // Reward private static final int WIND_FISHING_LURE = 7610; public Q050_LanoscosSpecialBait() { super(50, "Lanosco's Special Bait"); setItemsIds(ESSENCE_OF_WIND); addStartNpc(31570); // Lanosco addTalkId(31570); addKillId(21026); // Singing wind } @Override public String onAdvEvent(String event, Npc npc, Player player) { String htmltext = event; QuestState st = player.getQuestState(qn); if (st == null) return htmltext; if (event.equalsIgnoreCase("31570-03.htm")) { st.setState(STATE_STARTED); st.set("cond", "1"); st.playSound(Sound.SOUND_ACCEPT); } else if (event.equalsIgnoreCase("31570-07.htm")) { htmltext = "31570-06.htm"; st.takeItems(ESSENCE_OF_WIND, -1); st.rewardItems(WIND_FISHING_LURE, 4); st.playSound(Sound.SOUND_FINISH); st.exitQuest(false); } return htmltext; } @Override public String onTalk(Npc npc, Player player) { QuestState st = player.getQuestState(qn); String htmltext = getNoQuestMsg(); if (st == null) return htmltext; switch (st.getState()) { case STATE_CREATED: htmltext = (player.getLevel() < 27) ? "31570-02.htm" : "31570-01.htm"; break; case STATE_STARTED: htmltext = (st.getQuestItemsCount(ESSENCE_OF_WIND) == 100) ? "31570-04.htm" : "31570-05.htm"; break; case STATE_COMPLETED: htmltext = getAlreadyCompletedMsg(); break; } return htmltext; } @Override public String onKill(Npc npc, Player player, boolean isPet) { QuestState st = checkPlayerCondition(player, npc, "cond", "1"); if (st == null) return null; if (st.dropItems(ESSENCE_OF_WIND, 1, 100, 500000)) st.set("cond", "2"); return null; } }
[ "wande@DESKTOP-DM71DUV" ]
wande@DESKTOP-DM71DUV
6a920cd9980640c6bf42cab1ce9533ea6aaec71b
32419c55feb8f0c8ea51fa234c94bccf3910663e
/app/src/main/java/com/example/anand/moviezone/MoviesData.java
917c881349848fc1dbfab8d11d6d2da1715247a1
[]
no_license
anandsyncs/MovieZoneProject
8738135d80ade1924922dcf93cfa7007a15ead2f
a143de592600637e41f1aab8b92f554a11a7997b
refs/heads/master
2023-07-07T03:38:54.805935
2016-09-21T04:41:01
2016-09-21T04:41:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
330
java
package com.example.anand.moviezone; import android.graphics.Bitmap; import android.media.Image; /** * Created by anand on 06/06/16. */ public class MoviesData { String movieName; Bitmap image; public MoviesData(String movieName, Bitmap image){ this.movieName=movieName; this.image=image; } }
ea12a4e5260da5e8b1b25e414dcf560d91c329c6
8e704c03eb7a27db8bb1fa13bde577760948aaf3
/pomelo-parent/pomelo-core/src/main/java/pomelo/core/datasource/DynamicDataSource.java
492da003f764e14355902fbb27be6e59c62b57bc
[]
no_license
PomeloMan/pomelo
fc74ad3ac882c832eacdc5c08a8d2d0cfde8dadb
ae5c365667be3ab64f3a6dd7d15ea4d2139376e8
refs/heads/master
2021-06-26T02:04:35.645781
2019-04-28T07:53:26
2019-04-28T07:53:26
125,967,782
0
0
null
null
null
null
UTF-8
Java
false
false
696
java
package pomelo.core.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import pomelo.core.datasource.annotation.DataSource.DataSources; /** * Dynamic dataSource * * @author Pomelor */ public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<DataSources> context = new ThreadLocal<>(); @Override protected Object determineCurrentLookupKey() { return getDataSource(); } public static void setDataSource(DataSources dataSource) { context.set(dataSource); } public static DataSources getDataSource() { return context.get(); } public static void clearDataSource() { context.remove(); } }
3b08decc07d8764a42f1542bd782b44695db11b1
f942a22c1e1fac7fa124ce0c2149946b175401ec
/src/main/java/com/quickstart/bbframework/common/service/RedisService.java
3a65d1a0a4fc1f22719eb21b4fa8da83f0342390
[ "Apache-2.0" ]
permissive
halower/bbframework-project
b6c97d5818a607a771bbd6c43b9440afec1cbeb9
7721c49e9356a384becbf3ba01a0854ee1819098
refs/heads/main
2023-02-28T12:54:57.297738
2021-02-08T09:11:46
2021-02-08T09:11:46
337,016,435
0
0
null
null
null
null
UTF-8
Java
false
false
3,429
java
package com.quickstart.bbframework.common.service; import java.util.List; import java.util.Map; import java.util.Set; /** * redis操作Service */ public interface RedisService { /** * 保存属性 */ void set(String key, Object value, long time); /** * 保存属性 */ void set(String key, Object value); /** * 获取属性 */ Object get(String key); /** * 删除属性 */ Boolean del(String key); /** * 批量删除属性 */ Long del(List<String> keys); /** * 设置过期时间 */ Boolean expire(String key, long time); /** * 获取过期时间 */ Long getExpire(String key); /** * 判断是否有该属性 */ Boolean hasKey(String key); /** * 按delta递增 */ Long incr(String key, long delta); /** * 按delta递减 */ Long decr(String key, long delta); /** * 获取Hash结构中的属性 */ Object hGet(String key, String hashKey); /** * 向Hash结构中放入一个属性 */ Boolean hSet(String key, String hashKey, Object value, long time); /** * 向Hash结构中放入一个属性 */ void hSet(String key, String hashKey, Object value); /** * 直接获取整个Hash结构 */ Map<Object, Object> hGetAll(String key); /** * 直接设置整个Hash结构 */ Boolean hSetAll(String key, Map<String, Object> map, long time); /** * 直接设置整个Hash结构 */ void hSetAll(String key, Map<String, ?> map); /** * 删除Hash结构中的属性 */ void hDel(String key, Object... hashKey); /** * 判断Hash结构中是否有该属性 */ Boolean hHasKey(String key, String hashKey); /** * Hash结构中属性递增 */ Long hIncr(String key, String hashKey, Long delta); /** * Hash结构中属性递减 */ Long hDecr(String key, String hashKey, Long delta); /** * 获取Set结构 */ Set<Object> sMembers(String key); /** * 向Set结构中添加属性 */ Long sAdd(String key, Object... values); /** * 向Set结构中添加属性 */ Long sAdd(String key, long time, Object... values); /** * 是否为Set中的属性 */ Boolean sIsMember(String key, Object value); /** * 获取Set结构的长度 */ Long sSize(String key); /** * 删除Set结构中的属性 */ Long sRemove(String key, Object... values); /** * 获取List结构中的属性 */ List<Object> lRange(String key, long start, long end); /** * 获取List结构的长度 */ Long lSize(String key); /** * 根据索引获取List中的属性 */ Object lIndex(String key, long index); /** * 向List结构中添加属性 */ Long lPush(String key, Object value); /** * 向List结构中添加属性 */ Long lPush(String key, Object value, long time); /** * 向List结构中批量添加属性 */ Long lPushAll(String key, Object... values); /** * 向List结构中批量添加属性 */ Long lPushAll(String key, Long time, Object... values); /** * 从List结构中移除属性 */ Long lRemove(String key, long count, Object value); }
2a04711fe6cd86b4d242ec036000866da8059471
58b00824ae7913b1b90c1d81f0a529aeb4bc373e
/MyEJBTestClient/src/net/mv/ejb/ex2/HelloWorldTestCLient.java
f64ba16282e9e303c27ae09fad8640967c86f605
[]
no_license
bhpham/EJB-Practices
cf8a1c26ace432d097f32051ad7f53e0402118a6
67ef5baf029a203a837e58e8475b82fd660283eb
refs/heads/master
2021-01-10T14:15:12.835177
2015-10-14T00:30:01
2015-10-14T00:30:01
44,213,870
0
0
null
null
null
null
UTF-8
Java
false
false
2,506
java
package net.mv.ejb.ex2; import java.util.Properties; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import weblogic.jndi.WLInitialContextFactory; public class HelloWorldTestCLient { public static void main(String[] args) { Properties props = new Properties(); props.put(Context.PROVIDER_URL, "t3://localhost:7001"); props.put(Context.INITIAL_CONTEXT_FACTORY, WLInitialContextFactory.class.getName()); Context ctx = null; try { ctx = new InitialContext(props); // HelloWorldRemote hwr = (HelloWorldRemote) ctx.lookup("myEJB#" + HelloWorldRemote.class.getName()); // // String result = hwr.sayHello("Binh"); // System.out.println(result); // // StatefulHelloWorldRemote shwr = (StatefulHelloWorldRemote) ctx.lookup("myStatefulEJB#" + StatefulHelloWorldRemote.class.getName()); // // int i = 0; // while ( i < 10 ) { // System.out.println(shwr.sayHello("Tom")); // i++; // } QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup("weblogic.jms.ConnectionFactory"); QueueConnection qc = qcf.createQueueConnection(); Queue destinationQueue = (Queue) ctx.lookup("jms/queue"); QueueSession qSession = qc.createQueueSession(false, 0); QueueSender qSender = qSession.createSender(destinationQueue); TextMessage tm = qSession.createTextMessage("blah blah donuts from Deepak, since he was on facebook"); qSender.send(tm); TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("weblogic.jms.ConnectionFactory"); TopicConnection tc = tcf.createTopicConnection(); Topic destinationTopic = (Topic) ctx.lookup("jms/topic"); TopicSession tSession = tc.createTopicSession(false, 0); TopicPublisher tPublisher = tSession.createPublisher(destinationTopic); tm = tSession.createTextMessage("blah blah bagels from Ankit"); tPublisher.publish(tm); } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
633d2d6f41fbcc735b184c68f5df8fb10083c9d8
e2c2fef3bb7942a62a3b874665ca1e5bd4cb175c
/co.gruposaberes.rails.parser.models/xtend-gen/co/gruposaberes/rails/parser/generator/ModelsGenerator.java
ea24c9ca5b94ecfd70c7d1b40a20b30e033ed1f9
[]
no_license
jairud-garcia/rails-model-extractor
e1397f5b51227c2d937c3ef42af67c91d0125d1f
5c0eeb55bec96bb33228a1b59c3ff12a2d5da8b2
refs/heads/master
2020-05-25T00:26:48.111062
2017-03-14T01:43:17
2017-03-14T01:43:17
84,892,659
1
0
null
null
null
null
UTF-8
Java
false
false
667
java
/** * generated by Xtext 2.10.0 */ package co.gruposaberes.rails.parser.generator; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.generator.AbstractGenerator; import org.eclipse.xtext.generator.IFileSystemAccess2; import org.eclipse.xtext.generator.IGeneratorContext; /** * Generates code from your model files on save. * * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation */ @SuppressWarnings("all") public class ModelsGenerator extends AbstractGenerator { @Override public void doGenerate(final Resource resource, final IFileSystemAccess2 fsa, final IGeneratorContext context) { } }
ba20228c03a77a00a07616819e7448e40c3df424
c03f34fd12db4d1a704073c2ba448b6a68309c8a
/com.mind_era.knime.hits.interop/src/com/mind_era/knime/hits/plate/format/PlateFormatNodeModel.java
e5dca343f485e7267301694e18750db127fa3df6
[ "Apache-2.0" ]
permissive
aravindprasad/hits
1e4d4b1b394bb31e7215b7d89fba22334c03a712
a92ab8ff1ecaf6a0ea656fa0a36b374906bcdbfe
refs/heads/master
2022-04-04T13:17:42.529938
2020-03-01T09:41:35
2020-03-01T10:43:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,526
java
package com.mind_era.knime.hits.plate.format; import java.io.File; import java.io.IOException; import javax.annotation.Nullable; import org.knime.core.data.DataCell; import org.knime.core.data.DataColumnSpec; import org.knime.core.data.DataRow; import org.knime.core.data.DataTableSpec; import org.knime.core.data.DataType; import org.knime.core.data.IntValue; import org.knime.core.data.container.AbstractCellFactory; import org.knime.core.data.container.ColumnRearranger; import org.knime.core.data.def.IntCell; import org.knime.core.node.BufferedDataTable; import org.knime.core.node.CanceledExecutionException; import org.knime.core.node.ExecutionContext; import org.knime.core.node.ExecutionMonitor; import org.knime.core.node.InvalidSettingsException; import org.knime.core.node.NodeLogger; import org.knime.core.node.NodeModel; import org.knime.core.node.NodeSettingsRO; import org.knime.core.node.NodeSettingsWO; import org.knime.core.node.defaultnodesettings.SettingsModelEnum; import org.knime.core.node.defaultnodesettings.SettingsModelEnumWithIcon; import com.mind_era.knime.common.Format; /** * This is the model implementation of Plate Format. Converts between 96, 384, * 1536 format plates. It is also capable of mixing replicates in. * * @author <a href="[email protected]">Gabor Bakos</a> */ public class PlateFormatNodeModel extends NodeModel { /** * This class computes the new indices for plates/replicates/rows/columns. */ static final class PlateFormatCellFactory extends AbstractCellFactory { /** */ private final int plateIndex; /** */ private final int rowIndex; /** */ private final int colIndex; private final DataCell[] EMPTY = new DataCell[] { DataType.getMissingCell(), DataType.getMissingCell(), DataType.getMissingCell() }; private final Format from; private final Format to; private final CombinationPattern pattern; /** * Constructs {@link PlateFormatCellFactory}. * * @param colSpecs * The input table's {@link DataColumnSpec}s (order: {@code * plate}, {@code row}, {@code col}). * @param plateIndex * The index of the {@code plate} column in the input. * @param rowIndex * The index of the {@code row} column in the input. * @param colIndex * The index of the {@code col} column in the input. * @param from * The input table {@link Format}. * @param to * The output table {@link Format}. * @param pattern * The {@link CombinationPattern} to use. */ PlateFormatCellFactory(final DataColumnSpec[] colSpecs, final int plateIndex, final int rowIndex, final int colIndex, final Format from, final Format to, final CombinationPattern pattern) { super(colSpecs); this.plateIndex = plateIndex; this.rowIndex = rowIndex; this.colIndex = colIndex; this.from = from; this.to = to; this.pattern = pattern; if (pattern.isCombineReplicates()) { throw new UnsupportedOperationException( "Support for replicates is not implemented"); } if (pattern.getPipettes() != 0) { assert to.getRow() % pattern.getPipettes() == 0 : "to.getRow: " + to.getRow() + "\npipettes: " + pattern.getPipettes(); } } @Override public DataCell[] getCells(final DataRow dataRow) { final Integer oldPlate = getCell(dataRow, plateIndex); final Integer oldRow = getCell(dataRow, rowIndex); final Integer oldCol = getCell(dataRow, colIndex); if (oldPlate == null || oldRow == null || oldCol == null) { return EMPTY; } final int plate = oldPlate.intValue() - 1; final int row = oldRow.intValue() - 1; final int col = oldCol.intValue() - 1; final int newPlate = pattern .plateCompute(plate, row, col, from, to); final int newRow = pattern.rowCompute(plate, row, from, to); final int newCol = pattern.colCompute(plate, col, from, to); return new DataCell[] { new IntCell(newPlate), new IntCell(newRow), new IntCell(newCol) }; } @Nullable private Integer getCell(final DataRow row, final int index) { final DataCell cell = row.getCell(index); return cell.isMissing() ? null : Integer.valueOf(((IntValue) cell) .getIntValue()); } } // the logger instance private static final NodeLogger logger = NodeLogger .getLogger(PlateFormatNodeModel.class); /** Configuration key for the well count of input plates. */ static final String CFGKEY_FROM_WELL_COUNT = "from.well.count"; /** Default value for the well count of input plates. */ static final Format DEFAULT_FROM_WELL_COUNT = Format._96; /** Configuration key for the well count of output plates. */ static final String CFGKEY_TO_WELL_COUNT = "to.well.count"; /** Default value for the well count of output plates. */ static final Format DEFAULT_TO_WELL_COUNT = Format._384; /** Configuration key for the combination pattern. */ static final String CFGKEY_COMBINATION_PATTERN = "combination.pattern"; /** Default value for the combination pattern. */ static final CombinationPattern DEFAULT_COMBINATION_PATTERN = CombinationPattern.LeftToRightThenDown8PipettesClose; /** The possible {@link CombinationPattern} values. */ static final CombinationPattern[] POSSIBLE_COMBINATION_PATTERN_VALUES = new CombinationPattern[] { CombinationPattern.LeftToRightThenDown8PipettesClose, CombinationPattern.LeftToRightThenDown, CombinationPattern.UpToDownThenRight, CombinationPattern.UpToDownThenRight8Pipettes }; private final SettingsModelEnum<Format> fromWellCount = new SettingsModelEnum<Format>( CFGKEY_FROM_WELL_COUNT, DEFAULT_FROM_WELL_COUNT, Format.values()); private final SettingsModelEnum<Format> toWellCount = new SettingsModelEnum<Format>( CFGKEY_TO_WELL_COUNT, DEFAULT_TO_WELL_COUNT, Format.values()); private final SettingsModelEnumWithIcon<CombinationPattern> combinationPattern = new SettingsModelEnumWithIcon<CombinationPattern>( CFGKEY_COMBINATION_PATTERN, DEFAULT_COMBINATION_PATTERN, POSSIBLE_COMBINATION_PATTERN_VALUES); /** * Constructor for the node model. */ protected PlateFormatNodeModel() { super(1, 1); } /** * {@inheritDoc} */ @Override protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { final DataTableSpec spec = inData[0].getDataTableSpec(); final ColumnRearranger rearranger = new ColumnRearranger(spec); final int plateIndex = spec.findColumnIndex("Plate") == -1 ? spec .findColumnIndex("plate") : spec.findColumnIndex("Plate"); final DataColumnSpec plateSpec = spec.getColumnSpec(plateIndex); final int rowIndex = spec.findColumnIndex("row"); final DataColumnSpec rowSpec = spec.getColumnSpec(rowIndex); final int colIndex = spec.findColumnIndex("col"); final DataColumnSpec colSpec = spec.getColumnSpec(colIndex); rearranger.replace(new PlateFormatCellFactory(new DataColumnSpec[] { plateSpec, rowSpec, colSpec }, plateIndex, rowIndex, colIndex, fromWellCount.getEnumValue(), toWellCount.getEnumValue(), combinationPattern.getEnumValue()), plateIndex, rowIndex, colIndex); final BufferedDataTable ret = exec.createColumnRearrangeTable( inData[0], rearranger, exec); logger.debug("Table converted to " + toWellCount.getStringValue() + " well format."); return new BufferedDataTable[] { ret }; } /** * {@inheritDoc} */ @Override protected void reset() { // Nothing to do } /** * {@inheritDoc} */ @Override protected DataTableSpec[] configure(final DataTableSpec[] inSpecs) throws InvalidSettingsException { return new DataTableSpec[] { inSpecs[0] }; } /** * {@inheritDoc} */ @Override protected void saveSettingsTo(final NodeSettingsWO settings) { fromWellCount.saveSettingsTo(settings); toWellCount.saveSettingsTo(settings); combinationPattern.saveSettingsTo(settings); } /** * {@inheritDoc} */ @Override protected void loadValidatedSettingsFrom(final NodeSettingsRO settings) throws InvalidSettingsException { fromWellCount.loadSettingsFrom(settings); toWellCount.loadSettingsFrom(settings); combinationPattern.loadSettingsFrom(settings); } /** * {@inheritDoc} */ @Override protected void validateSettings(final NodeSettingsRO settings) throws InvalidSettingsException { fromWellCount.validateSettings(settings); toWellCount.validateSettings(settings); try { combinationPattern.validateSettings(settings); } catch (final InvalidSettingsException e) { if (settings instanceof NodeSettingsWO) { ((NodeSettingsWO) settings) .addString(CFGKEY_COMBINATION_PATTERN, CombinationPattern.LeftToRightThenDown .getDisplayText()); } logger.debug("Unable to load the combination pattern, using " + CombinationPattern.LeftToRightThenDown.getDisplayText(), e); } } /** {@inheritDoc} */ @Override protected void loadInternals(final File nodeInternDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { // No state } /** {@inheritDoc} */ @Override protected void saveInternals(final File nodeInternDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { // No state } }
33a79dd8b14db4bdc67236ae021c9bac36a51913
7a53089d9bb134cf9e42a03bc49bc4b283e86594
/app/src/test/java/be/ugent/zeus/hydra/library/LibraryTest.java
cf7cd50b0c42216485357ca61bfed2f6e6df9b23
[]
no_license
engmms/hydra-android
80fa6ac43bc94765a2ea6ef7dd1879e02a1a3f71
9d1fc46ac1d9fbe0bc4d5dddd116220e8e92edee
refs/heads/master
2020-12-04T15:42:37.593931
2019-09-21T17:32:45
2019-09-21T17:32:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
919
java
package be.ugent.zeus.hydra.library; import be.ugent.zeus.hydra.common.ModelTest; import nl.jqno.equalsverifier.Warning; import org.junit.Test; import static be.ugent.zeus.hydra.testing.Utils.defaultVerifier; import static be.ugent.zeus.hydra.testing.Utils.generate; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Niko Strijbol */ public class LibraryTest extends ModelTest<Library> { public LibraryTest() { super(Library.class); } @Test public void hasTelephone() { Library empty = new Library(); assertFalse(empty.hasTelephone()); Library full = generate(Library.class); assertTrue(full.hasTelephone()); } @Test @Override public void equalsAndHash() { defaultVerifier(Library.class) .withOnlyTheseFields("code", "favourite") .verify(); } }
838d53473310a93ab9df84139e899eff3656e718
1d5d53495bbffca12c150852389b341dfdff9935
/app/src/main/java/com/app/androidutildemo/mvp/view/CmsListView.java
6197acad142a9cfaf2403ea79a4e2a6037d40943
[]
no_license
HannahNick/HannahCore
78002c46b714744bd9435dd567c3461e6f0c8df7
97656062e90569b44fdab5b9afd206b424756408
refs/heads/master
2020-06-25T16:09:49.363235
2019-11-15T09:44:21
2019-11-15T09:44:21
199,361,595
0
0
null
null
null
null
UTF-8
Java
false
false
244
java
package com.app.androidutildemo.mvp.view; import com.app.androidutildemo.bean.TmsWrapperBean; import java.util.List; /** * Created by Nick on 2019-05-08. */ public interface CmsListView { void getHomeData(List<TmsWrapperBean> data); }
3be95ae574cf98ef4cb05ec2fb95564576750caa
1fdbf2035f497992d1066120fc1c5eb3eecc45f5
/core/index/src/main/java/org/locationtech/geowave/core/index/simple/SimpleDoubleIndexStrategy.java
cf06a12b8b057a9c3ebda5c2a1e65043d4a88398
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
ChesleyTan/geowave
0381abd2da300f20566adec8c104994399f27fc7
a5b20e40e5bb24a3f2533db69fcd29768a928402
refs/heads/kudu-master
2020-04-21T20:11:53.046160
2019-05-06T15:27:47
2019-05-06T15:37:36
169,835,181
1
0
Apache-2.0
2019-05-06T15:27:48
2019-02-09T05:26:07
Java
UTF-8
Java
false
false
429
java
package org.locationtech.geowave.core.index.simple; import org.locationtech.geowave.core.index.lexicoder.Lexicoders; public class SimpleDoubleIndexStrategy extends SimpleNumericIndexStrategy<Double> { public SimpleDoubleIndexStrategy() { super(Lexicoders.DOUBLE); } @Override protected Double cast(final double value) { return value; } @Override protected boolean isInteger() { return false; } }
b9248122194dde13b543b000c803b69ec6423861
7ba074aaff5db3aa507df21ac8f421e41838ff24
/mfw/mfw/src/com/mfw/util/FileUtil.java
c9e6db770d8a439ea074f2c7ea0f4abd02ca99bd
[]
no_license
eideo/framework
72ae19c53cded98bdeeb31b6460087ba3d3bad63
36b83a0a953c97025277eb434b972ad910ba30c1
refs/heads/master
2020-12-30T15:43:18.681234
2015-11-20T18:25:04
2015-11-20T18:25:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,047
java
package com.mfw.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; public class FileUtil { public static void main(String[] args) { String dirName = "d:/mfw/topic/";// 创建目录 FileUtil.createDir(dirName); } /** * 创建目录 * * @param destDirName 目标目录名 * @return 目录创建成功返回true,否则返回false */ public static boolean createDir(String destDirName) { File dir = new File(destDirName); if (dir.exists()) { return false; } if (!destDirName.endsWith(File.separator)) { destDirName = destDirName + File.separator; } // 创建单个目录 if (dir.mkdirs()) { return true; } else { return false; } } /** * 删除文件 * * @param filePathAndName String 文件路径及名称 如c:/fqf.txt * @param fileContent String * @return boolean */ public static void delFile(String filePathAndName) { try { String filePath = filePathAndName; filePath = filePath.toString(); java.io.File myDelFile = new java.io.File(filePath); myDelFile.delete(); } catch (Exception e) { System.out.println("删除文件操作出错"); e.printStackTrace(); } } /** * 读取到字节数组0 * * @param filePath //路径 * @throws IOException */ public static byte[] getContent(String filePath) throws IOException { File file = new File(filePath); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { System.out.println("file too big..."); return null; } FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // 确保所有数据均被读取 if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fi.close(); return buffer; } /** * 读取到字节数组1 * * @param filePath * @return * @throws IOException */ public static byte[] toByteArray(String filePath) throws IOException { File f = new File(filePath); if (!f.exists()) { throw new FileNotFoundException(filePath); } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } bos.close(); } } /** * 读取到字节数组2 * * @param filePath * @return * @throws IOException */ public static byte[] toByteArray2(String filePath) throws IOException { File f = new File(filePath); if (!f.exists()) { throw new FileNotFoundException(filePath); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { // do nothing // System.out.println("reading"); } return byteBuffer.array(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能 * * @param filename * @return * @throws IOException */ public static byte[] toByteArray3(String filePath) throws IOException { FileChannel fc = null; RandomAccessFile rf = null; try { rf = new RandomAccessFile(filePath, "r"); fc = rf.getChannel(); MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load(); //System.out.println(byteBuffer.isLoaded()); byte[] result = new byte[(int) fc.size()]; if (byteBuffer.remaining() > 0) { // System.out.println("remain"); byteBuffer.get(result, 0, byteBuffer.remaining()); } return result; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { rf.close(); fc.close(); } catch (IOException e) { e.printStackTrace(); } } } }
ee95223fb5781b514a4c58a4aa999bd5fa530199
6201d4ab2febf3532cd146f6e311cc764630464e
/src/test/java/pages/HomePage.java
3bb79e1c1076fbbb5a423aaa9786a2d129d4c99e
[]
no_license
JakubZelazkiewicz/homework-programa
15d73d30b45d7507572de3690986597f0cf4f8f8
cc5ba82b4fc7ac556107567620e2fe426becbbb2
refs/heads/master
2020-03-28T07:55:36.421944
2018-09-10T16:30:49
2018-09-10T16:30:49
147,933,874
0
0
null
null
null
null
UTF-8
Java
false
false
651
java
package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class HomePage { @FindBy(partialLinkText = "Logowanie") private WebElement signInButton; @FindBy(xpath = "//*[@id=\"navbar-top-collapse\"]/ul[2]/li[2]/a") private WebElement signUpButton; @FindBy(xpath = "//*[@id=\"navbar-top-collapse\"]/ul[1]/li[2]") public WebElement usersButton; public void clickOnSignInButton() { signInButton.click (); } public void clickOnSignUpButton() { signUpButton.click (); } public void clickOnUsersButton() { usersButton.click (); } }
ce3f7efe0522e2c766aba10f596d418ac4c892fd
0e30f1998d8e06d5ca177ad53ad1b7efb0ed0cad
/jBPM6Example_persistence_basic_BPMS6/src/test/java/com/sample/ProcessJPATest.java
8c67322a2a802105faffd4a81de7391d213f4e9f
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
cjk007/jbpm6example
ba999f2ca22b975370923b3caed57c4f4634eacc
8679948c6cafd199eb3a92f55c38fe12c9a09d82
refs/heads/master
2021-01-16T18:23:12.027586
2014-10-22T03:25:13
2014-10-22T03:25:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,782
java
package com.sample; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import junit.framework.TestCase; import org.jbpm.process.audit.JPAAuditLogService; import org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder; import org.jbpm.services.task.identity.JBossUserGroupCallbackImpl; import org.jbpm.test.JBPMHelper; import org.junit.Test; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeEnvironment; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.manager.RuntimeManagerFactory; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.TaskService; import org.kie.api.task.UserGroupCallback; import org.kie.api.task.model.TaskSummary; import org.kie.internal.io.ResourceFactory; import org.kie.internal.runtime.manager.context.EmptyContext; import bitronix.tm.BitronixTransactionManager; import bitronix.tm.TransactionManagerServices; import bitronix.tm.resource.jdbc.PoolingDataSource; /** * This is a sample file to launch a process. */ public class ProcessJPATest extends TestCase { private static EntityManagerFactory emf; @Test public void testProcess() throws Exception { try { setup(); RuntimeManager manager = getRuntimeManager("sample.bpmn"); RuntimeEngine runtime = manager.getRuntimeEngine(EmptyContext.get()); KieSession ksession = runtime.getKieSession(); // JPAAuditLogService logService = new // JPAAuditLogService(ksession.getEnvironment()); // logService.clear(); BitronixTransactionManager transactionManager = TransactionManagerServices.getTransactionManager(); transactionManager.setTransactionTimeout(3600); // longer timeout // for a debugger // start a new process instance Map<String, Object> params = new HashMap<String, Object>(); ProcessInstance pi = ksession.startProcess("com.sample.bpmn.hello", params); System.out.println("A process instance started : pid = " + pi.getId()); TaskService taskService = runtime.getTaskService(); // ------------ { List<TaskSummary> list = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK"); for (TaskSummary taskSummary : list) { System.out.println("john starts a task : taskId = " + taskSummary.getId()); taskService.start(taskSummary.getId(), "john"); taskService.complete(taskSummary.getId(), "john", null); } } // ----------- { List<TaskSummary> list = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK"); for (TaskSummary taskSummary : list) { System.out.println("mary starts a task : taskId = " + taskSummary.getId()); taskService.start(taskSummary.getId(), "mary"); taskService.complete(taskSummary.getId(), "mary", null); } } // ----------- manager.disposeRuntimeEngine(runtime); } catch (Throwable th) { th.printStackTrace(); } System.exit(0); } private static void setup() { // for H2 datasource JBPMHelper.startH2Server(); JBPMHelper.setupDataSource(); // for external database datasource // setupDataSource(); Map configOverrides = new HashMap(); configOverrides.put("hibernate.hbm2ddl.auto", "create"); // Uncomment if you don't want to clean up tables configOverrides.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); // Edit for other databases // configOverrides.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect"); emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa", configOverrides); } private static RuntimeManager getRuntimeManager(String process) { Properties properties = new Properties(); properties.setProperty("krisv", ""); properties.setProperty("mary", ""); properties.setProperty("john", ""); UserGroupCallback userGroupCallback = new JBossUserGroupCallbackImpl(properties); RuntimeEnvironment environment = RuntimeEnvironmentBuilder.getDefault() .persistence(true) .entityManagerFactory(emf) .userGroupCallback(userGroupCallback) .addAsset(ResourceFactory.newClassPathResource(process), ResourceType.BPMN2) .get(); return RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment); } public static PoolingDataSource setupDataSource() { // Please edit here when you want to use your database PoolingDataSource pds = new PoolingDataSource(); pds.setUniqueName("jdbc/jbpm-ds"); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties().put("user", "mysql"); pds.getDriverProperties().put("password", "mysql"); pds.getDriverProperties().put("url", "jdbc:mysql://localhost:3306/testbpms602"); pds.getDriverProperties().put("driverClassName", "com.mysql.jdbc.Driver"); pds.init(); return pds; } }
ed679e5fd71f3b52a44af38741d523574a89c752
e273a7ef199bcee09931091de5520de8ffda07fb
/javaOO/AddressBookv2/src/test/java/com/sg/addressbookv2/dao/listAllTest.java
0261e657b4a18dbaa3490753f6e2a7b1f2c5d2b6
[]
no_license
caseyPav/assorted-projects
ea0da89a0bb5f9ae3190eb1fbf455909d9f3ad7a
037cfc62492f5b7ef32a7e19729f75fb8978a2d7
refs/heads/master
2021-04-15T05:06:17.429468
2016-07-26T15:18:06
2016-07-26T15:18:06
63,108,060
0
0
null
null
null
null
UTF-8
Java
false
false
853
java
/* * 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.sg.addressbookv2.dao; import com.sg.addressbookv2.dao.AddressBookIMPL; import com.sg.addressbookv2.dao.AddressBookUtils; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; /** * * @author apprentice */ public class listAllTest { int expected, actual; public listAllTest() { } @Test public void saveAddressesToFileTest1() { expected = 300; //if test returns fails make sure this number matches the number of lines in addresses.txt!!!!!!!! AddressBookIMPL u = new AddressBookIMPL(); actual = u.listAll().size(); Assert.assertEquals(expected, actual); } }
67de09dc6e0305abf965c2fb56e776f66ef0bd7a
72954937b1f2be8a0ec23c5d87f43df49d9beb20
/src/main/java/com/zsmart/tva/service/facade/TauxTvaService.java
3feecbad69ee6fccde8ba6297aca5f70590ecc8e
[]
no_license
ZOUANI/compta_transparency_tva
e0123d96aea9ed9d40a61c2a4f9f51bcb20f313a
f5bcbd37dfc00dd0d1880c7715f1d0ab3ff9ac6e
refs/heads/master
2021-03-27T03:20:38.198230
2020-03-19T00:18:10
2020-03-19T09:14:42
247,781,041
0
0
null
null
null
null
UTF-8
Java
false
false
862
java
package com.zsmart.tva.service.facade; import java.util.ArrayList; import java.util.List; import java.util.Date; import java.math.BigDecimal; import com.zsmart.tva.bean.TauxTva; public interface TauxTvaService { public TauxTva save(TauxTva tauxtva); public List<TauxTva> findAll(); public TauxTva findById(Long id); public int delete(TauxTva tauxtva); public void deleteById(Long id); public void clone(TauxTva tauxtva,TauxTva tauxtvaClone); public TauxTva clone(TauxTva tauxtva); public List<TauxTva> clone(List<TauxTva>tauxtvas); public List<TauxTva> findByCriteria(Long idMin,Long idMax,BigDecimal percentageMin,BigDecimal percentageMax,BigDecimal majorationMin,BigDecimal majorationMax,BigDecimal penaliteMin,BigDecimal penaliteMax,Date dateApplicationDebutMin,Date dateApplicationDebutMax,Date dateApplicationFinMin,Date dateApplicationFinMax); }
[ "MoulaYounes@DESKTOP-GBNILO9" ]
MoulaYounes@DESKTOP-GBNILO9
2ad8476ea85fb2ca7bcc26d77790175b3dfc3726
3bd2b934a4fa0f4a137ef667187c2f3da84f5021
/Super_Duper_App/app/src/androidTest/java/com/example/super_duper_app/ExampleInstrumentedTest.java
14463b1d715b70a3c492c6cdd538f4d85bd0b3d7
[]
no_license
martin-cervantes/Android
82e9069e1be48cffbc39009c480f01104bb7f290
e78558760778cf32a5cfe944daba312ee7bfc1f2
refs/heads/master
2023-03-03T23:12:12.392914
2023-02-28T23:49:30
2023-02-28T23:49:30
85,215,244
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package com.example.super_duper_app; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.super_duper_app", appContext.getPackageName()); } }
f1bdb0cbb5e3278f9a5e7c52c1bf4f58a4285a45
336d652e88f9477dd6f0b76ba40d4264bca05d06
/Celest2Horizon-1.0.0/src/com/c2h/C2H.java
94b2cae2854fa57c53654e68f1364255a294d322
[]
no_license
Giacomo88/celest2horizon
61d671e158f4b9f1693c595b1b40ef086aaf1a04
d02d8809b071e8727df48762859eb92da1bfc891
refs/heads/master
2021-01-10T16:43:20.332658
2012-01-24T19:20:55
2012-01-24T19:20:55
45,044,182
0
0
null
null
null
null
UTF-8
Java
false
false
19,817
java
/* Celest2Horizon - Converts RA / Dec to Altitude / Azimuth on Droid Phones Copyright (C) 2010 F. A. Willis This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.c2h; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Spinner; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.os.CountDownTimer; import java.io.FileNotFoundException; import java.util.*; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.AdapterView; import android.content.Intent; import java.util.Calendar; /* http://code.google.com/p/android-file-dialog/ */ import com.lamerman.FileDialog; public class C2H extends Activity implements OnClickListener { private static final int REQUEST_SAVE = 0; private static final int REQUEST_LOAD = 0; EditText textAltitude; EditText textAzimuth; EditText textScopeAltitude; EditText textScopeAzimuth; EditText textRA; EditText textDEC; Button ButtonSync; Button ButtonMakeHighest; Button ButtonInfoView; SyncClicked mySyncClicker; Spinner spinner; Spinner spinner_group; int objectSet; TextView objectName; MyLocationListener thisLocation; DobOrientation thisDob; MyCount counter; Stats myStats; protected int mPos; protected String mSelection; Messier myMessiers; Stars myStars; Planets myPlanets; UserObjects myObjects; NearestObjs myHighestObjs; //Calendar mst = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //MyDataStruct myPlanets[]; ArrayAdapter<String> adapterMessier; ArrayAdapter<String> adapterStars; ArrayAdapter<String> adapterPlanets; ArrayAdapter<String> adapterUserObjects; ArrayAdapter<String> adapterHighestObjects; ArrayAdapter<String> adapterGroups; int globalPos = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Globals.myContext = this; myStats = new Stats(); thisLocation = new MyLocationListener(this); thisDob = new DobOrientation(this); //textSiderealTime = (EditText) findViewById(R.id.EditTextTimeSidereal); textAltitude = (EditText) findViewById(R.id.EditTextAlt); textAzimuth = (EditText) findViewById(R.id.EditTextAz); textScopeAltitude = (EditText) findViewById(R.id.EditTextScopeAlt); textScopeAzimuth = (EditText) findViewById(R.id.EditTextScopeAz); textRA = (EditText) findViewById(R.id.EditTextRA); textDEC = (EditText) findViewById(R.id.EditTextDEC); ButtonSync = (Button)findViewById(R.id.buttonSync); mySyncClicker = new SyncClicked(); ButtonSync.setOnClickListener(mySyncClicker); ButtonMakeHighest = (Button)findViewById(R.id.buttonSortHighest); ButtonMakeHighest.setOnClickListener(this); ButtonInfoView = (Button)findViewById(R.id.buttonInfo); ButtonInfoView.setOnClickListener(this); objectName = (TextView)findViewById(R.id.TextView09); counter = new MyCount(15000, 1000); counter.start(); spinner_group= (Spinner) findViewById(R.id.Spinner02); String myGroups[] = new String[5]; myGroups[0] = "Messier"; myGroups[1] = "Planets"; myGroups[2] = "Stars"; myGroups[3] = "User"; myGroups[4] = "Highest"; // adapterGroups = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myGroups); adapterGroups = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, myGroups); adapterGroups.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_group.setAdapter(adapterGroups); OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(this,this.adapterGroups); spinner_group.setOnItemSelectedListener(spinnerListener); spinner = (Spinner) findViewById(R.id.Spinner01); myMessiers = new Messier(); myPlanets = new Planets(); myStars = new Stars(); myHighestObjs = new NearestObjs(); myHighestObjs.SortHighest(); try { myObjects = new UserObjects(); } catch (FileNotFoundException e1) { Log.d("Debug", "File not found"); e1.printStackTrace(); } String[] someStrings;//= new String[110]; someStrings = myMessiers.GetStrings(); adapterMessier = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someStrings); adapterMessier.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterMessier); spinnerListener = new myOnItemSelectedListener(this, this.adapterMessier); spinner.setOnItemSelectedListener(spinnerListener); String[] somePlanets = myPlanets.GetStrings(); adapterPlanets = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, somePlanets); String[] someStars = myStars.GetStrings(); adapterStars = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someStars); String[] someHighestObjs = myHighestObjs.GetStrings(); adapterHighestObjects = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someHighestObjs); Log.d("Debug", "Getting obj strings"); String[] someObjs; if( myObjects != null ) { someObjs = myObjects.GetStrings(); } else { someObjs = new String[1]; someObjs[0] = ("No user objects defined"); } Log.d("Debug", "Got obj strings"); if( someObjs != null ) adapterUserObjects = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someObjs); Log.d("Debug", "On create finished"); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt("objectSet", objectSet); outState.putInt("globalPos", globalPos); super.onSaveInstanceState(outState); Log.d("Debug", "On save instance -> "+globalPos); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { objectSet = savedInstanceState.getInt("objectSet"); globalPos = savedInstanceState.getInt("globalPos"); spinner.setSelection(globalPos); super.onRestoreInstanceState(savedInstanceState); Log.d("Debug", "On restore instance -> "+globalPos); } @Override protected void onResume() { super.onResume(); Log.d("Debug", "C2H - On resume"); counter.bRunning = true; thisDob.onResume(); Globals.OnResume(); } @Override protected void onPause() { super.onPause(); Log.d("Debug", "C2H - On pause"); counter.bRunning = false; thisDob.onPause(); Globals.OnPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } // This method is called once the menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) { String str = String.format("Menu %d", item.getItemId()); Log.d("Debug", str); switch (item.getItemId()) { case R.id.About: AboutDialog myAboutBox = new AboutDialog(this); myAboutBox.show(); break; case R.id.settings: /*Log.d("Debug", "Settings dialog - creating"); SettingsDialog mySettingsBox = new SettingsDialog(this); Log.d("Debug", "Settings dialog completed"); mySettingsBox.Init(); mySettingsBox.show();*/ Log.d("Debug", "Settings shown"); Intent settingsActivity = new Intent(getBaseContext(), Preferences.class); startActivity(settingsActivity); Log.d("Debug", "Pref activity started"); break; case R.id.user: Intent fileIntent = new Intent(C2H.this, FileDialog.class); fileIntent.putExtra(FileDialog.START_PATH, "/sdcard"); startActivityForResult(fileIntent, REQUEST_SAVE); break; } return true; } @Override public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_SAVE) { Log.d("FD", "Saving..."); } else if (requestCode == REQUEST_LOAD) { Log.d("FD", "Loading..."); } String filePath = data.getStringExtra(FileDialog.RESULT_PATH); Log.d("FD", "File "+filePath); Globals.strUserPath = filePath; } else if (resultCode == Activity.RESULT_CANCELED) { Log.d("FD", "Request cancelled"); //Logger.getLogger(AccelerationChartRun.class.getName()).log( // Level.WARNING, "file not selected"); } } public class MyCount extends CountDownTimer { Boolean bRunning; public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); bRunning = true; } @Override public void onFinish() { if( bRunning ) { Log.d("Debug", "restarting clock"); start(); } } @Override public void onTick(long millisUntilFinished) { Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); int nHour = now.get(Calendar.HOUR_OF_DAY); int nMinutes = now.get(Calendar.MINUTE); String txt = String.format("%d - %d", nHour, nMinutes); String strRA = textRA.getText().toString(); String strDEC = textDEC.getText().toString(); Globals.coord_to_horizon((Calendar)now.clone(), strRA, strDEC, Globals.dLatitude, Globals.dLongitude); txt = String.format("%.2f", Globals.hrz_altitude); textAltitude.setText(txt); txt = String.format("%.2f", Globals.hrz_azimuth); textAzimuth.setText(txt); Globals.dTargetHeading = Globals.hrz_azimuth; Globals.dTargetPitch = Globals.hrz_altitude; txt = String.format("%.2f", Globals.dDobPitch - Globals.dDobPitchDelta); textScopeAltitude.setText(txt); txt = String.format("%.2f", Globals.dDobHeading - Globals.dDobHeadingDelta); textScopeAzimuth.setText(txt); } }; public class myOnItemSelectedListener implements OnItemSelectedListener { /* * provide local instances of the mLocalAdapter and the mLocalContext */ ArrayAdapter<String> mLocalAdapter; Activity mLocalContext; /** * Constructor * @param c - The activity that displays the Spinner. * @param ad - The Adapter view that * controls the Spinner. * Instantiate a new listener object. */ public myOnItemSelectedListener(Activity c, ArrayAdapter<String> ad) { this.mLocalContext = c; this.mLocalAdapter = ad; } /** * When the user selects an item in the spinner, this method is invoked by the callback * chain. Android calls the item selected listener for the spinner, which invokes the * onItemSelected method. * * @see android.widget.AdapterView.OnItemSelectedListener#onItemSelected( * android.widget.AdapterView, android.view.View, int, long) * @param parent - the AdapterView for this listener * @param v - the View for this listener * @param pos - the 0-based position of the selection in the mLocalAdapter * @param row - the 0-based row number of the selection in the View */ public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) { String str; if( parent==spinner ){ str = String.format("Parent = (spinner), Objectset (%d), pos (%d), row *%d)", objectSet, pos, row); Log.d("Debug", str); globalPos = pos; if( objectSet==0 ){ textRA.setText(myMessiers.GetRA(pos)); textDEC.setText(myMessiers.GetDEC(pos)); objectName.setText(myMessiers.GetName(pos)); } if( objectSet==1 ){ Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); myPlanets.UpdateRADEC((Calendar)now.clone(), pos); textRA.setText(myPlanets.GetRA(pos)); textDEC.setText(myPlanets.GetDEC(pos)); objectName.setText(myPlanets.GetName(pos)); } if( objectSet==2 ){ textRA.setText(myStars.GetRA(pos)); textDEC.setText(myStars.GetDEC(pos)); objectName.setText(myStars.GetName(pos)); } if( objectSet==3 ){ if( myObjects == null ) { textRA.setText("0h0"); textDEC.setText("0"); objectName.setText("None"); } else { textRA.setText(myObjects.GetRA(pos)); textDEC.setText(myObjects.GetDEC(pos)); objectName.setText(myObjects.GetName(pos)); } } if( objectSet==4 ){ textRA.setText(myHighestObjs.GetRA(pos)); textDEC.setText(myHighestObjs.GetDEC(pos)); objectName.setText(myHighestObjs.GetName(pos)); } } if( parent==spinner_group ){ str = String.format("Parent = (spinner_group), Objectset (%d), pos (%d), row *%d)", objectSet, pos, row); Log.d("Debug", str); if( pos == 0 ){ adapterMessier.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterMessier); objectSet = 0; } if( pos == 1 ){ adapterPlanets.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterPlanets); objectSet = 1; } if( pos == 2 ){ adapterStars.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterStars); objectSet = 2; } if( pos == 3 ){ adapterUserObjects.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterUserObjects); objectSet = 3; } if( pos == 4 ){ adapterHighestObjects.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterHighestObjects); objectSet = 4; } spinner.setSelection(globalPos, true); } } /** * The definition of OnItemSelectedListener requires an override * of onNothingSelected(), even though this implementation does not use it. * @param parent - The View for this Listener */ public void onNothingSelected(AdapterView<?> parent) { // do nothing } } @Override public void onClick(View v) { switch(v.getId()) { case R.id.buttonSortHighest: myHighestObjs = new NearestObjs(); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //"C1","0h0.0","0 0","---","0" for(int i=0; i<110; i++) { //String strLabel = "Sort"+Integer.toString(i); //String strAz = "0h"+Integer.toString(i); //MyDataStruct ds = new MyDataStruct(strLabel, strAz, "0 0", "+++", "1"); Globals.coord_to_horizon((Calendar)now.clone(), myMessiers.myMessier[i].RA, myMessiers.myMessier[i].DEC, Globals.dLatitude, Globals.dLongitude); myMessiers.myMessier[i].dAltitude = Globals.hrz_altitude; myMessiers.myMessier[i].dAzimuth = Globals.hrz_azimuth; myHighestObjs.Add(myMessiers.myMessier[i]); } myHighestObjs.SortHighest(); String[] someHighestObjs = myHighestObjs.GetStrings(); adapterHighestObjects = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, someHighestObjs); adapterHighestObjects.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapterHighestObjects); objectSet = 4; break; case R.id.buttonInfo: Log.d("Debug", "Showing info dialog"); InfoDialog myInfoBox = new InfoDialog(this); myInfoBox.show(); break; } } }
[ "crappiemeister@12253d9f-7557-08cb-0b6a-951e442744b5" ]
crappiemeister@12253d9f-7557-08cb-0b6a-951e442744b5
42d23e8ba8489948c7b707303ca0002308cb688b
ea4336e7d729c1781d0e7c6679a272d1c2558797
/Advanced/Advanced Spring Version/ProjectOne/src/phone/Galaxy.java
fa93ce6e5d6a5a0e88a7d1c15060c1e9126f0282
[]
no_license
Manzurka/Java
7045fbc633337318fb607536fe342abcfcb5efd2
c464bde0097e583e7b4dde822caa6cbdd589139e
refs/heads/master
2020-03-12T17:01:12.715268
2018-06-20T21:48:56
2018-06-20T21:48:56
130,728,003
0
0
null
null
null
null
UTF-8
Java
false
false
704
java
package phone; public class Galaxy extends Phone implements Ringable { public Galaxy(String versionNumber, int batteryPercentage, String carrier, String ringTone) { super(versionNumber, batteryPercentage, carrier, ringTone); } @Override public String ring() { String ring = this.getRingTone(); return "Galaxy" + this.getVersionNumber() + "says " + ring; } @Override public String unlock() { return "Unlocked via finger print"; } @Override public void displayInfo() { System.out.println("Galaxy info: version: " + this.getVersionNumber()+ ",battery: " + this.getBatteryPercentage() + " carrier: " + this.getCarrier()); } }
2af88447e1ff84a097baf5c674b061b20dda67ea
4f8dfcdd6f1494b59684438b8592c6c5c2e63829
/DiffTGen-result/output/patch4-Math-82-Jaid-plausible/Math_82_4-plausible_jaid/target/0/25/evosuite-tests/org/apache/commons/math/optimization/linear/SimplexSolver_ESTest_scaffolding.java
e55154843388c718c337cfb3de988b6deb26599a
[]
no_license
IntHelloWorld/Ddifferent-study
fa76c35ff48bf7a240dbe7a8b55dc5a3d2594a3b
9782867d9480e5d68adef635b0141d66ceb81a7e
refs/heads/master
2021-04-17T11:40:12.749992
2020-03-31T23:58:19
2020-03-31T23:58:19
249,439,516
0
0
null
null
null
null
UTF-8
Java
false
false
10,202
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Mon Mar 30 02:00:07 GMT 2020 */ package org.apache.commons.math.optimization.linear; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class SimplexSolver_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "org.apache.commons.math.optimization.linear.SimplexSolver"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("file.encoding", "UTF-8"); java.lang.System.setProperty("java.awt.headless", "true"); java.lang.System.setProperty("java.io.tmpdir", "/tmp"); java.lang.System.setProperty("user.country", "US"); java.lang.System.setProperty("user.dir", "/home/hewitt/work/DiffTGen-master/output/patch4-Math-82-Jaid-plausible/Math_82_4-plausible_jaid/target/0/25"); java.lang.System.setProperty("user.home", "/home/hewitt"); java.lang.System.setProperty("user.language", "en"); java.lang.System.setProperty("user.name", "hewitt"); java.lang.System.setProperty("user.timezone", "Asia/Chongqing"); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(SimplexSolver_ESTest_scaffolding.class.getClassLoader() , "org.apache.commons.math.linear.BlockFieldMatrix", "org.apache.commons.math.optimization.linear.UnboundedSolutionException", "org.apache.commons.math.MathException", "org.apache.commons.math.util.MathUtils", "org.apache.commons.math.util.OpenIntToDoubleHashMap$1", "org.apache.commons.math.ConvergenceException", "org.apache.commons.math.optimization.linear.Relationship", "org.apache.commons.math.linear.AbstractRealMatrix$5", "org.apache.commons.math.linear.MatrixUtils", "org.apache.commons.math.Field", "org.apache.commons.math.util.OpenIntToDoubleHashMap", "org.apache.commons.math.linear.FieldMatrixChangingVisitor", "org.apache.commons.math.linear.RealMatrix", "org.apache.commons.math.linear.DefaultRealMatrixChangingVisitor", "org.apache.commons.math.util.OpenIntToDoubleHashMap$Iterator", "org.apache.commons.math.optimization.linear.LinearObjectiveFunction", "org.apache.commons.math.util.CompositeFormat", "org.apache.commons.math.linear.AbstractFieldMatrix", "org.apache.commons.math.optimization.linear.LinearConstraint", "org.apache.commons.math.linear.SparseRealVector", "org.apache.commons.math.MathRuntimeException", "org.apache.commons.math.linear.ArrayRealVector", "org.apache.commons.math.MathRuntimeException$1", "org.apache.commons.math.MathRuntimeException$2", "org.apache.commons.math.MathRuntimeException$3", "org.apache.commons.math.MathRuntimeException$4", "org.apache.commons.math.MathRuntimeException$5", "org.apache.commons.math.MathRuntimeException$6", "org.apache.commons.math.MathRuntimeException$7", "org.apache.commons.math.MathRuntimeException$8", "org.apache.commons.math.MathRuntimeException$10", "org.apache.commons.math.MathRuntimeException$9", "org.apache.commons.math.linear.RealMatrixImpl", "org.apache.commons.math.optimization.OptimizationException", "org.apache.commons.math.linear.DecompositionSolver", "org.apache.commons.math.linear.RealVectorFormat", "org.apache.commons.math.linear.AnyMatrix", "org.apache.commons.math.optimization.linear.NoFeasibleSolutionException", "org.apache.commons.math.FieldElement", "org.apache.commons.math.MaxIterationsExceededException", "org.apache.commons.math.linear.RealMatrixPreservingVisitor", "org.apache.commons.math.linear.Array2DRowRealMatrix", "org.apache.commons.math.optimization.linear.SimplexTableau", "org.apache.commons.math.linear.SparseRealMatrix", "org.apache.commons.math.linear.FieldMatrixPreservingVisitor", "org.apache.commons.math.linear.NonSquareMatrixException", "org.apache.commons.math.linear.MatrixVisitorException", "org.apache.commons.math.linear.MatrixIndexException", "org.apache.commons.math.linear.AbstractRealMatrix", "org.apache.commons.math.linear.DefaultRealMatrixPreservingVisitor", "org.apache.commons.math.optimization.RealPointValuePair", "org.apache.commons.math.linear.BigMatrix", "org.apache.commons.math.linear.FieldVector", "org.apache.commons.math.linear.Array2DRowFieldMatrix", "org.apache.commons.math.linear.OpenMapRealVector", "org.apache.commons.math.linear.BlockRealMatrix", "org.apache.commons.math.linear.InvalidMatrixException", "org.apache.commons.math.linear.RealVector", "org.apache.commons.math.linear.RealMatrixChangingVisitor", "org.apache.commons.math.linear.FieldMatrix", "org.apache.commons.math.optimization.linear.LinearOptimizer", "org.apache.commons.math.optimization.linear.AbstractLinearOptimizer", "org.apache.commons.math.linear.OpenMapRealMatrix", "org.apache.commons.math.optimization.GoalType", "org.apache.commons.math.optimization.linear.SimplexSolver" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(SimplexSolver_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "org.apache.commons.math.optimization.linear.AbstractLinearOptimizer", "org.apache.commons.math.optimization.linear.SimplexSolver", "org.apache.commons.math.optimization.linear.SimplexTableau", "org.apache.commons.math.util.CompositeFormat", "org.apache.commons.math.linear.RealVectorFormat", "org.apache.commons.math.linear.ArrayRealVector", "org.apache.commons.math.optimization.linear.LinearObjectiveFunction", "org.apache.commons.math.optimization.linear.LinearConstraint", "org.apache.commons.math.optimization.linear.Relationship", "org.apache.commons.math.linear.AbstractRealMatrix", "org.apache.commons.math.linear.Array2DRowRealMatrix", "org.apache.commons.math.linear.OpenMapRealVector", "org.apache.commons.math.util.OpenIntToDoubleHashMap", "org.apache.commons.math.util.OpenIntToDoubleHashMap$Iterator", "org.apache.commons.math.MathRuntimeException", "org.apache.commons.math.MathRuntimeException$7", "org.apache.commons.math.MathRuntimeException$4", "org.apache.commons.math.MathException", "org.apache.commons.math.ConvergenceException", "org.apache.commons.math.optimization.OptimizationException", "org.apache.commons.math.MaxIterationsExceededException", "org.apache.commons.math.linear.MatrixIndexException", "org.apache.commons.math.util.MathUtils", "org.apache.commons.math.optimization.linear.UnboundedSolutionException", "org.apache.commons.math.linear.MatrixUtils", "org.apache.commons.math.linear.OpenMapRealMatrix", "org.apache.commons.math.optimization.RealPointValuePair", "org.apache.commons.math.optimization.linear.NoFeasibleSolutionException", "org.apache.commons.math.linear.InvalidMatrixException", "org.apache.commons.math.linear.NonSquareMatrixException", "org.apache.commons.math.linear.BlockRealMatrix", "org.apache.commons.math.linear.DefaultRealMatrixPreservingVisitor", "org.apache.commons.math.linear.AbstractRealMatrix$5" ); } }
e6ed929f0513c5541a85370212508603cad7fdd7
f8041533e6432ca3616d07af98cb3c6592010f1b
/app/src/main/java/com/example/sqlitepractice/Models/User.java
386a886f269491e8e73320478ecc796750d2f31f
[]
no_license
xenonJr/EshopDataBaseProject
c3a0dee4c877fb384e71825aff88259cd6cf58ac
c6bcb58eeaf081017493dacd658cefff829743b0
refs/heads/master
2023-02-14T05:27:46.444672
2020-12-30T19:38:33
2020-12-30T19:38:33
323,367,703
0
0
null
null
null
null
UTF-8
Java
false
false
1,043
java
package com.example.sqlitepractice.Models; public class User { String name,username,address,mail,pass; public User(String name, String username, String address, String mail, String pass) { this.name = name; this.username = username; this.address = address; this.mail = mail; this.pass = pass; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
c9dc1e0834b62070caaa046738910fa505c46e85
e4a96621b6cb1dad2670ead9c26f8a5e87b0e2d0
/core/src/com/lindengames/line/screens/ScreenAdapter.java
5509338b3872337041e8422d074455e001ba4c46
[]
no_license
jaqbcygan/com.lindengames.line
0ffcb9d04e0a27241f67d3d18778856c630467d5
391e283d86aa55775aeb154e1c27ad048f5f5e37
refs/heads/master
2021-01-17T20:01:55.396794
2016-08-17T16:18:49
2016-08-17T16:18:49
64,148,566
0
0
null
null
null
null
UTF-8
Java
false
false
1,388
java
package com.lindengames.line.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.Timer; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; public abstract class ScreenAdapter implements Screen { OrthographicCamera camera; Viewport viewport; Stage stage; Timer timer; public ScreenAdapter(){ camera = new OrthographicCamera(); viewport = new ScreenViewport(camera); stage = new Stage(viewport); Gdx.input.setInputProcessor(stage); timer = new Timer(); } @Override public void show() { } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 1, 1, 0); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 45f)); stage.draw(); } @Override public void resize(int width, int height) { viewport.update(width, height, true); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
061678a611c36736b9ced36e8ce7f7611b245589
d8bf44e44213ae4197d0aa8f54f3e3c2c1f361cc
/박성철/210405/BJ_14567.java
259162597b6805adfed629b3ed1b2b65937648b6
[]
no_license
SSAFY05-SEOUL07-ALGO05/AlgorithmTest
3126c751f378c0dcc6fc24bf64771e528e67ed13
2edd4886535add41741bab7f864a5fb4f2a7bf46
refs/heads/main
2023-04-20T20:52:43.888351
2021-05-13T11:35:16
2021-05-13T11:35:16
352,645,834
0
1
null
2021-05-13T11:35:17
2021-03-29T13:04:13
Java
UTF-8
Java
false
false
1,712
java
package com.ssafy.day0405; import java.io.*; import java.util.*; // 백준 14567. 선수과목. // 위상 정렬. public class BJ_14567 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[] preNode = new int[N+1]; int[] result = new int[N+1]; List<Integer> resultRoute = new ArrayList<Integer>(); List<Integer>[] listArr = new ArrayList[N+1]; for(int i=1; i<=N; i++) { listArr[i] = new ArrayList<Integer>(); } for(int i=0; i<M; i++) { st = new StringTokenizer(br.readLine(), " "); int from = Integer.parseInt(st.nextToken()); int to = Integer.parseInt(st.nextToken()); listArr[from].add(to); preNode[to] += 1; } Deque<Integer> dq = new LinkedList<Integer>(); for(int i=1; i<=N; i++) { if(preNode[i] == 0) { dq.offer(i); } } int layer = 1; int count = 0; while(!dq.isEmpty()) { int size = dq.size(); for(int i=0; i<size; i++) { int node = dq.poll(); count++; resultRoute.add(node); result[node] = layer; for(int next : listArr[node]) { preNode[next] -= 1; if(preNode[next] == 0) { dq.offer(next); } } } layer++; } for(int i=1; i<=N; i++) { sb.append(result[i]).append(" "); } System.out.println(count); for(int i : resultRoute) { System.out.print(i + " "); } System.out.println(); System.out.println(sb.toString()); br.close(); } }
f72ec9286222ca040826e86b1ee6b5710d52f9a9
e15a01f82717956bc0e9d7abeff8519b70a62d98
/invenio/invenio-systems/services/src/main/java/com/invenio/service/admin/XtradersExchangeService.java
4ce4e45e1aea7ea14ec44c3baf35977e06d04a95
[]
no_license
ruchiapandeya/projects
89340fb548c7921e13856af138fb413177db2d97
b9668cb999902b4f2194bd7646a047d4155e6ed2
refs/heads/master
2021-01-20T21:26:13.689265
2014-05-15T07:54:01
2014-05-15T07:54:01
18,482,492
1
0
null
null
null
null
UTF-8
Java
false
false
288
java
package com.invenio.service.admin; import com.invenio.schema.beans.admin.XtradersExchange; import com.invenio.service.PersistenceService; public interface XtradersExchangeService extends PersistenceService<XtradersExchange, com.invenio.dao.entity.admin.XtradersExchange, Integer> { }
f3c692322f2560d255629e2e2dd8329807afff01
ecd2b1fdaff03c67ef4514fa30d9e07de7e09cf7
/src/Algorithm/minSubArrayLen.java
4bd0ad27a7da490957f3d4ba4926c2a971f28188
[]
no_license
MrSongzzZ/StructureAndAlgorithm
d760af20aa75b9c596f6d3bd9033cf1f69d2efef
2c1142afec58ffe2a5d637d8d87c20100488ace3
refs/heads/main
2023-08-05T15:44:02.267357
2021-09-16T05:41:20
2021-09-16T05:41:20
305,950,994
0
0
null
null
null
null
UTF-8
Java
false
false
1,969
java
package Algorithm; /** * 给定一个含有 n 个正整数的数组和一个正整数 target 。 * * 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。 * * * * 示例 1: * * 输入:target = 7, nums = [2,3,1,2,4,3] * 输出:2 * 解释:子数组 [4,3] 是该条件下的长度最小的子数组。 * 示例 2: * * 输入:target = 4, nums = [1,4,4] * 输出:1 * 示例 3: * * 输入:target = 11, nums = [1,1,1,1,1,1,1,1] * 输出:0 * * * 提示: * * 1 <= target <= 109 * 1 <= nums.length <= 105 * 1 <= nums[i] <= 105 */ public class minSubArrayLen { public static int minSubArrayLen(int target, int[] nums) { int result = 0; int left = 0; int right = 0; int sum = nums[right]; while (left <= right && right < nums.length) { if (left == right) { if (nums[left] >= target) { return 1; } else { right++; if (right < nums.length) { sum = sum + nums[right]; } } } else { if (sum >= target) { if (result == 0) { result = right - left + 1; } else { result = Math.min(result, right - left + 1); } sum = sum - nums[left]; left++; } else { right++; if (right < nums.length) { sum = sum + nums[right]; } } } } return result; } public static void main(String[] args) { System.out.println(minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3})); } }
9a1af07ad622aa166790b567372be88bde0cc867
40f90cae409f6b5a8f9b9c4b08d32718673ac9b2
/app/src/main/java/com/example/optimas/firebaseconsole/FoodList.java
c92a697c9a676b84690f4bda5176c1db895f671e
[]
no_license
kuldeep23/DamayaServices
00c21d90f9c5701559b29e695bc17f5af49d7df5
7ff6add78441f7b30ad37c0ee690e90ac9d63ec9
refs/heads/master
2020-12-11T04:36:28.108789
2020-02-12T07:05:31
2020-02-12T07:05:31
233,778,525
0
0
null
null
null
null
UTF-8
Java
false
false
18,331
java
package com.example.optimas.firebaseconsole; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.optimas.firebaseconsole.Common.Common; import com.example.optimas.firebaseconsole.Database.Database; import com.example.optimas.firebaseconsole.Interface.ItemClickListener; import com.example.optimas.firebaseconsole.Model.Category; import com.example.optimas.firebaseconsole.Model.Favorites; import com.example.optimas.firebaseconsole.Model.Food; import com.example.optimas.firebaseconsole.Model.Order; import com.example.optimas.firebaseconsole.ViewHolder.FoodViewHolder; import com.facebook.CallbackManager; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; import com.facebook.share.widget.ShareDialog; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.makeramen.roundedimageview.RoundedTransformationBuilder; import com.mancj.materialsearchbar.MaterialSearchBar; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import com.squareup.picasso.Transformation; import java.util.ArrayList; import java.util.List; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class FoodList extends AppCompatActivity { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; FirebaseDatabase database; DatabaseReference foodList; String categoryId = ""; FirebaseRecyclerAdapter<Food, FoodViewHolder> adapter; //Search Fuctionality FirebaseRecyclerAdapter<Food, FoodViewHolder> searchadapter; List<String> suggestList= new ArrayList<>(); MaterialSearchBar materialSearchbar; //Favroties Database localDB; //Facebook Share CallbackManager callbackManager; ShareDialog shareDialog; SwipeRefreshLayout swipeRefreshLayout; //Create target from Picaso Target target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { //Create photo from Bitmap SharePhoto photo = new SharePhoto.Builder() .setBitmap(bitmap) .build(); if(ShareDialog.canShow(SharePhotoContent.class)){ SharePhotoContent content = new SharePhotoContent.Builder() .addPhoto(photo) .build(); shareDialog.show(content); } } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //fonts CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/OpenSans-Regular.ttf") .setFontAttrId(R.attr.fontPath) .build()); setContentView(R.layout.activity_cart); setContentView(R.layout.activity_food_list); //Init Facebook callbackManager = CallbackManager.Factory.create(); shareDialog = new ShareDialog(this); database = FirebaseDatabase.getInstance(); foodList = database.getReference("Restaurants").child(Common.restaurantSelected) .child("details").child("Foods"); //Local DB localDB = new Database(this); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_layout); swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_dark, android.R.color.holo_orange_dark, android.R.color.holo_blue_dark); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (getIntent() != null) categoryId = getIntent().getStringExtra("CategoryId"); switch (categoryId) { case "05": Intent sendpackage=new Intent(FoodList.this,HouseHolds.class); sendpackage.putExtra("CategoryId",categoryId); startActivity(sendpackage); break; case "02": if (!categoryId.isEmpty() && categoryId != null) { if(Common.isConnectedToInternet(getBaseContext())) loadListFood(categoryId); else { Toast.makeText(FoodList.this, "Please check your connection !!", Toast.LENGTH_SHORT).show(); return; } /// loadFood(categoryId); } break; } } }); swipeRefreshLayout.post(new Runnable() { @Override public void run() { if (getIntent() != null) categoryId = getIntent().getStringExtra("CategoryId"); if (!categoryId.isEmpty() && categoryId != null) { if(Common.isConnectedToInternet(getBaseContext())) loadListFood(categoryId); else { Toast.makeText(FoodList.this, "Please check your connection !!", Toast.LENGTH_SHORT).show(); return; } /// loadFood(categoryId); } //Search materialSearchbar=(MaterialSearchBar)findViewById(R.id.searchBar); materialSearchbar.setHint("Enter your food"); //materialSearchbar.setSpeechMode(false); loadSuggest(); materialSearchbar.setCardViewElevation(10); materialSearchbar.addTextChangeListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // When user type text suggest List<String> suggest=new ArrayList<String>(); for(String search:suggestList){ if(search.toLowerCase().contains(materialSearchbar.getText().toLowerCase())) suggest.add(search); } materialSearchbar.setLastSuggestions(suggest); } @Override public void afterTextChanged(Editable s) { } }); materialSearchbar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() { @Override public void onSearchStateChanged(boolean enabled) { if(!enabled) recyclerView.setAdapter(adapter); } @Override public void onSearchConfirmed(CharSequence text) { startSearch(text); } @Override public void onButtonClicked(int buttonCode) { } }); } }); recyclerView = (RecyclerView) findViewById(R.id.recycle_food); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); } private void startSearch(CharSequence text) { Query searchByName = foodList.orderByChild("name").equalTo(text.toString()); FirebaseRecyclerOptions<Food> foodOptions = new FirebaseRecyclerOptions.Builder<Food>() .setQuery(searchByName,Food.class) .build(); searchadapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(foodOptions) { @Override protected void onBindViewHolder(@NonNull FoodViewHolder viewHolder, int position, @NonNull Food model) { viewHolder.food_name.setText(model.getName()); viewHolder.food_description.setText(model.getDescription()); viewHolder.food_price.setText(model.getPrice()); Transformation transformation = new RoundedTransformationBuilder() .borderColor(Color.BLACK) .borderWidthDp(3) .cornerRadiusDp(30) .oval(false) .build(); Picasso.with(getBaseContext()) .load(model.getImage()) .fit() .transform(transformation) .into(viewHolder.food_image); final Food local = model; viewHolder.setItemClickListener(new ItemClickListener() { @Override public void onClick(View view, int position, boolean isLongClick) { // Toast.makeText(Home.this,""+clickItem.getName(),Toast.LENGTH_SHORT).show(); //Get CategoryID Intent foodDetail = new Intent(FoodList.this, FoodDetail.class); foodDetail.putExtra("foodId", searchadapter.getRef(position).getKey()); startActivity(foodDetail); } }); } @NonNull @Override public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.food_item1,parent,false); return new FoodViewHolder(itemView); } }; searchadapter.startListening(); recyclerView.setAdapter(searchadapter); } private void loadSuggest() { foodList.orderByChild("menuId").equalTo(categoryId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot:dataSnapshot.getChildren()){ Food item= postSnapshot.getValue(Food.class); suggestList.add(item.getName()); } materialSearchbar.setLastSuggestions(suggestList); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void loadListFood(String categoryId) { Query searchByName = foodList.orderByChild("menuId").equalTo(categoryId); FirebaseRecyclerOptions<Food> foodOptions = new FirebaseRecyclerOptions.Builder<Food>() .setQuery(searchByName,Food.class) .build(); adapter=new FirebaseRecyclerAdapter<Food, FoodViewHolder>(foodOptions) { @Override protected void onBindViewHolder(@NonNull final FoodViewHolder viewHolder, final int position, @NonNull final Food model) { viewHolder.food_name.setText(model.getName()); viewHolder.food_price.setText(String.format("Rs. %s", model.getPrice().toString())); viewHolder.food_description.setText(model.getDescription()); Transformation transformation = new RoundedTransformationBuilder() .cornerRadiusDp(8) .oval(false) .build(); Picasso.with(getBaseContext()) .load(model.getImage()) .fit() .transform(transformation) .into(viewHolder.food_image); // Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.food_image); viewHolder.quick_cart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Quick Cart boolean isExists = new Database(getBaseContext()).checkFoodExist(adapter.getRef(position).getKey(), Common.currentUser.getPhone()); if (!isExists) { new Database(getBaseContext()).addToCart(new Order( Common.currentUser.getPhone(), adapter.getRef(position).getKey(), model.getName(), "1", model.getPrice(), model.getDiscount(), model.getImage() )); } else { new Database(getBaseContext()).increaseCart(Common.currentUser.getPhone(), adapter.getRef(position).getKey()); } Toast.makeText(FoodList.this, "Added to Cart", Toast.LENGTH_SHORT).show(); } }); //Add Favroties if(localDB.isFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone())) viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp); //Click to Share /*viewHolder.share_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Picasso.with(getApplicationContext()) .load(model.getImage()) .into(target); } });*/ //Click to change state of favroties viewHolder.fav_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Favorites favorites = new Favorites(); favorites.setFoodId( adapter.getRef(position).getKey()); favorites.setFoodName(model.getName()); favorites.setFoodDescription(model.getDescription()); favorites.setFoodDiscount(model.getDiscount()); favorites.setFoodImage(model.getImage()); favorites.setFoodMenuId(model.getMenuId()); favorites.setUserPhone(Common.currentUser.getPhone()); favorites.setFoodPrice(model.getPrice()); if(!localDB.isFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone())){ localDB.addToFavorites(favorites); viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp); Toast.makeText(FoodList.this,""+model.getName()+" was added to Favorites",Toast.LENGTH_LONG).show(); } else{ localDB.removeFromFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone()); viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_border_black_24dp); Toast.makeText(FoodList.this,""+model.getName()+" was removed from Favorites",Toast.LENGTH_LONG).show(); } } }); final Food local=model; viewHolder.setItemClickListener(new ItemClickListener() { @Override public void onClick(View view, int position, boolean isLongClick) { // Toast.makeText(Home.this,""+clickItem.getName(),Toast.LENGTH_SHORT).show(); //Get CategoryID Intent foodDetail=new Intent(FoodList.this,FoodDetail.class); foodDetail.putExtra("foodId",adapter.getRef(position).getKey()); startActivity(foodDetail); } }); } @Override public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.food_item1,parent,false); return new FoodViewHolder(itemView); } }; adapter.startListening(); recyclerView.setAdapter(adapter); swipeRefreshLayout.setRefreshing(false); } @Override public void onResume(){ super.onResume(); loadListFood(categoryId); //will be executed onResume if(adapter!=null) adapter.startListening(); } @Override protected void onStop() { super.onStop(); if(adapter!=null) adapter.stopListening(); if(searchadapter!=null) searchadapter.stopListening(); } }
ae2438814871249b914a0e842f14a1141f42a0cf
82159a65b13fdfd538a17448f3a572a11489c564
/app/src/test/java/com.danilov.supermanga/core/repository/realweb/MangaReaderNetTest.java
603ffa56d24d296bbec56a0a2312a04d84683eab
[ "Apache-2.0" ]
permissive
SammyVimes/manga
130329f9cc7be733b6a2a2cb7021b9ad42a1c6f3
971f24e943239e9c1638d5da3c96b0cd33a96c88
refs/heads/master
2021-01-19T01:06:21.141338
2018-10-01T10:59:21
2018-10-01T10:59:21
53,887,772
30
13
null
2018-04-08T05:06:01
2016-03-14T20:02:52
Java
UTF-8
Java
false
false
4,797
java
package com.danilov.supermanga.core.repository.realweb; import com.danilov.supermanga.BuildConfig; import com.danilov.supermanga.core.model.Manga; import com.danilov.supermanga.core.model.MangaChapter; import com.danilov.supermanga.core.model.MangaSuggestion; import com.danilov.supermanga.core.repository.MangaReaderNetEngine; import com.danilov.supermanga.core.repository.RepositoryEngine; import com.danilov.supermanga.core.repository.RepositoryException; import com.danilov.supermanga.core.repository.RepositoryHolder; import com.danilov.supermanga.core.util.ServiceContainer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Collections; import java.util.List; /** * Created by Semyon on 19.03.2016. */ @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class MangaReaderNetTest { private MangaReaderNetEngine engine; @Before public void setUp() { RepositoryHolder service = ServiceContainer.getService(RepositoryHolder.class); RepositoryEngine.Repository repository = service.valueOf(RepositoryEngine.DefaultRepository.MANGAREADERNET.toString()); engine = (MangaReaderNetEngine) repository.getEngine(); } @After public void tearDown() { } @Test public void testGetSuggestions() { List<MangaSuggestion> suggestions = null; try { suggestions = engine.getSuggestions("Naru"); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } Assert.assertNotNull(suggestions); Assert.assertTrue(!suggestions.isEmpty()); } @Test public void testQueryRepository() { List<Manga> searchResults = null; try { searchResults = engine.queryRepository("Dragon", Collections.emptyList()); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } Assert.assertNotNull(searchResults); Assert.assertTrue(!searchResults.isEmpty()); } @Test public void testQueryForMangaDescription() { List<Manga> searchResults = null; try { searchResults = engine.queryRepository("Dragon", Collections.emptyList()); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } Assert.assertNotNull(searchResults); Assert.assertTrue(!searchResults.isEmpty()); Manga manga = searchResults.get(0); try { boolean success = engine.queryForMangaDescription(manga); Assert.assertTrue(success); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } } @Test public void testQueryForMangaChapters() { List<Manga> searchResults = null; try { searchResults = engine.queryRepository("Dragon", Collections.emptyList()); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } Assert.assertNotNull(searchResults); Assert.assertTrue(!searchResults.isEmpty()); Manga manga = searchResults.get(0); try { boolean success = engine.queryForChapters(manga); Assert.assertTrue(success); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } } @Test public void testQueryForChapterImages() { List<Manga> searchResults = null; try { searchResults = engine.queryRepository("Dragon", Collections.emptyList()); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } Assert.assertNotNull(searchResults); Assert.assertTrue(!searchResults.isEmpty()); Manga manga = searchResults.get(0); try { boolean success = engine.queryForChapters(manga); Assert.assertTrue(success); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } List<MangaChapter> chapters = manga.getChapters(); Assert.assertNotNull(chapters); Assert.assertTrue(chapters.size() > 0); MangaChapter mangaChapter = chapters.get(0); try { List<String> chapterImages = engine.getChapterImages(mangaChapter); Assert.assertTrue(chapterImages.size() > 0); } catch (RepositoryException e) { Assert.fail("Should not fail: " + e.getMessage()); } } }
876ebe0baa5139ab955193180bb21272309f1074
264f301b67d799428187cd57e75f8831005368f7
/HW2_iteration/src/S05_Prime.java
a263907a10f554c4c75c253768b920482c37143a
[]
no_license
Auphie/JAVA
44697506413b55d19404aafe0c4dd3cfa2fe4df5
767da8765acd5831952ac37a20eefe442413b6da
refs/heads/master
2021-05-01T05:53:00.589630
2018-02-11T14:24:33
2018-02-11T14:24:33
121,131,632
0
0
null
null
null
null
BIG5
Java
false
false
329
java
public class S05_Prime { public static void main(String[] args) { int x = 100; System.out.printf("小於%d的質數共有:%n",x); for(int i=2; i<x; i++) {int count = 0; for(int j=1; j<i; j++){ if(i%j == 0) count += 1; } if(count == 1) System.out.printf("%d,",i); } } }
1b6e0a3cb24591289d923f0e02df0176c0377644
c0f36ad2176cd480b0801f3d048bf6d6f4fbf5ff
/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/JobReservationException.java
ca7ced367b67f3bce6eb164b71dff82f57c00b84
[ "Apache-2.0" ]
permissive
tgianos/genie
bf93c15cb69c0b2ff4a04bca4beb6141bf76bfba
abe4f230fde07964a665ff1d5ad210836827499b
refs/heads/master
2022-06-20T23:12:50.899169
2022-05-07T16:30:36
2022-05-09T19:33:58
76,530,669
0
1
Apache-2.0
2022-01-24T17:35:23
2016-12-15T06:30:51
Java
UTF-8
Java
false
false
1,320
java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.agent.execution.exceptions; /** * Failure to reserve a job id for reasons other than the specified job id being already used. * * @author mprimi * @since 4.0.0 */ public class JobReservationException extends Exception { /** * Constructor with message. * * @param message a message */ public JobReservationException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public JobReservationException(final String message, final Throwable cause) { super(message, cause); } }
20ef3069192aa5f6560368b6142a6fc9bdfc6447
9bca04c5bb7347232385f5135c80a128896dad88
/Android/BackgroundReplacementApp/app/src/main/java/ai/fritz/replaceBackground/OverlayView.java
9f3dc51f26118e6bfaca2433285dd8b8c7cfd9e6
[ "MIT" ]
permissive
fritzlabs/fritz-examples
6b8579de22a84d14139120dc9607adaf89d8c3b2
3a74ba7fd269793b3f49b50166a6f4fe059217c1
refs/heads/master
2023-04-16T10:51:16.428826
2023-03-01T13:22:53
2023-03-01T13:22:53
114,158,003
148
91
MIT
2021-01-27T19:51:29
2017-12-13T19:00:02
Java
UTF-8
Java
false
false
884
java
package ai.fritz.replaceBackground; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; /** * A simple View providing a render callback to other classes. */ public class OverlayView extends View { private DrawCallback callback; public OverlayView(final Context context, final AttributeSet attrs) { super(context, attrs); } /** * Interface defining the callback for client classes. */ public interface DrawCallback { public void drawCallback(final Canvas canvas); } public void setCallback(final DrawCallback callback) { this.callback = callback; } @Override public synchronized void draw(final Canvas canvas) { super.draw(canvas); if(callback != null) { callback.drawCallback(canvas); } } }
d00111bf5c05eee7e88bf9d541556cf41e7b0df4
c3d9e65c697098147a681b18ced6fc154349a67e
/UserSelector.java
f38c61f590c5c693f41b160b7a6483c668ae161e
[]
no_license
DARSHAN-18-2000/S-SchoolManagment
630c77ec09c5c65e14b3b7b5c2a0bfd74af2df38
55d1ee4e413a16e1e76f1e1f88c67454aa057f51
refs/heads/main
2023-05-08T21:15:08.282919
2021-06-08T06:44:14
2021-06-08T06:44:14
374,905,791
0
0
null
null
null
null
UTF-8
Java
false
false
1,474
java
package com.example.school_app; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.content.Intent; import android.widget.Toast; public class UserSelector extends AppCompatActivity { SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_selector); sp=getSharedPreferences("MyUserPrefs", Context.MODE_PRIVATE); } public void Studentfunc(View view) { SharedPreferences.Editor editor = sp.edit(); editor.putString("selectdb","student_details"); editor.commit(); Intent i =new Intent(getApplicationContext(),MainActivity.class); startActivity(i); } public void Teacherfunc(View view) { SharedPreferences.Editor editor = sp.edit(); editor.putString("selectdb","teacherdb"); editor.commit(); Intent i =new Intent(getApplicationContext(),MainActivity.class); startActivity(i); } public void Parentfunc(View view) { SharedPreferences.Editor editor = sp.edit(); editor.putString("selectdb","parentdb"); editor.commit(); Intent i =new Intent(getApplicationContext(),MainActivity.class); startActivity(i); } }
330c1755937553b619d73dd917c2817443775af3
64cb91c34c4098315fe735711631d14254182362
/java/wenxin/leetcode/java/SuperUglyNumber.java
d141da0a6478526531bc7353846188e9cd8cca8b
[]
no_license
wl4kx/Leetcode
d47be00b75919d2197dd18846fd067bf56423814
c00179b522996edd2e9d4b65445ce46d2241bdee
refs/heads/master
2021-01-15T08:09:30.565400
2016-08-26T00:58:39
2016-08-26T00:58:39
38,285,019
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
1,303
java
package wenxin.leetcode.java; /* * Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4. Note: (1) 1 is a super ugly number for any given primes. (2) The given numbers in primes are in ascending order. (3) 0 < k ¡Ü 100, 0 < n ¡Ü 106, 0 < primes[i] < 1000. */ public class SuperUglyNumber { public static void main(String[] args) { // TODO Auto-generated method stub } // http://bookshadow.com/weblog/2015/12/03/leetcode-super-ugly-number/ public int nthSuperUglyNumber(int n, int[] primes) { int size = primes.length; int q[] = new int[n]; int idxes[] = new int[size]; int vals[] = new int[size]; q[0] = 1; for (int i = 1; i < n; i++) { for (int j = 0; j < size; j++) { vals[j] = q[idxes[j]] * primes[j]; } q[i] = findMin(vals); for (int j = 0; j < size; j++) { if (vals[j] == q[i]) { idxes[j] += 1; } } } return q[n - 1]; } public int findMin(int[] nums) { int min = nums[0]; for (int i = 1; i < nums.length; i++) { min = Math.min(min, nums[i]); } return min; } }
b89816f5bb61b773e45979708c7561d373bc838b
93f9247011407dca684b365b5a2e64b65f7b4fe4
/src/main/java/com/project/bookstore/model/UserSignupInputData.java
8f950f18f28e723ee01b8e97e2d407fe97cd5916
[]
no_license
rushilp2311/4413-Backend
09a11e4fa3a19f92b24c1984591ae90bae503a2c
8026851f5b97066dc79f926a06968123ec97a75b
refs/heads/main
2023-01-28T07:38:44.592195
2020-12-07T04:16:14
2020-12-07T04:16:14
310,707,203
0
2
null
null
null
null
UTF-8
Java
false
false
977
java
package com.project.bookstore.model; public class UserSignupInputData { private String firstName; private String lastName; private String email; private String password; public UserSignupInputData() { } public UserSignupInputData(String firstName, String lastName, String email, String password) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
ab8ec1d175e19851f16a4706ba56ef574c5a370a
208ba847cec642cdf7b77cff26bdc4f30a97e795
/di/db/src/main/java/org.wp.db/ui/comments/CommentActions.java
3246505cdf409d39c2e01c6479661dd5dae6ef00
[]
no_license
kageiit/perf-android-large
ec7c291de9cde2f813ed6573f706a8593be7ac88
2cbd6e74837a14ae87c1c4d1d62ac3c35df9e6f8
refs/heads/master
2021-01-12T14:00:19.468063
2016-09-27T13:10:42
2016-09-27T13:10:42
69,685,305
0
0
null
2016-09-30T16:59:49
2016-09-30T16:59:48
null
UTF-8
Java
false
false
20,667
java
package org.wp.db.ui.comments; import android.os.Handler; import android.text.TextUtils; import com.android.volley.VolleyError; import com.wordpress.rest.RestRequest; import org.json.JSONObject; import org.wp.db.WordPress; import org.wp.db.datasets.CommentTable; import org.wp.db.models.Blog; import org.wp.db.models.Comment; import org.wp.db.models.CommentList; import org.wp.db.models.CommentStatus; import org.wp.db.models.Note; import org.wp.db.util.AppLog; import org.wp.db.util.AppLog.T; import org.wp.db.util.VolleyUtils; import org.xmlpull.v1.XmlPullParserException; import org.xmlrpc.db.ApiHelper; import org.xmlrpc.db.ApiHelper.Method; import org.xmlrpc.db.XMLRPCClientInterface; import org.xmlrpc.db.XMLRPCException; import org.xmlrpc.db.XMLRPCFactory; import org.xmlrpc.db.XMLRPCFault; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * actions related to comments - replies, moderating, etc. * methods below do network calls in the background & update local DB upon success * all methods below MUST be called from UI thread */ public class CommentActions { private CommentActions() { throw new AssertionError(); } /* * listener when a comment action is performed */ public interface CommentActionListener { void onActionResult(CommentActionResult result); } /* * listener when comments are moderated or deleted */ public interface OnCommentsModeratedListener { void onCommentsModerated(final CommentList moderatedComments); } /* * used by comment fragments to alert container activity of a change to one or more * comments (moderated, deleted, added, etc.) */ public enum ChangeType {EDITED, REPLIED} public interface OnCommentChangeListener { void onCommentChanged(ChangeType changeType); } public interface OnCommentActionListener { void onModerateComment(int accountId, Comment comment, CommentStatus newStatus); } public interface OnNoteCommentActionListener { void onModerateCommentForNote(Note note, CommentStatus newStatus); } /** * reply to an individual comment */ static void submitReplyToComment(final int accountId, final Comment comment, final String replyText, final CommentActionListener actionListener) { final Blog blog = WordPress.getBlog(accountId); if (blog==null || comment==null || TextUtils.isEmpty(replyText)) { if (actionListener != null) { actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); } return; } final Handler handler = new Handler(); new Thread() { @Override public void run() { XMLRPCClientInterface client = XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), blog.getHttppassword()); Map<String, Object> replyHash = new HashMap<>(); replyHash.put("comment_parent", Long.toString(comment.commentID)); replyHash.put("content", replyText); replyHash.put("author", ""); replyHash.put("author_url", ""); replyHash.put("author_email", ""); Object[] params = { blog.getRemoteBlogId(), blog.getUsername(), blog.getPassword(), Long.toString(comment.postID), replyHash }; long newCommentID; String message = null; try { Object newCommentIDObject = client.call(Method.NEW_COMMENT, params); if (newCommentIDObject instanceof Integer) { newCommentID = ((Integer) newCommentIDObject).longValue(); } else if (newCommentIDObject instanceof Long) { newCommentID = (Long) newCommentIDObject; } else { AppLog.e(T.COMMENTS, "wp.newComment returned the wrong data type"); newCommentID = CommentActionResult.COMMENT_ID_ON_ERRORS; } } catch (XMLRPCFault e) { AppLog.e(T.COMMENTS, "Error while sending the new comment", e); newCommentID = CommentActionResult.COMMENT_ID_ON_ERRORS; message = e.getFaultString(); } catch (XMLRPCException | IOException | XmlPullParserException e) { AppLog.e(T.COMMENTS, "Error while sending the new comment", e); newCommentID = CommentActionResult.COMMENT_ID_ON_ERRORS; } final CommentActionResult cr = new CommentActionResult(newCommentID, message); if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onActionResult(cr); } }); } } }.start(); } /** * reply to an individual comment that came from a notification - this differs from * submitReplyToComment() in that it enables responding to a reply to a comment this * user made on someone else's blog */ public static void submitReplyToCommentNote(final Note note, final String replyText, final CommentActionListener actionListener) { if (note == null || TextUtils.isEmpty(replyText)) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_UNKNOWN, null)); } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) AppLog.e(T.COMMENTS, volleyError.getMessage(), volleyError); if (actionListener != null) { actionListener.onActionResult( new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, VolleyUtils.messageStringFromVolleyError(volleyError)) ); } } }; Note.Reply reply = note.buildReply(replyText); WordPress.getRestClientUtils().replyToComment(reply.getContent(), reply.getRestPath(), listener, errorListener); } /** * reply to an individual comment via the WP.com REST API */ public static void submitReplyToCommentRestApi(long siteId, long commentId, final String replyText, final CommentActionListener actionListener) { if (TextUtils.isEmpty(replyText)) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_UNKNOWN, null)); } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { if (volleyError != null) AppLog.e(T.COMMENTS, volleyError.getMessage(), volleyError); if (actionListener != null) actionListener.onActionResult( new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, VolleyUtils.messageStringFromVolleyError(volleyError)) ); } }; WordPress.getRestClientUtils().replyToComment(siteId, commentId, replyText, listener, errorListener); } /** * Moderate a comment from a WPCOM notification */ public static void moderateCommentRestApi(long siteId, final long commentId, CommentStatus newStatus, final CommentActionListener actionListener) { WordPress.getRestClientUtils().moderateComment( String.valueOf(siteId), String.valueOf(commentId), CommentStatus.toRESTString(newStatus), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { if (actionListener != null) { actionListener.onActionResult(new CommentActionResult(commentId, null)); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (actionListener != null) { actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); } } } ); } /** * Moderate a comment from a WPCOM notification */ public static void moderateCommentForNote(final Note note, CommentStatus newStatus, final CommentActionListener actionListener) { WordPress.getRestClientUtils().moderateComment( String.valueOf(note.getSiteId()), String.valueOf(note.getCommentId()), CommentStatus.toRESTString(newStatus), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { if (actionListener != null) { actionListener.onActionResult(new CommentActionResult(note.getCommentId(), null)); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (actionListener != null) { actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); } } } ); } /** * change the status of a single comment */ static void moderateComment(final int accountId, final Comment comment, final CommentStatus newStatus, final CommentActionListener actionListener) { // deletion is handled separately if (newStatus != null && (newStatus.equals(CommentStatus.TRASH) || newStatus.equals(CommentStatus.DELETE))) { deleteComment(accountId, comment, actionListener, newStatus.equals(CommentStatus.DELETE)); return; } final Blog blog = WordPress.getBlog(accountId); if (blog==null || comment==null || newStatus==null || newStatus==CommentStatus.UNKNOWN) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } final Handler handler = new Handler(); new Thread() { @Override public void run() { final boolean success = ApiHelper.editComment(blog, comment, newStatus); if (success) { CommentTable.updateCommentStatus(blog.getLocalTableBlogId(), comment.commentID, CommentStatus .toString(newStatus)); } if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onActionResult(new CommentActionResult(comment.commentID, null)); } }); } } }.start(); } /** * change the status of multiple comments * TODO: investigate using system.multiCall to perform a single call to moderate the list */ static void moderateComments(final int accountId, final CommentList comments, final CommentStatus newStatus, final OnCommentsModeratedListener actionListener) { // deletion is handled separately if (newStatus != null && (newStatus.equals(CommentStatus.TRASH) || newStatus.equals(CommentStatus.DELETE))) { deleteComments(accountId, comments, actionListener, newStatus.equals(CommentStatus.DELETE)); return; } final Blog blog = WordPress.getBlog(accountId); if (blog==null || comments==null || comments.size() == 0 || newStatus==null || newStatus==CommentStatus.UNKNOWN) { if (actionListener != null) actionListener.onCommentsModerated(new CommentList()); return; } final CommentList moderatedComments = new CommentList(); final String newStatusStr = CommentStatus.toString(newStatus); final int localBlogId = blog.getLocalTableBlogId(); final Handler handler = new Handler(); new Thread() { @Override public void run() { for (Comment comment: comments) { if (ApiHelper.editComment(blog, comment, newStatus)) { comment.setStatus(newStatusStr); moderatedComments.add(comment); } } // update status in SQLite of successfully moderated comments CommentTable.updateCommentsStatus(localBlogId, moderatedComments, newStatusStr); if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onCommentsModerated(moderatedComments); } }); } } }.start(); } /** * delete (trash) a single comment */ private static void deleteComment(final int accountId, final Comment comment, final CommentActionListener actionListener, final boolean deletePermanently) { final Blog blog = WordPress.getBlog(accountId); if (blog==null || comment==null) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } final Handler handler = new Handler(); new Thread() { @Override public void run() { XMLRPCClientInterface client = XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), blog.getHttppassword()); Object[] params = { blog.getRemoteBlogId(), blog.getUsername(), blog.getPassword(), comment.commentID, deletePermanently}; Object result; try { result = client.call(Method.DELETE_COMMENT, params); } catch (final XMLRPCException | XmlPullParserException | IOException e) { AppLog.e(T.COMMENTS, "Error while deleting comment", e); result = null; } //update local database final boolean success = (result != null && Boolean.parseBoolean(result.toString())); if (success){ if (deletePermanently) { CommentTable.deleteComment(accountId, comment.commentID); } else { // update status in SQLite of successfully moderated comments CommentTable.updateCommentStatus(blog.getLocalTableBlogId(), comment.commentID, CommentStatus.toString(CommentStatus.TRASH)); } } if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onActionResult(new CommentActionResult(comment.commentID, null)); } }); } } }.start(); } /** * delete multiple comments */ private static void deleteComments(final int accountId, final CommentList comments, final OnCommentsModeratedListener actionListener, final boolean deletePermanently) { final Blog blog = WordPress.getBlog(accountId); if (blog==null || comments==null || comments.size() == 0) { if (actionListener != null) actionListener.onCommentsModerated(new CommentList()); return; } final CommentList deletedComments = new CommentList(); final int localBlogId = blog.getLocalTableBlogId(); final int remoteBlogId = blog.getRemoteBlogId(); final Handler handler = new Handler(); new Thread() { @Override public void run() { XMLRPCClientInterface client = XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), blog.getHttppassword()); for (Comment comment: comments) { Object[] params = { remoteBlogId, blog.getUsername(), blog.getPassword(), comment.commentID, deletePermanently}; Object result; try { result = client.call(Method.DELETE_COMMENT, params); boolean success = (result != null && Boolean.parseBoolean(result.toString())); if (success) deletedComments.add(comment); } catch (XMLRPCException | XmlPullParserException | IOException e) { AppLog.e(T.COMMENTS, "Error while deleting comment", e); } } // remove successfully deleted comments from SQLite if (deletePermanently) { CommentTable.deleteComments(localBlogId, deletedComments); } else { // update status in SQLite of successfully moderated comments CommentTable.updateCommentsStatus(blog.getLocalTableBlogId(), deletedComments, CommentStatus.toString(CommentStatus.TRASH)); } if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onCommentsModerated(deletedComments); } }); } } }.start(); } }
f142dad76edb37d1b4a6b71d620df172a7fca4ce
4367bbdad8fd6a31c127c9b6a7fc84c11a9328b3
/Arrays/SumOfArrayElmnts.java
269eb15412121d0bb0b30744971403e752957e55
[]
no_license
DBALAK/SpringPrograms
a537d4763d9b2441a0dd614c2f3e25c3c9c5faf2
4e85e00950bb3e749aa32de1997cb23520cba0e0
refs/heads/master
2021-09-03T04:32:45.437392
2018-01-05T15:37:11
2018-01-05T15:37:11
112,945,185
0
0
null
null
null
null
UTF-8
Java
false
false
580
java
package com.arrays; public class SumOfArrayElmnts { public static void main(String[] args) { int a[] = { 2, 6, 8, 9, 3 }, sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; } System.out.println("Without Recursion:"); System.out.println(sum); int sum1 = sumWithRecursion(a, a.length - 1); System.out.println("With Recursion:"); System.out.println(sum1); } private static int sumWithRecursion(int[] a, int n) { if (n == 0) { return a[n]; } else { return a[n] + sumWithRecursion(a, n - 1); } } }
f0d553f681a476d4ebdab992f1e49de65957b835
9d334e61860801337761f5b0b5663183f588b786
/libresdk/src/main/java/com/mavid/libresdk/TaskManager/SAC/Listeners/SACListenerWithResponse.java
d675553ef75fbf787e80fcdec8d65a49d78d1c3d
[]
no_license
atul-17/Mavid3m
4f9a7d78c7739319b1d86f67d60a125439a8dd2e
c64175ad1d9f91906cda1c263ffa277ae61179c6
refs/heads/master
2023-01-05T23:45:15.310176
2020-10-31T06:53:03
2020-10-31T06:53:03
286,229,267
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
package com.mavid.libresdk.TaskManager.SAC.Listeners; import com.mavid.libresdk.TaskManager.Discovery.Listeners.ListenerUtils.MessageInfo; /** * Created by bhargav on 27/4/18. */ public interface SACListenerWithResponse { public void response(MessageInfo messageInfo); public void failure(Exception e); }
99acaa4b9614d4159316d822be034ca31943cfbb
53527e1e18eaa45a9560c088f3481e9474947aae
/app/src/main/java/com/example/getsumfoot/data/EventMapData.java
654761263ec907ed314ea6c32f227f52639c1f14
[]
no_license
JonghunAn/getSum_foodtruck
c7d3c824686df9023205c521c56d3a78a8815174
533581e82c5ca0cea7b292c7967d531cd9ab139d
refs/heads/master
2023-01-30T01:57:54.030424
2020-12-11T18:16:00
2020-12-11T18:16:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
840
java
package com.example.getsumfoot.data; import org.jetbrains.annotations.NotNull; public class EventMapData { public double 위도,경도; public String 소재지도로명주소; EventMapData(){} public EventMapData(double 위도, double 경도){ this.위도 = 위도; this.경도 = 경도; } public double get_latitude(){ return 위도; } public void set_latitude(int 위도) { this.위도 = 위도; } public double get_longitude(){ return 경도; } public void set_longitude(int 경도) { this.경도 = 경도; } public String get_roadAdress(){ return 소재지도로명주소; } public void set_roadAdress(int 경도) { this.경도 = 경도; } }
c20a6cd43a0be62e60a12ac6ba5905ba8f8c4d2e
3f9c5f9bd4317d56196461f46b1d482c0a20df9b
/src/main/java/com/frostwire/jlibtorrent/plugins/SwigPlugin.java
5a4624f89be0791c314ccf3c219154be60d568e4
[ "MIT" ]
permissive
davidxv/frostwire-jlibtorrent
2c2bf139ef8d2ebce1873f6638e59e1892ce5d91
c6a1c82dcb167b81bfe21cd0fc21a7d91c15e773
refs/heads/master
2021-01-17T20:17:20.655235
2015-10-20T05:06:01
2015-10-20T05:06:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,160
java
package com.frostwire.jlibtorrent.plugins; import com.frostwire.jlibtorrent.*; import com.frostwire.jlibtorrent.alerts.Alerts; import com.frostwire.jlibtorrent.swig.*; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * @author gubatron * @author aldenml */ public final class SwigPlugin extends swig_plugin { private static final Logger LOG = Logger.getLogger(SwigPlugin.class); private final Plugin p; private final List<SwigTorrentPlugin> mem; private final Object memLock; private final List<SwigDhtPlugin> memDht; public SwigPlugin(Plugin p) { this.p = p; this.mem = new LinkedList<SwigTorrentPlugin>(); this.memLock = new Object(); this.memDht = new LinkedList<SwigDhtPlugin>(); } @Override public swig_torrent_plugin new_torrent(torrent_handle t) { try { if (p.handleOperation(Plugin.Operation.NEW_TORRENT)) { TorrentPlugin tp = p.newTorrent(new TorrentHandle(t)); if (tp != null) { return pin(new SwigTorrentPlugin(tp, t)); } } } catch (Throwable e) { LOG.error("Error in plugin (new_torrent)", e); } return super.new_torrent(t); } @Override public void added(session_handle s) { try { p.added(new SessionHandle(s)); } catch (Throwable e) { LOG.error("Error in plugin (added)", e); } } @Override public void register_dht_extensions(string_dht_extension_handler_listener_ptr_pair_vector dht_extensions) { try { if (p.handleOperation(Plugin.Operation.REGISTER_DHT_EXTENSIONS)) { List<Pair<String, DhtPlugin>> plugins = new LinkedList<Pair<String, DhtPlugin>>(); p.registerDhtPlugins(plugins); for (Pair<String, DhtPlugin> pp : plugins) { String q = pp.first; SwigDhtPlugin h = pin(new SwigDhtPlugin(pp.second)); string_dht_extension_handler_listener_ptr_pair pair = new string_dht_extension_handler_listener_ptr_pair(q, h); dht_extensions.add(pair); } } } catch (Throwable e) { LOG.error("Error in plugin (register_dht_extensions)", e); } } @Override public void on_alert(alert a) { try { if (p.handleOperation(Plugin.Operation.ON_ALERT)) { p.onAlert(Alerts.cast(a)); } } catch (Throwable e) { LOG.error("Error in plugin (on_alert)", e); } } @Override public boolean on_unknown_torrent(sha1_hash info_hash, peer_connection_handle pc, add_torrent_params p) { try { if (this.p.handleOperation(Plugin.Operation.ON_UNKNOWN_TORRENT)) { return this.p.onUnknownTorrent(new Sha1Hash(info_hash), new PeerConnection(pc.native_handle()), new AddTorrentParams(p)); } } catch (Throwable e) { LOG.error("Error in plugin (on_unknown_torrent)", e); } return false; } @Override public void on_tick() { try { p.onTick(); } catch (Throwable e) { LOG.error("Error in plugin (on_tick)", e); } cleanup(); } @Override public boolean on_optimistic_unchoke(peer_connection_handle_vector peers) { try { if (this.p.handleOperation(Plugin.Operation.ON_OPTIMISTIC_UNCHOKE)) { int size = (int) peers.size(); PeerConnectionHandle[] arr = new PeerConnectionHandle[size]; for (int i = 0; i < size; i++) { arr[i] = new PeerConnectionHandle(peers.get(i)); } return p.onOptimisticUnchoke(arr); } } catch (Throwable e) { LOG.error("Error in plugin (on_optimistic_unchoke)", e); } return false; } @Override public void save_state(entry e) { try { if (p.handleOperation(Plugin.Operation.SAVE_STATE)) { p.saveState(new Entry(e)); } } catch (Throwable t) { LOG.error("Error in plugin (save_state)", t); } } @Override public void load_state(bdecode_node n) { try { if (p.handleOperation(Plugin.Operation.LOAD_STATE)) { p.loadState(n); } } catch (Throwable e) { LOG.error("Error in plugin (load_state)", e); } } private SwigTorrentPlugin pin(SwigTorrentPlugin p) { mem.add(p); return p; } private SwigDhtPlugin pin(SwigDhtPlugin p) { memDht.add(p); return p; } private void cleanup() { synchronized (memLock) { Iterator<SwigTorrentPlugin> it = mem.iterator(); while (it.hasNext()) { SwigTorrentPlugin p = it.next(); if (p.t.is_aborted()) { it.remove(); } } } } }
92322d9e5dd8515b44c3b2a859ff9121ad2f8425
515af6cf1cbee1a5428d9782cc8f215c4fc0c746
/src/day59_polymorphism_exceptions/InputField.java
3f4a3266651974a8a6db49ccd8ffee793f70663f
[]
no_license
XinFuxuan/Java-programming
f2e0ac0e568ceeab5d30edd82c2f551d27379e8b
468b9b859621cc4ffedfa9369ab9f9f664e1ad81
refs/heads/master
2023-06-19T04:26:56.020945
2021-07-18T21:08:30
2021-07-18T21:08:30
371,525,207
0
0
null
2021-05-29T21:07:01
2021-05-27T23:09:29
Java
UTF-8
Java
false
false
606
java
package day59_polymorphism_exceptions; public class InputField implements WebElement { public static final String TAG_NAME = "input"; public String getValue() { System.out.println("Getting value in the InputField"); return "selenium"; } @Override public void sendKeys(String txt) { System.out.println("Typing into input field - " + txt); } @Override public void click() { System.out.println(""); } @Override public String getText() { System.out.println("getting text of input field"); return "java"; } }
b991eec7c737db6158c4859afcf1192ff4f6b754
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_92b3a7d282086806cfd59aa7a853655e0e5856c4/WindowsDisplay/2_92b3a7d282086806cfd59aa7a853655e0e5856c4_WindowsDisplay_s.java
f6236604d478c3f6de28d70e6794c510fa389124
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
19,126
java
/* * Copyright (c) 2002-2004 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lwjgl.opengl; /** * This is the Display implementation interface. Display delegates * to implementors of this interface. There is one DisplayImplementation * for each supported platform. * @author elias_naur */ import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.lwjgl.LWJGLException; import org.lwjgl.LWJGLUtil; import org.lwjgl.input.Cursor; final class WindowsDisplay implements DisplayImplementation { private final static int GAMMA_LENGTH = 256; private final static int WM_MOUSEMOVE = 0x0200; private final static int WM_LBUTTONDOWN = 0x0201; private final static int WM_LBUTTONUP = 0x0202; private final static int WM_LBUTTONDBLCLK = 0x0203; private final static int WM_RBUTTONDOWN = 0x0204; private final static int WM_RBUTTONUP = 0x0205; private final static int WM_RBUTTONDBLCLK = 0x0206; private final static int WM_MBUTTONDOWN = 0x0207; private final static int WM_MBUTTONUP = 0x0208; private final static int WM_MBUTTONDBLCLK = 0x0209; private final static int WM_MOUSEWHEEL = 0x020A; private final static int WM_QUIT = 0x0012; private final static int WM_SYSCOMMAND = 0x0112; private final static int WM_PAINT = 0x000F; private final static int SC_SIZE = 0xF000; private final static int SC_MOVE = 0xF010; private final static int SC_MINIMIZE = 0xF020; private final static int SC_MAXIMIZE = 0xF030; private final static int SC_NEXTWINDOW = 0xF040; private final static int SC_PREVWINDOW = 0xF050; private final static int SC_CLOSE = 0xF060; private final static int SC_VSCROLL = 0xF070; private final static int SC_HSCROLL = 0xF080; private final static int SC_MOUSEMENU = 0xF090; private final static int SC_KEYMENU = 0xF100; private final static int SC_ARRANGE = 0xF110; private final static int SC_RESTORE = 0xF120; private final static int SC_TASKLIST = 0xF130; private final static int SC_SCREENSAVE = 0xF140; private final static int SC_HOTKEY = 0xF150; private final static int SC_DEFAULT = 0xF160; private final static int SC_MONITORPOWER = 0xF170; private final static int SC_CONTEXTHELP = 0xF180; private final static int SC_SEPARATOR = 0xF00F; private final static int SM_CXCURSOR = 13; private final static int SIZE_RESTORED = 0; private final static int SIZE_MINIMIZED = 1; private final static int SIZE_MAXIMIZED = 2; private final static int WM_SIZE = 0x0005; private final static int WM_ACTIVATE = 0x0006; private final static int WA_INACTIVE = 0; private final static int WA_ACTIVE = 1; private final static int WA_CLICKACTIVE = 2; private final static int SW_SHOWMINNOACTIVE = 7; private final static int SW_RESTORE = 9; private static WindowsDisplay current_display; private WindowsDisplayPeerInfo peer_info; private WindowsKeyboard keyboard; private WindowsMouse mouse; private boolean close_requested; private boolean is_dirty; private ByteBuffer current_gamma; private ByteBuffer saved_gamma; private DisplayMode current_mode; private boolean mode_set; private boolean isFullscreen; private boolean isMinimized; private boolean isFocused; private boolean did_maximize; private boolean inAppActivate; public WindowsDisplay() { current_display = this; } public void createWindow(DisplayMode mode, boolean fullscreen, int x, int y) throws LWJGLException { close_requested = false; is_dirty = false; isFullscreen = fullscreen; isMinimized = false; isFocused = false; did_maximize = false; nCreateWindow(mode, fullscreen, x, y); peer_info.initDC(); } private native void nCreateWindow(DisplayMode mode, boolean fullscreen, int x, int y) throws LWJGLException; public void destroyWindow() { nDestroyWindow(); if (isFullscreen) resetCursorClipping(); } private static native void nDestroyWindow(); private static native void resetCursorClipping(); private static native void setupCursorClipping(long hwnd) throws LWJGLException; public void switchDisplayMode(DisplayMode mode) throws LWJGLException { nSwitchDisplayMode(mode); current_mode = mode; mode_set = true; } private static native void nSwitchDisplayMode(DisplayMode mode) throws LWJGLException; /* * Called when the application is alt-tabbed to or from */ private void appActivate(boolean active) { if (inAppActivate) { return; } inAppActivate = true; isFocused = active; if (active) { if (isFullscreen) { restoreDisplayMode(); } showWindow(getHwnd(), SW_RESTORE); setForegroundWindow(getHwnd()); setFocus(getHwnd()); did_maximize = true; } else if (isFullscreen) { showWindow(getHwnd(), SW_SHOWMINNOACTIVE); resetDisplayMode(); } inAppActivate = false; } private static native void showWindow(long hwnd, int mode); private static native void setForegroundWindow(long hwnd); private static native void setFocus(long hwnd); private void restoreDisplayMode() { try { doSetGammaRamp(current_gamma); } catch (LWJGLException e) { LWJGLUtil.log("Failed to restore gamma: " + e.getMessage()); } if (!mode_set) { mode_set = true; try { nSwitchDisplayMode(current_mode); } catch (LWJGLException e) { LWJGLUtil.log("Failed to restore display mode: " + e.getMessage()); } } } public void resetDisplayMode() { try { doSetGammaRamp(saved_gamma); } catch (LWJGLException e) { LWJGLUtil.log("Failed to reset gamma ramp: " + e.getMessage()); } current_gamma = saved_gamma; if (mode_set) { mode_set = false; nResetDisplayMode(); } resetCursorClipping(); } private static native void nResetDisplayMode(); public int getGammaRampLength() { return GAMMA_LENGTH; } public void setGammaRamp(FloatBuffer gammaRamp) throws LWJGLException { doSetGammaRamp(convertToNativeRamp(gammaRamp)); } private static native ByteBuffer convertToNativeRamp(FloatBuffer gamma_ramp) throws LWJGLException; private static native ByteBuffer getCurrentGammaRamp() throws LWJGLException; private void doSetGammaRamp(ByteBuffer native_gamma) throws LWJGLException { nSetGammaRamp(native_gamma); current_gamma = native_gamma; } private static native void nSetGammaRamp(ByteBuffer native_ramp) throws LWJGLException; public String getAdapter() { try { String adapter_string = WindowsRegistry.queryRegistrationKey( WindowsRegistry.HKEY_LOCAL_MACHINE, "HARDWARE\\DeviceMap\\Video", "\\Device\\Video0"); String root_key = "\\registry\\machine\\"; if (adapter_string.toLowerCase().startsWith(root_key)) { String driver_value = WindowsRegistry.queryRegistrationKey( WindowsRegistry.HKEY_LOCAL_MACHINE, adapter_string.substring(root_key.length()), "InstalledDisplayDrivers"); return driver_value; } } catch (LWJGLException e) { LWJGLUtil.log("Exception occurred while querying registry: " + e); } return null; } public String getVersion() { String driver = getAdapter(); if (driver != null) { WindowsFileVersion version = nGetVersion(driver + ".dll"); if (version != null) return version.toString(); } return null; } private native WindowsFileVersion nGetVersion(String driver); public DisplayMode init() throws LWJGLException { current_gamma = saved_gamma = getCurrentGammaRamp(); return current_mode = getCurrentDisplayMode(); } private static native DisplayMode getCurrentDisplayMode() throws LWJGLException; public native void setTitle(String title); public boolean isCloseRequested() { boolean saved = close_requested; close_requested = false; return saved; } public boolean isVisible() { return !isMinimized; } public boolean isActive() { return isFocused; } public boolean isDirty() { boolean saved = is_dirty; is_dirty = false; return saved; } public PeerInfo createPeerInfo(PixelFormat pixel_format) throws LWJGLException { peer_info = new WindowsDisplayPeerInfo(pixel_format); return peer_info; } public void update() { nUpdate(); if (did_maximize) { did_maximize = false; /** * WORKAROUND: * Making the context current (redundantly) when the window * is maximized helps some gfx recover from fullscreen */ try { if (Display.getContext().isCurrent()) Display.getContext().makeCurrent(); } catch (LWJGLException e) { LWJGLUtil.log("Exception occurred while trying to make context current: " + e); } } } private static native void nUpdate(); public void reshape(int x, int y, int width, int height) { if (!isFullscreen) nReshape(getHwnd(), x, y, width, height); } private static native void nReshape(long hwnd, int x, int y, int width, int height); public native DisplayMode[] getAvailableDisplayModes() throws LWJGLException; /* Mouse */ public boolean hasWheel() { return mouse.hasWheel(); } public int getButtonCount() { return mouse.getButtonCount(); } public void createMouse() throws LWJGLException { mouse = new WindowsMouse(createDirectInput(), getHwnd()); } public void destroyMouse() { mouse.destroy(); mouse = null; } public void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons) { update(); mouse.poll(coord_buffer, buttons); } public void readMouse(ByteBuffer buffer) { update(); mouse.read(buffer); } public void grabMouse(boolean grab) { mouse.grab(grab); } public int getNativeCursorCapabilities() { return Cursor.CURSOR_ONE_BIT_TRANSPARENCY; } public void setCursorPosition(int x, int y) { nSetCursorPosition(x, y, isFullscreen); } private static native void nSetCursorPosition(int x, int y, boolean fullscreen); public native void setNativeCursor(Object handle) throws LWJGLException; public int getMinCursorSize() { return getSystemMetrics(SM_CXCURSOR); } public int getMaxCursorSize() { return getSystemMetrics(SM_CXCURSOR); } public native int getSystemMetrics(int index); private static native long getDllInstance(); private static native long getHwnd(); /* Keyboard */ public void createKeyboard() throws LWJGLException { keyboard = new WindowsKeyboard(createDirectInput(), getHwnd()); } public void destroyKeyboard() { keyboard.destroy(); keyboard = null; } public void pollKeyboard(ByteBuffer keyDownBuffer) { update(); keyboard.poll(keyDownBuffer); } public void readKeyboard(ByteBuffer buffer) { update(); keyboard.read(buffer); } // public native int isStateKeySet(int key); public native ByteBuffer nCreateCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, int images_offset, IntBuffer delays, int delays_offset) throws LWJGLException; public Object createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException { return nCreateCursor(width, height, xHotspot, yHotspot, numImages, images, images.position(), delays, delays != null ? delays.position() : -1); } public native void destroyCursor(Object cursorHandle); public int getPbufferCapabilities() { try { // Return the capabilities of a minimum pixel format return nGetPbufferCapabilities(new PixelFormat(0, 0, 0, 0, 0, 0, 0, 0, false)); } catch (LWJGLException e) { LWJGLUtil.log("Exception occurred while determining pbuffer capabilities: " + e); return 0; } } private native int nGetPbufferCapabilities(PixelFormat format) throws LWJGLException; public boolean isBufferLost(PeerInfo handle) { return ((WindowsPbufferPeerInfo)handle).isBufferLost(); } public PeerInfo createPbuffer(int width, int height, PixelFormat pixel_format, IntBuffer pixelFormatCaps, IntBuffer pBufferAttribs) throws LWJGLException { return new WindowsPbufferPeerInfo(width, height, pixel_format, pixelFormatCaps, pBufferAttribs); } public void setPbufferAttrib(PeerInfo handle, int attrib, int value) { ((WindowsPbufferPeerInfo)handle).setPbufferAttrib(attrib, value); } public void bindTexImageToPbuffer(PeerInfo handle, int buffer) { ((WindowsPbufferPeerInfo)handle).bindTexImageToPbuffer(buffer); } public void releaseTexImageFromPbuffer(PeerInfo handle, int buffer) { ((WindowsPbufferPeerInfo)handle).releaseTexImageFromPbuffer(buffer); } /** * Sets one or more icons for the Display. * <ul> * <li>On Windows you should supply at least one 16x16 icon and one 32x32.</li> * <li>Linux (and similar platforms) expect one 32x32 icon.</li> * <li>Mac OS X should be supplied one 128x128 icon</li> * </ul> * The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform. * * @param icons Array of icons in RGBA mode * @return number of icons used. */ public int setIcon(ByteBuffer[] icons) { boolean done16 = false; boolean done32 = false; int used = 0; for (int i=0;i<icons.length;i++) { int size = icons[i].limit() / 4; if ((((int) Math.sqrt(size)) == 16) && (!done16)) { nSetWindowIcon16(icons[i].asIntBuffer()); used++; done16 = true; } if ((((int) Math.sqrt(size)) == 32) && (!done32)) { nSetWindowIcon32(icons[i].asIntBuffer()); used++; done32 = true; } } return used; } private static native int nSetWindowIcon16(IntBuffer icon); private static native int nSetWindowIcon32(IntBuffer icon); private void handleMouseButton(int button, int state, long millis) { if (mouse != null) mouse.handleMouseButton((byte)button, (byte)state, millis); } private void handleMouseMoved(int x, int y, long millis) { if (mouse != null) mouse.handleMouseMoved(x, y, millis); } private void handleMouseScrolled(int amount, long millis) { if (mouse != null) mouse.handleMouseScrolled(amount, millis); } private static native int transformY(long hwnd, int y); private static boolean handleMessage(long hwnd, int msg, long wParam, long lParam, long millis) { if (current_display != null) return current_display.doHandleMessage(hwnd, msg, wParam, lParam, millis); else return false; } private boolean doHandleMessage(long hwnd, int msg, long wParam, long lParam, long millis) { if (isFullscreen && !isMinimized && isFocused) { try { setupCursorClipping(getHwnd()); } catch (LWJGLException e) { LWJGLUtil.log("setupCursorClipping failed: " + e.getMessage()); } } switch (msg) { // disable screen saver and monitor power down messages which wreak havoc case WM_ACTIVATE: switch ((int)wParam) { case WA_ACTIVE: case WA_CLICKACTIVE: appActivate(true); break; case WA_INACTIVE: appActivate(false); break; } return true; case WM_SIZE: switch ((int)wParam) { case SIZE_RESTORED: case SIZE_MAXIMIZED: isMinimized = false; break; case SIZE_MINIMIZED: isMinimized = true; break; } return false; case WM_MOUSEMOVE: int xPos = (int)(short)(lParam & 0xFFFF); int yPos = transformY(getHwnd(), (int)(short)((lParam >> 16) & 0xFFFF)); handleMouseMoved(xPos, yPos, millis); return true; case WM_MOUSEWHEEL: int dwheel = (int)(short)((wParam >> 16) & 0xFFFF); handleMouseScrolled(dwheel, millis); return true; case WM_LBUTTONDOWN: handleMouseButton(0, 1, millis); return true; case WM_LBUTTONUP: handleMouseButton(0, 0, millis); return true; case WM_RBUTTONDOWN: handleMouseButton(1, 1, millis); return true; case WM_RBUTTONUP: handleMouseButton(1, 0, millis); return true; case WM_MBUTTONDOWN: handleMouseButton(2, 1, millis); return true; case WM_MBUTTONUP: handleMouseButton(2, 0, millis); return true; case WM_QUIT: close_requested = true; return true; case WM_SYSCOMMAND: switch ((int)wParam) { case SC_KEYMENU: case SC_MOUSEMENU: case SC_SCREENSAVE: case SC_MONITORPOWER: return true; case SC_CLOSE: close_requested = true; return true; default: break; } return false; case WM_PAINT: is_dirty = true; return false; default: return false; } } static WindowsDirectInput createDirectInput() throws LWJGLException { try { return new WindowsDirectInput8(getDllInstance()); } catch (LWJGLException e) { LWJGLUtil.log("Failed to create DirectInput 8 interface, falling back to DirectInput 3"); return new WindowsDirectInput3(getDllInstance()); } } public int getWidth() { return Display.getDisplayMode().getWidth(); } public int getHeight() { return Display.getDisplayMode().getHeight(); } }
469642fa842b269b793841e7d3f01763bdcc297e
ce6135be5ce53759251c20dd88c80aaa09d11816
/Android/Ex00_Project3/app/src/main/java/com/study/android/test2/Fragment3.java
ad5c71639c60b5b6b5b93f06fdc338317c6786a7
[]
no_license
LeeKeonHoo/kosmo41_LeeKeonHoo
b0882853b5c378076d5fe80b550ff77fd8033f29
571526febc124f2065f8ff47c09f04396476db78
refs/heads/master
2020-03-21T04:41:08.596557
2019-02-20T07:32:39
2019-02-20T07:32:39
138,122,535
0
0
null
null
null
null
UTF-8
Java
false
false
12,056
java
package com.study.android.test2; import android.app.Activity; import android.content.DialogInterface; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class Fragment3 extends Fragment { private static final String TAG = "lecture"; TextView textView6; EditText editText2; EditText editText3; EditText editText4; Button button5; Button button6; Button button7; SQLiteDatabase database; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment3,container,false); textView6 = rootView.findViewById(R.id.textView6); editText2 = rootView.findViewById(R.id.editText2); editText3 = rootView.findViewById(R.id.editText3); editText4 = rootView.findViewById(R.id.editText4); button5 = rootView.findViewById(R.id.button5); button5.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ AlertDialog.Builder alert_confirm = new AlertDialog.Builder(getContext()); alert_confirm.setMessage("3가지를 입력하셔야 등록됩니다.\n 등록하시겠습니까?").setCancelable(false).setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dataadd(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'No' return; } }); AlertDialog alert = alert_confirm.create(); alert.show(); } }); button6 = rootView.findViewById(R.id.button6); button6.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ AlertDialog.Builder alert_confirm = new AlertDialog.Builder(getContext()); alert_confirm.setMessage("제목만 입력하셔도 삭제됩니다.\n 정말 삭제하시겠습니까?").setCancelable(false).setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { datadelete(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'No' return; } }); AlertDialog alert = alert_confirm.create(); alert.show(); } }); button7 = rootView.findViewById(R.id.button7); button7.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ AlertDialog.Builder alert_confirm = new AlertDialog.Builder(getContext()); alert_confirm.setMessage("기존에 등록된 데이터를 불러옵니다.\n 불러오시겠습니까?").setCancelable(false).setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dataplus(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'No' return; } }); AlertDialog alert = alert_confirm.create(); alert.show(); } }); createMyDatabase(); createMyTable(); return rootView; } public void printInfo(String msg){ textView6.append(msg + "\n"); } private void createMyDatabase(){ try{ database = getActivity().openOrCreateDatabase("customer.sqlite", Activity.MODE_PRIVATE,null); printInfo("데이터베이스 만듬 : customer.sqlite"); }catch (Exception e){ e.printStackTrace(); } } private void createMyTable(){ String sql = "create table if not exists customer (name text,age integer, mobile text,star integer) "; printInfo("테이블 만듬 : customer"); try{ database.execSQL(sql); }catch (Exception e){ e.printStackTrace(); } } private void dataadd(){ String search1 = editText2.getText().toString(); String search2 = editText3.getText().toString(); String search3 = editText4.getText().toString(); String sql1 = "insert into customer " + "(name, age, mobile,star) values ('"+search1+"',"+search3+",'"+search2+"',0) "; try{ database.execSQL(sql1); printInfo("데이터 추가 : 1"); Toast.makeText(getActivity(), " 데이터를 추가했습니다 ", Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(getActivity(), " 데이터를 추가하지 못했습니다 ", Toast.LENGTH_SHORT).show(); } } private void datadelete(){ String search1 = editText3.getText().toString(); String sql1 = "delete from customer " + "where mobile = '"+search1+"' "; try{ database.execSQL(sql1); printInfo("데이터 추가 : 1"); Toast.makeText(getActivity(), search1 + " 를 삭제했습니다 ", Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(getActivity(), search1 + " 를 삭제하지 못했습니다 ", Toast.LENGTH_SHORT).show(); } } private void dataplus(){ String sql1 = "insert into customer " + "(name, age, mobile,star) values ('윤하',1,'오늘 헤어졌어요',0) "; String sql2 = "insert into customer " + "(name, age, mobile,star) values ('볼빨간 사춘기',2,'여행',0) "; String sql3 = "insert into customer " + "(name, age, mobile,star) values ('태연',3,'Rain',0) "; String sql4 = "insert into customer " + "(name, age, mobile,star) values ('아이유(IU)',4,'비밀의 화원',0) "; String sql5 = "insert into customer " + "(name, age, mobile,star) values ('트와이스(TWICE)',5,'Dance The Night Away',0) "; String sql6 = "insert into customer " + "(name, age, mobile,star) values ('샤넌',6,'눈물이 흘러',0) "; String sql7 = "insert into customer " + "(name, age, mobile,star) values ('마마무',7,'칠해줘',0) "; String sql8 = "insert into customer " + "(name, age, mobile,star) values ('헤이즈(Heize)',8,'비도 오고 그래서',0) "; String sql9 = "insert into customer " + "(name, age, mobile,star) values ('창모',9,'마에스트로(Maestro)',0) "; String sql10 = "insert into customer " + "(name, age, mobile,star) values ('DPR LIVE',10,'Martini Blue',0) "; String sql11 = "insert into customer " + "(name, age, mobile,star) values ('2NE1',11,'너 아님 안돼',0) "; String sql12 = "insert into customer " + "(name, age, mobile,star) values ('FT아일랜드',12,'사랑앓이',0) "; String sql13 = "insert into customer " + "(name, age, mobile,star) values ('박재범(Jay Park)',13,'All I Wanna Do',0) "; String sql14 = "insert into customer " + "(name, age, mobile,star) values ('딘(DEAN)',14,'D(Half Moon)',0) "; String sql15 = "insert into customer " + "(name, age, mobile,star) values ('로꼬(LOCO)',15,'감아',0) "; String sql16 = "insert into customer " + "(name, age, mobile,star) values ('신화',16,'Brand New',0) "; String sql17 = "insert into customer " + "(name, age, mobile,star) values ('레드벨벳(Red Velvet)',17,'Power Up',0) "; String sql18 = "insert into customer " + "(name, age, mobile,star) values ('워너원(Wanna One)',18,'에너제틱(Energetic)',0) "; String sql19 = "insert into customer " + "(name, age, mobile,star) values ('문문(MoonMoon)',19,'물감',0) "; String sql20 = "insert into customer " + "(name, age, mobile,star) values ('블락비(Block B)',20,'YESTERDAY',0) "; try{ database.execSQL(sql1); printInfo("데이터 추가 : 1"); database.execSQL(sql2); printInfo("데이터 추가 : 2"); database.execSQL(sql3); printInfo("데이터 추가 : 3"); database.execSQL(sql4); printInfo("데이터 추가 : 4"); database.execSQL(sql5); printInfo("데이터 추가 : 5"); database.execSQL(sql6); printInfo("데이터 추가 : 6"); database.execSQL(sql7); printInfo("데이터 추가 : 7"); database.execSQL(sql8); printInfo("데이터 추가 : 8"); database.execSQL(sql9); printInfo("데이터 추가 : 9"); database.execSQL(sql10); printInfo("데이터 추가 : 10"); database.execSQL(sql11); printInfo("데이터 추가 : 11"); database.execSQL(sql12); printInfo("데이터 추가 : 12"); database.execSQL(sql13); printInfo("데이터 추가 : 13"); database.execSQL(sql14); printInfo("데이터 추가 : 14"); database.execSQL(sql15); printInfo("데이터 추가 : 15"); database.execSQL(sql16); printInfo("데이터 추가 : 16"); database.execSQL(sql17); printInfo("데이터 추가 : 17"); database.execSQL(sql18); printInfo("데이터 추가 : 18"); database.execSQL(sql19); printInfo("데이터 추가 : 19"); database.execSQL(sql20); printInfo("데이터 추가 : 20"); Toast.makeText(getActivity(), "기존데이터를 불러왔습니다.", Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(getActivity(), "기존데이터를 불러오지 못했습니다.", Toast.LENGTH_SHORT).show(); } } }
da4ba1f23b34e42a603cfc51e0574cbe88a50cdd
08b4cadbb485684547d53bf8bc10becd78a47f1c
/src/net/magicraft/AutoRefill/AutoRefillPlugin.java
adb6aef67ccf4f8c3dc30fbe47e58e313590acde
[ "MIT" ]
permissive
LaGamma/AutoRefill
1c97c70b97cfd96707363d76073dbceb266c8bb2
f39f56e7196226df76453b7cce4b83850494f340
refs/heads/master
2022-12-25T15:39:18.930033
2020-10-10T06:31:31
2020-10-10T06:31:31
300,878,562
0
0
null
2020-10-04T11:17:31
2020-10-03T12:46:13
Java
UTF-8
Java
false
false
1,401
java
package net.magicraft.AutoRefill; import net.milkbowl.vault.permission.Permission; import java.util.logging.Logger; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; public class AutoRefillPlugin extends JavaPlugin { private static AutoRefillPlugin plugin = null; private PermissionsHandler pmh; private DataManager dm; private final static Logger LOGGER = Logger.getLogger(AutoRefillPlugin.class.getName()); public void onEnable() { plugin = this; this.dm = new DataManager(this); getCommand("autorefill").setExecutor(new AutoRefillCmd(this)); getServer().getPluginManager().registerEvents(new AutoRefillListener(this.dm), (Plugin)this); if (getServer().getPluginManager().isPluginEnabled("Vault")) { RegisteredServiceProvider<Permission> provp = getServer().getServicesManager().getRegistration(Permission.class); if (provp != null) { Permission perms = (Permission) provp.getProvider(); if (perms != null) { this.pmh = new PermissionsHandler(perms); LOGGER.info("Hooked into Vault's permissions!"); } } } } public void onDisable() { this.dm.cleanUp(); } public DataManager getDataManager() { return this.dm; } public PermissionsHandler getPermissionsHandler() { return this.pmh; } public static AutoRefillPlugin getPlugin() { return plugin; } }
0fa0e7a6d2a9f5989cbbc968a9f3725de2fc3b80
dcb65e710bc606cebc3962a36d46c2918558d5a1
/src/boardgame/Board.java
64cf8daa38db9326f70dd9560492d43d5b11f60b
[]
no_license
AlefGoncalves/chess-system-java
d7aece45a936adc1b771fa6c789139321828c34e
2a1d91f3618b7fa3a4307924fd906a39db1db260
refs/heads/master
2023-02-04T23:38:39.700815
2020-12-29T15:11:58
2020-12-29T15:11:58
322,359,057
0
0
null
null
null
null
UTF-8
Java
false
false
1,866
java
package boardgame; public class Board { private int rows, columns; private Piece[][] pieces; public Board(int rows, int columns) { if(rows < 1 || columns < 1) { throw new BoardException("Error creating board: there must be at least 1 row and 1 column"); } this.rows = rows; this.columns = columns; pieces = new Piece[rows][columns]; } public int getRows() { return rows; } public int getColumns() { return columns; } public Piece piece(int row, int column) { if(!positionExists(row, column)) { throw new BoardException("Position not on the board"); } return pieces[row][column]; } public Piece piece(Position position) { if(!positionExists(position)) { throw new BoardException("Position not on the board"); } return pieces[position.getRow()][position.getColumn()]; } public void placePiece(Piece piece, Position position) { if(thereIsAPiece(position)) { throw new BoardException("There is already a piece in position "+ position); } pieces[position.getRow()][position.getColumn()] = piece; piece.position = position; } public Piece removePiece(Position position) { if(!positionExists(position)) { throw new BoardException("Position not on the board"); } if(piece(position) == null) { return null; } Piece aux = piece(position); aux.position = null; pieces[position.getRow()][position.getColumn()] = null; return aux; } private boolean positionExists(int row, int column) { return row >= 0 && row < rows && column >= 0 && column < columns; } public boolean positionExists(Position position) { return positionExists(position.getRow(), position.getColumn()); } public boolean thereIsAPiece(Position position) { if(!positionExists(position)) { throw new BoardException("Position not on the board"); } return piece(position) != null; } }
5777333481da6ac810ccf50b3c2afce06c4fabeb
8ad9e61b602e4fa12fc193ad24ab3483f50b7598
/IBM Proactive Technology Online/ProtonJ2SE/src/com/ibm/hrl/proton/metadata/epa/StatefulEventProcesingAgentType.java
64cafd8d293474cf801fee81c300eec83a38f0bf
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mindis/Proton
91b54d6a9295d7f42c6fe4b3c18a8131d351ac0a
c1f2bd31194e0519dcc85e1f4626e8ac76b403a6
refs/heads/master
2020-05-29T12:22:39.582754
2015-04-28T14:16:59
2015-04-28T14:16:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,307
java
/******************************************************************************* * Copyright 2014 IBM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.ibm.hrl.proton.metadata.epa; import java.util.Collection; import java.util.List; import java.util.UUID; import com.ibm.hrl.proton.metadata.computedVariable.IComputedVariableType; import com.ibm.hrl.proton.metadata.context.interfaces.IContextType; import com.ibm.hrl.proton.metadata.context.interfaces.ISegmentationContextType; import com.ibm.hrl.proton.metadata.epa.enums.CardinalityPolicyEnum; import com.ibm.hrl.proton.metadata.epa.enums.EPATypeEnum; import com.ibm.hrl.proton.metadata.epa.enums.EvaluationPolicyEnum; import com.ibm.hrl.proton.metadata.epa.interfaces.IDerivationSchema; import com.ibm.hrl.proton.metadata.epa.interfaces.IFilteringSchema; import com.ibm.hrl.proton.metadata.epa.interfaces.IMatchingSchema; import com.ibm.hrl.proton.metadata.event.IEventType; import com.ibm.hrl.proton.runtime.epa.interfaces.IExpression; public class StatefulEventProcesingAgentType extends EventProcessingAgentType { /** * */ private static final long serialVersionUID = 1L; public IMatchingSchema matchingSchema; protected EvaluationPolicyEnum evaluation; protected CardinalityPolicyEnum cardinality; protected IExpression parsedAssertion; protected String assertion; protected Collection<ISegmentationContextType> epaSegmentation; protected IComputedVariableType agentContextInformation; public StatefulEventProcesingAgentType(UUID id, String name, EPATypeEnum epaType, List<IEventType> inputEvents, IMatchingSchema matchingSchema, IFilteringSchema filteringSchema, IDerivationSchema derivationSchema, IContextType context, boolean isFair){ super(id, name, epaType, inputEvents,filteringSchema, derivationSchema, context,isFair); this.matchingSchema = matchingSchema; } /** * The order of input and output events in the input and derivation lists matter - should be as operands order * @param id * @param name * @param epaType * @param inputEvents * @param derivedEvents * @param matchingSchema * @param filteringSchema * @param derivationSchema * @param context * @param cardinality * @param reportParticipants * @param isFair */ public StatefulEventProcesingAgentType( UUID id, String name, EPATypeEnum epaType, List<IEventType> inputEvents, IMatchingSchema matchingSchema, IFilteringSchema filteringSchema, IDerivationSchema derivationSchema, IContextType context, CardinalityPolicyEnum cardinality, boolean isFair,String assertion, IExpression parsedExpression,EvaluationPolicyEnum evaluationPolicy, Collection<ISegmentationContextType> epaSegmentation) { super(id, name, epaType, inputEvents, filteringSchema, derivationSchema, context, isFair); this.matchingSchema = matchingSchema; this.cardinality = cardinality; this.parsedAssertion = parsedExpression; this.evaluation = evaluationPolicy; this.epaSegmentation = epaSegmentation; // TODO Auto-generated constructor stub } public void setEpaSegmentation(Collection<ISegmentationContextType> epaSegmentation) { this.epaSegmentation = epaSegmentation; } public EvaluationPolicyEnum getEvaluation() { return evaluation; } public CardinalityPolicyEnum getCardinality() { return cardinality; } public IExpression getParsedAssertion() { return parsedAssertion; } public IMatchingSchema getMatchingSchema() { return matchingSchema; } public void setMatchingSchema(IMatchingSchema matchingSchema) { this.matchingSchema = matchingSchema; } public void setEvaluation(EvaluationPolicyEnum evaluation) { this.evaluation = evaluation; } public void setCardinality(CardinalityPolicyEnum cardinality) { this.cardinality = cardinality; } public void setParsedAssertion(IExpression parsedAssertion) { this.parsedAssertion = parsedAssertion; } public void setAssertion(String assertion) { this.assertion = assertion; } public IComputedVariableType getAgentContextInformation() { return agentContextInformation; } public void setAgentContextInformation( IComputedVariableType agentContextInformation) { this.agentContextInformation = agentContextInformation; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "EPA '"+getName()+"' of type: "+getType(); } @Override public Collection<ISegmentationContextType> getLocalSegmentation() { return epaSegmentation; } }
9173fe25ee0834c30570ea90350c98bdaee7b700
59edba456caf55f7192f426f86400c869151fba5
/src/main/java/pl/sklep/zadanie2/controller/ShopController.java
b7291762836ce53ddcdf65058220cca47dcff95a
[]
no_license
rafi921/Shop
c6d36c6891a85e7dc35af1982a9d6823cb4a1ada
0896f0ce7de285df2c2cad2f7497a77962ab028e
refs/heads/master
2023-02-25T15:03:09.801914
2021-01-25T17:08:23
2021-01-25T17:08:23
332,821,169
0
0
null
null
null
null
UTF-8
Java
false
false
931
java
package pl.sklep.zadanie2.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Profile; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Controller; import pl.sklep.zadanie2.model.Product; import pl.sklep.zadanie2.service.ShopService; import java.util.List; @Controller @Profile({"Pro", "Plus", "Start"}) public class ShopController { private ShopService shopService; @Autowired public ShopController(ShopService shopService) { this.shopService = shopService; } @EventListener(ApplicationReadyEvent.class) public void runApplication() { shopService.addProduct(); List<Product> list = shopService.getList(); list.forEach(System.out::println); shopService.calculateBill(); } }
eaa3db87e2c0dc4ebb0850d22c6e742e4cc219af
469f79093305089c1da06dd0deddf8b4953f1f71
/42challenge/src/com/clintlooney/Main.java
fda3a9c8ee924c1d1b7e624ab2aa47f00d1d29a6
[]
no_license
clprivate/java-udemy
7f89ac770addbbdff90cd8e3847cc1aec57f1113
f15fed734c3c4b75b23074715f3cbacaf33d3612
refs/heads/master
2020-03-18T10:17:27.438109
2018-08-30T16:21:14
2018-08-30T16:21:14
134,605,431
0
0
null
null
null
null
UTF-8
Java
false
false
1,025
java
package com.clintlooney; public class Main { public static void main(String[] args) { // for (int i = 8; i >= 2; i--) { // System.out.println("$10K at " + i + "% interest = $" + String.format("%.2f",calculateInterest(10000,(double) i))); // } int primeCount = 0; for (int i = 10; i <= 50; i++) { if(isPrime(i)) { primeCount++; System.out.println(i + " is prime."); System.out.println("Prime counter: " + primeCount); if (primeCount == 3) { break; } } } } public static double calculateInterest(double amount, double interestRate) { return amount * (interestRate /100); } public static boolean isPrime(int n) { if (n == 1) { return false; } for (int i = 2; i <= n/2; i++) { if(n % 1 ==0) { return false; } } return true; } }
10aff1958e2ebda7b54f88c5793f68e78413c520
e21d17cdcd99c5d53300a7295ebb41e0f876bbcb
/22_Chapters_Edition/src/main/java/com/lypgod/test/tij4/practices/Ch10_InnerClasses/Practice4/Sequence.java
0924c087c88c558e113c03c4c1d4d5d82ade470a
[]
no_license
lypgod/Thinking_In_Java_4th_Edition
dc42a377de28ae51de2c4000a860cd3bc93d0620
5dae477f1a44b15b9aa4944ecae2175bd5d8c10e
refs/heads/master
2020-04-05T17:39:55.720961
2018-11-11T12:07:56
2018-11-11T12:08:26
157,070,646
0
0
null
null
null
null
UTF-8
Java
false
false
1,357
java
package com.lypgod.test.tij4.practices.Ch10_InnerClasses.Practice4;//: innerclasses/Sequence.java // Holds a sequence of Objects. interface Selector { boolean end(); Object current(); void next(); } public class Sequence { private Object[] items; private int next = 0; public Sequence(int size) { items = new Object[size]; } public void add(Object x) { if (next < items.length) items[next++] = x; } private class SequenceSelector implements Selector { private int i = 0; public boolean end() { return i == items.length; } public Object current() { return items[i]; } public void next() { if (i < items.length) i++; } public Sequence getSequence() { return Sequence.this; } } public Selector selector() { return new SequenceSelector(); } public static void main(String[] args) { Sequence sequence = new Sequence(10); for (int i = 0; i < 10; i++) sequence.add(Integer.toString(i)); Selector selector = sequence.selector(); while (!selector.end()) { System.out.print(selector.current() + " "); selector.next(); } } } /* Output: 0 1 2 3 4 5 6 7 8 9 *///:~
e0f809e9248fa0fd783e59b2349d6ecccdad5f45
7c671f79781238d71653023fcc8ed629ee3d29f7
/Android/EKutuphane/app/build/generated/source/buildConfig/androidTest/debug/com/akarakaya/ekutuphane/test/BuildConfig.java
b6a0c4f3f113bd3e9f62c48f962653694e5546ed
[]
no_license
akarakaya/DigitalLibrary
e4d892fbfa8414d6a14b0d1c1c20528b1d4e26c0
0d012a12d8b8b6305568e7e898dab874fd53b886
refs/heads/master
2020-07-15T14:03:33.759051
2016-08-24T09:15:22
2016-08-24T09:15:22
66,210,548
1
0
null
null
null
null
UTF-8
Java
false
false
465
java
/** * Automatically generated file. DO NOT MODIFY */ package com.akarakaya.ekutuphane.test; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.akarakaya.ekutuphane.test"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = "1.0"; }
f48468fdd30100b96983fde26790e7571ad3db80
939dd20ead0a8b4b7ae1e1a331888c2afb4c0327
/src/main/java/com/uca/capas/ServletInitializer.java
8765be4a6b36cd12e7ad0dce0e752370e219e84c
[]
no_license
JoseDFS/Labo4_PNCapas
0a4ed33480304a7574ed89cae93602b97ca64110
21f6d298705541bb1e31bbe95ddfeec6ac6214f3
refs/heads/master
2022-07-10T14:44:28.366484
2020-05-12T02:32:04
2020-05-12T02:32:04
263,212,255
0
0
null
null
null
null
UTF-8
Java
false
false
413
java
package com.uca.capas; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(TareaLabo4NCapasApplication.class); } }
376c77de074980159f17c70c06ec433db03f8b73
77ef13801192f83882d15093069cb0644e98d2a2
/src/main/java/com/malkierian/plasmacraft/common/blocks/BlockGlowCloth.java
5410fac4895d71a01f03f7a13fe64d29cd0f9e77
[]
no_license
Mrkwtkr/PlasmaCraft
3c43558e1e58ea9f9767bb6a67ff4ad0a5ed351c
3826508ed47b45875fa940efbd27806e39985e4d
refs/heads/master
2020-12-27T15:21:35.229948
2014-10-03T06:03:12
2014-10-03T06:03:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,142
java
package com.malkierian.plasmacraft.common.blocks; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import com.malkierian.plasmacraft.common.PlasmaCraft; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockGlowCloth extends Block { private IIcon[] icons; public BlockGlowCloth() { super(Material.cloth); setLightLevel(1F); setStepSound(Block.soundTypeCloth); setCreativeTab(PlasmaCraft.plasmaTab); setHardness(0.8F); } // public void addCreativeItems(ArrayList itemList) // { // for(int i = 0; i < 8; i++) // { // itemList.add(new ItemStack(this, 1, i)); // } // } @Override public int damageDropped(int i) { return i; } @Override public IIcon getIcon(int i, int j) { return icons[j]; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item par1, CreativeTabs tab, List subItems) { for (int ix = 0; ix < 8; ix++) { subItems.add(new ItemStack(this, 1, ix)); } } @Override public int quantityDropped(Random random) { return 1; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister) { this.icons = new IIcon[] { par1IconRegister.registerIcon("plasmacraft:glowCloth_acid"), par1IconRegister.registerIcon("plasmacraft:glowCloth_radionite"), par1IconRegister.registerIcon("plasmacraft:glowCloth_netherflow"), par1IconRegister.registerIcon("plasmacraft:glowCloth_neptunium"), par1IconRegister.registerIcon("plasmacraft:glowCloth_uranium"), par1IconRegister.registerIcon("plasmacraft:glowCloth_plutonium"), par1IconRegister.registerIcon("plasmacraft:glowCloth_cryonite"), par1IconRegister.registerIcon("plasmacraft:glowCloth_obsidium") }; } }
941f74150c54e7e2a89f57eaefcebf66087fd981
1a22463a70e5592bcc7e09b940dfa9605904520b
/src/hashtable/valid_sudoku_36/Solution1.java
5f391de6485c0d72dae575f8eabcec9390bd56a6
[]
no_license
toni-stepanov/leetcode
efecd3cdac1281d00b12599c21c0a7b88ae50012
ae3fe75a5ce0017e72dd0ced81cb7f67745cbc31
refs/heads/master
2020-03-29T11:33:28.873517
2020-02-16T12:56:02
2020-02-16T12:56:02
149,809,038
0
0
null
null
null
null
UTF-8
Java
false
false
2,258
java
package hashtable.valid_sudoku_36; import java.util.HashSet; import java.util.Set; /* 36. Valid Sudoku https://leetcode.com/problems/valid-sudoku/#/description Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. */ public class Solution1 { private final int innerSize = 2; private final int outerSize = 4; private void inputValidation(char[][] board) { if (board == null) throw new IllegalArgumentException("board should be provided"); if (board.length != outerSize || board[0] == null || board[0].length != outerSize) { throw new IllegalArgumentException("board size is not correct"); } } private boolean isCellDataValid(char item) { if (item == '.') return true; if (Character.isDigit(item)) { int itemValue = item - '0'; return itemValue > 0 && itemValue <= outerSize; } return false; } private boolean isPortionValid(char item, Set<Character> set) { if (!isCellDataValid(item)) throw new RuntimeException(String.format("%1$c is not valid cell data ", item)); if (item == '.') return true; return set.add(item); } // Great solutions // https://discuss.leetcode.com/topic/9748/shared-my-concise-java-code // https://discuss.leetcode.com/topic/5803/sharing-my-easy-understand-java-solution-using-set public boolean isValidSudoku(char[][] board) { inputValidation(board); for (int i=0; i<outerSize; i++) { Set<Character> rowItems = new HashSet<>(); Set<Character> colItems = new HashSet<>(); Set<Character> squareItems = new HashSet<>(); for (int j=0; j<outerSize; j++) { if (!isPortionValid(board[i][j], rowItems)) return false; if (!isPortionValid(board[j][i], colItems)) return false; int rowStart = innerSize*(i/innerSize); int colStart = innerSize*(i%innerSize); if (!isPortionValid(board[rowStart + j/innerSize][colStart+j%innerSize], squareItems)) return false; } } return true; } }
99af420878e12827b0c3a2908a9adebf732b3b45
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-13303-9-4-NSGA_II-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/doc/XWikiDocument_ESTest.java
eab306c4886417ce4e14ed16976bdf4d868db421
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
/* * This file was automatically generated by EvoSuite * Wed Apr 01 16:28:00 UTC 2020 */ package com.xpn.xwiki.doc; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class XWikiDocument_ESTest extends XWikiDocument_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
7ae319bdf7db65099b88539a8a4020821a98b5c0
972ba7db7018f146f2a426ce6bf712b848fde2f1
/src/main/querydsl/kr/co/mash_up/nine_tique/domain/QSellerProduct_Id.java
0312325c149adb8038988a128aaec84b79e8654d
[]
no_license
waffle-iron/9tique-backend
63c73baa7bb2c581ae734b651863bc99ecd4c949
c865eb95e1137810710607d2586347e56452e2cf
refs/heads/develop
2021-01-19T08:11:20.025600
2017-04-08T04:48:41
2017-04-08T04:48:41
87,608,778
0
0
null
2017-04-08T04:48:40
2017-04-08T04:48:40
null
UTF-8
Java
false
false
1,120
java
package kr.co.mash_up.nine_tique.domain; import static com.mysema.query.types.PathMetadataFactory.*; import com.mysema.query.types.path.*; import com.mysema.query.types.PathMetadata; import javax.annotation.Generated; import com.mysema.query.types.Path; /** * QSellerProduct_Id is a Querydsl query type for Id */ @Generated("com.mysema.query.codegen.EmbeddableSerializer") public class QSellerProduct_Id extends BeanPath<SellerProduct.Id> { private static final long serialVersionUID = 1704331980L; public static final QSellerProduct_Id id = new QSellerProduct_Id("id"); public final NumberPath<Long> productId = createNumber("productId", Long.class); public final NumberPath<Long> sellerId = createNumber("sellerId", Long.class); public QSellerProduct_Id(String variable) { super(SellerProduct.Id.class, forVariable(variable)); } public QSellerProduct_Id(Path<? extends SellerProduct.Id> path) { super(path.getType(), path.getMetadata()); } public QSellerProduct_Id(PathMetadata<?> metadata) { super(SellerProduct.Id.class, metadata); } }
69ccd98cc435a3d49b64bf6aa9782040e677a8f8
f57fc1543d1577640160d83ed93500ccda67b6f9
/NLUFrozenFood/src/main/java/com/nlufrozenfood/service/UserService.java
dda6527059995a6e5e9370d02754d2474cba5464
[]
no_license
17130225Hoangthinh/WebBanThit
4692939a77ed7bfe6f55d7ff3e050ef8999c2ff8
d848fea0af020cc74ee3220dd0c1b14266a653e1
refs/heads/master
2023-06-24T08:12:33.685554
2021-07-24T08:04:44
2021-07-24T08:04:44
389,032,611
0
0
null
null
null
null
UTF-8
Java
false
false
1,002
java
package com.nlufrozenfood.service; import java.util.Set; import com.nlufrozenfood.domain.User; import com.nlufrozenfood.domain.UserBilling; import com.nlufrozenfood.domain.UserPayment; import com.nlufrozenfood.domain.UserShipping; import com.nlufrozenfood.domain.security.PasswordResetToken; import com.nlufrozenfood.domain.security.UserRole; public interface UserService { PasswordResetToken getPasswordResetToken(final String token); void createPasswordResetTokenForUser(final User user, final String token); User findByUsername(String username); User findByEmail (String email); User findById(Long id); User createUser(User user, Set<UserRole> userRoles) throws Exception; User save(User user); void updateUserBilling(UserBilling userBilling, UserPayment userPayment, User user); void updateUserShipping(UserShipping userShipping, User user); void setUserDefaultPayment(Long userPaymentId, User user); void setUserDefaultShipping(Long userShippingId, User user); }
8ec4deb708984132382369bdce10ded723d50541
e09352fcebc136ebb989275f2e98af7e60049b99
/src/main/java/com/andersonmarques/debts_api/security/JwtLoginFilter.java
1666a8f61946f581f584e659340d9bc368ca4e43
[]
no_license
AndersonMarquess/Debts-management-api
a0949ccedf4013958f74ce1f4900dc0f90ba350f
d12fe2142478c2c78144848cac46a47d95ca2da6
refs/heads/master
2020-08-08T03:57:56.616377
2020-02-08T18:55:38
2020-02-08T18:55:38
213,704,204
0
0
null
null
null
null
UTF-8
Java
false
false
1,931
java
package com.andersonmarques.debts_api.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.andersonmarques.debts_api.models.AccountCredentials; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter { private static final Logger logger = LogManager.getLogger("JwtLoginFilter"); private JwtService jwtService; public JwtLoginFilter(AuthenticationManager authManager, JwtService JwtService) { super("/login"); this.jwtService = JwtService; setAuthenticationManager(authManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { AccountCredentials credentials = new ObjectMapper().readValue(request.getInputStream(), AccountCredentials.class); logger.info("Autenticando usuário: {}", credentials.getEmail()); return getAuthenticationManager().authenticate(credentials.generateAuthenticationToken()); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { logger.info("Usuário: {} autenticado com sucesso", authResult.getName()); jwtService.addAuthenticationToResponse(response, authResult.getName()); } }
9fbc11363e77d57cbd4f8fb4d7791ee55bde78a3
9251342abf31799bb9a8474f61293733723e3366
/screen-master/src/main/java/com/betel/estatemgmt/business/web/task/service/TaskService.java
c312fc316b9240b3e2cc1244796e73c8bcb52e8b
[]
no_license
zhuxiefei/screen-master
2dcb9a7e8e6be415facd0f7d82efcc20cb3b03cf
849025872ee7e5f59c98e4772b02c5cc9b8942ad
refs/heads/master
2020-03-27T17:46:10.713354
2018-08-31T09:50:22
2018-08-31T09:50:22
146,873,193
1
0
null
null
null
null
UTF-8
Java
false
false
2,074
java
package com.betel.estatemgmt.business.web.task.service; import com.betel.estatemgmt.business.propertyapp.task.model.AppTaskCount; import com.betel.estatemgmt.business.web.task.model.*; import com.betel.estatemgmt.common.model.work.TaskType; import com.betel.estatemgmt.utils.pagination.model.Paging; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * <p> * 业务实现接口 * </p> * ClassName: TaskService <br/> * Author: Xia.yx <br/> * Date: 2017/12/21 8:56 <br/> * Version: 1.0 <br/> */ public interface TaskService { String addTaskType(AddTaskTypeReq typeReq); String updateTaskType(UpdateTaskTypeReq typeReq); void deleteTaskType(DeleteTaskTypeReq typeReq); List<TaskType> findAllTaskTypes(Paging<TaskType> paging,String estateId); TaskType findTaskType(FindTaskTypeReq typeReq); /** * 添加任务 * @param taskReq * @param userId * @param type 1为web添加 2为app添加 * @return */ String addTask(AddTaskReq taskReq, String userId, Integer type, HttpServletRequest request) throws Exception; List<FindAllTasksResp> findAllTasks(FindAllTasksReq tasksReq , Paging<FindAllTasksResp> paging ,HttpServletRequest request) throws Exception; FindTaskResp findTask(FindTaskReq taskReq); /** * * @param taskReq * @param userId * @param type 1为web添加 2为app添加 * @return */ String updateTask(UpdateTaskReq taskReq, String userId, Integer type,HttpServletRequest request) throws Exception; void deleteTask(DeleteTaskReq deleteTaskReq, String userId) throws Exception; List<TaskType> findTaskTyps(String estateId); List<FindAllRecordResp> findAllRecords(Paging<FindAllRecordResp> paging, FindAllRecordReq recordReq,HttpServletRequest request) throws Exception; TaskCountResp findTaskCount(TaskCountReq taskCountReq) throws Exception; AppTaskCount appFindTaskCount(TaskCountReq taskCountReq) throws Exception; }
00b8ccc7ccea74a83e5de27e8ec6c4a271012d65
9ce02cf25b3c0dc7252e501a30e03a4e7aadc83a
/src/main/java/com/bm/insurance/cloud/sale/model/SaleRoleExample.java
1ae5a67dbb6c4ab89a9e729d9ad5b0a530670e85
[]
no_license
IaHehe/base-auth-framwork
9154cd69fddaae2b7e56df7aad753b88bb931d13
725b53d84f41d57a738ce34d4a3199a16906542e
refs/heads/master
2021-06-14T07:40:51.158026
2017-05-26T08:35:19
2017-05-26T08:35:19
107,238,503
0
1
null
2017-10-17T08:16:03
2017-10-17T08:16:02
null
UTF-8
Java
false
false
20,901
java
package com.bm.insurance.cloud.sale.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SaleRoleExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public SaleRoleExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andRoleNameIsNull() { addCriterion("role_name is null"); return (Criteria) this; } public Criteria andRoleNameIsNotNull() { addCriterion("role_name is not null"); return (Criteria) this; } public Criteria andRoleNameEqualTo(String value) { addCriterion("role_name =", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotEqualTo(String value) { addCriterion("role_name <>", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameGreaterThan(String value) { addCriterion("role_name >", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameGreaterThanOrEqualTo(String value) { addCriterion("role_name >=", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLessThan(String value) { addCriterion("role_name <", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLessThanOrEqualTo(String value) { addCriterion("role_name <=", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLike(String value) { addCriterion("role_name like", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotLike(String value) { addCriterion("role_name not like", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameIn(List<String> values) { addCriterion("role_name in", values, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotIn(List<String> values) { addCriterion("role_name not in", values, "roleName"); return (Criteria) this; } public Criteria andRoleNameBetween(String value1, String value2) { addCriterion("role_name between", value1, value2, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotBetween(String value1, String value2) { addCriterion("role_name not between", value1, value2, "roleName"); return (Criteria) this; } public Criteria andRoleCodeIsNull() { addCriterion("role_code is null"); return (Criteria) this; } public Criteria andRoleCodeIsNotNull() { addCriterion("role_code is not null"); return (Criteria) this; } public Criteria andRoleCodeEqualTo(String value) { addCriterion("role_code =", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeNotEqualTo(String value) { addCriterion("role_code <>", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeGreaterThan(String value) { addCriterion("role_code >", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeGreaterThanOrEqualTo(String value) { addCriterion("role_code >=", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeLessThan(String value) { addCriterion("role_code <", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeLessThanOrEqualTo(String value) { addCriterion("role_code <=", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeLike(String value) { addCriterion("role_code like", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeNotLike(String value) { addCriterion("role_code not like", value, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeIn(List<String> values) { addCriterion("role_code in", values, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeNotIn(List<String> values) { addCriterion("role_code not in", values, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeBetween(String value1, String value2) { addCriterion("role_code between", value1, value2, "roleCode"); return (Criteria) this; } public Criteria andRoleCodeNotBetween(String value1, String value2) { addCriterion("role_code not between", value1, value2, "roleCode"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
988aaece23df154f86d38cc2869ba38099a50c91
eff51af628af059cbb5be0c8397ea067ba2913c4
/tunnel-core/src/main/java/dll/struct/hw/META_RECT_S.java
262108c30f2182d7c06392a4c2a2f9538b060d01
[ "Apache-2.0" ]
permissive
jjzhang166/tunnel
e4ce8f39dcdd9188eba35b31147d3dcd5d1d11c6
fce57e1c3daa74ca4946b60e1b6aeae8a05a6933
refs/heads/master
2022-01-21T20:42:49.970616
2019-01-04T01:38:19
2019-01-04T01:38:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,772
java
package dll.struct; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * <i>native declaration : D:\HWPuSDK.h</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class META_RECT_S extends Structure { /** \u77e9\u5f62\u5de6\u4e0a\u9876\u70b9\u7684x\u5750\u6807 */ public short usX; /** \u77e9\u5f62\u5de6\u4e0a\u9876\u70b9\u7684y\u5750\u6807 */ public short usY; /** \u77e9\u5f62\u5bbd */ public short usWidth; /** \u77e9\u5f62\u9ad8 */ public short usHeight; public META_RECT_S() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("usX", "usY", "usWidth", "usHeight"); } /** * @param usX \u77e9\u5f62\u5de6\u4e0a\u9876\u70b9\u7684x\u5750\u6807<br> * @param usY \u77e9\u5f62\u5de6\u4e0a\u9876\u70b9\u7684y\u5750\u6807<br> * @param usWidth \u77e9\u5f62\u5bbd<br> * @param usHeight \u77e9\u5f62\u9ad8 */ public META_RECT_S(short usX, short usY, short usWidth, short usHeight) { super(); this.usX = usX; this.usY = usY; this.usWidth = usWidth; this.usHeight = usHeight; } public META_RECT_S(Pointer peer) { super(peer); } public static class ByReference extends META_RECT_S implements Structure.ByReference { }; public static class ByValue extends META_RECT_S implements Structure.ByValue { }; }
4ad6fd182f957680e29500a1a07d3ad119a08635
f7693e8323843a47db7060dfe7c705245a72fb4f
/src/wtlcompiler/IR/IRBase/IRPrinter.java
9ba2f3163b35eab129a5cc853cce2eb8cf3f8e61
[]
no_license
sjtuwtl/compiler
070beb1014bb50141d4cbaf8623b663c3514e563
3df02f905bf833203b7fe0fac09b0fdd45356c49
refs/heads/master
2020-03-12T22:14:16.666140
2018-06-06T09:33:49
2018-06-06T09:33:49
130,843,643
0
0
null
null
null
null
UTF-8
Java
false
false
2,570
java
package wtlcompiler.IR.IRBase; import wtlcompiler.IR.Function; import wtlcompiler.IR.IRInstruction; import wtlcompiler.IR.IRType.Class; import wtlcompiler.IR.Label; import wtlcompiler.utility.Name; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.List; public class IRPrinter { private IRInstruction entry; private IRInstruction initializeEntry; private FileOutputStream outputStream; private List<Class> typeList; private DataSection dataSection; public IRPrinter(IRInstruction entry, IRInstruction initializeEntry, FileOutputStream outputStream, List<Class> typeList, DataSection dataSection) { this.entry = entry; this.initializeEntry = initializeEntry; this.outputStream = outputStream; this.typeList = typeList; this.dataSection = dataSection; } public void printIR() { IRInstruction cur = entry; PrintStream printStream = new PrintStream(outputStream); printStream.println("__________________________________________"); printStream.println("===================TEXT==================="); printStream.println(""); while(cur != null) { if(cur instanceof Label) { printStream.println(""); printStream.println(" " + cur.toString()); } else if(cur instanceof Function) { printStream.println(""); printStream.println(cur.toString()); if (((Function) cur).getName() == Name.getName("main")) { IRInstruction tmp = initializeEntry; while (tmp != null) { printStream.println(" " + tmp.toString()); tmp = tmp.getNext(); } } } else printStream.println(" " + cur.toString()); cur = cur.getNext(); } printStream.println("\n"); printStream.println("__________________________________________"); printStream.println("===================TYPE==================="); for(Class item : typeList) printStream.println(item.toFullInfoString()); printStream.println("\n"); printStream.println("__________________________________________"); printStream.println("===================DATA==================="); for(DataSection.DataPiece item : dataSection.getDataPieces()) printStream.println(item.toString()); } }
7db663881b0f25cf5188ada6717c697815da947c
2b7b53995d254cc95ff38de30406dda0116077d1
/src/main/java/com/design/demo/utils/HttpUtil.java
33653616cafedb1ee95d6649b43dc5ee8c5f7a0f
[]
no_license
yedongWUXI/study
c9b4543cdab8fa316cda0b5cf873af92116fa1c1
7ba8a3a60a292a727637f2e4cecf772b5ad2f5ab
refs/heads/master
2022-07-07T05:09:49.826253
2021-06-04T02:01:31
2021-06-04T02:01:31
134,435,894
1
0
null
2022-06-29T19:43:29
2018-05-22T15:27:45
JavaScript
UTF-8
Java
false
false
16,689
java
package com.design.demo.utils; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPatch; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpUtil { private static PoolingHttpClientConnectionManager connMgr; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 7000; private static Logger logger = org.slf4j.LoggerFactory.getLogger(HttpUtil.class); static { // 设置连接池 connMgr = new PoolingHttpClientConnectionManager(); // 设置连接池大小 connMgr.setMaxTotal(100); connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); RequestConfig.Builder configBuilder = RequestConfig.custom(); // 设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); // 设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); // 设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); // 在提交请求之前 测试连接是否可用 configBuilder.setStaleConnectionCheckEnabled(true); requestConfig = configBuilder.build(); } /** * 发送 GET 请求(HTTP),K-V形式 * * @param url * @param params * @return */ public static String doGet(String url, Header[] headers, Map<String, Object> params) { String apiUrl = url; StringBuffer param = new StringBuffer(); int i = 0; for (String key : params.keySet()) { if (i == 0) param.append("?"); else param.append("&"); param.append(key).append("=").append(params.get(key)); i++; } apiUrl += param; String result = null; HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(apiUrl); httpGet.setHeaders(headers); HttpResponse response = httpclient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("执行状态码 : " + statusCode); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); result = IOUtils.toString(instream, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } return result; } /** * 发送 POST 请求(HTTP),不带输入数据 * * @param apiUrl * @return */ public static String doPost(String apiUrl) { return doPost(apiUrl, new HashMap<String, Object>()); } /** * 发送 POST 请求(HTTP),K-V形式 * * @param apiUrl API接口URL * @param params 参数map * @return */ public static String doPost(String apiUrl, Map<String, Object> params) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; try { httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList(params.size()); for (Map.Entry<String, Object> entry : params.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry .getValue().toString()); pairList.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); response = httpClient.execute(httpPost); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 发送 POST 请求(HTTP),JSON形式 * * @param apiUrl * @param json json对象 * @return */ public static String doPost(String apiUrl, Object json) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 发送 POST 请求(HTTP),JSON形式 * * @param apiUrl * @param json json对象 * @return */ public static String doPost(String apiUrl, Header[] headers, Object json) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); httpPost.setHeaders(headers); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage() + ":" + apiUrl); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 发送 PATCH 请求(HTTP),JSON形式 * * @param apiUrl * @param json json对象 * @return */ public static String doPatch(String apiUrl, Header[] headers, Object json) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPatch httpPatch = new HttpPatch(apiUrl); CloseableHttpResponse response = null; try { httpPatch.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPatch.setEntity(stringEntity); httpPatch.setHeaders(headers); response = httpClient.execute(httpPatch); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage() + ":" + apiUrl); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } public static Header[] getHttpHeader(HttpSession session) { String tokenId = (String) session.getAttribute("TokenId"); Header[] headers = {new BasicHeader("clientId", "MYJF_WKADMIN"), new BasicHeader("clientTime", String.valueOf(System.currentTimeMillis())), new BasicHeader("token", tokenId) }; return headers; } public static String doHttpRequest(HttpSession session, String URL, RequestMethod method, Object data) { Header[] heads = getHttpHeader(session); if (method == RequestMethod.POST) { return doPost(URL, heads, data); } else if (method == RequestMethod.PATCH) { return doPatch(URL, heads, data); } else { return doGet(URL, heads, (Map<String, Object>) data); } } /** * 发送 SSL POST 请求(HTTPS),K-V形式 * @param apiUrl API接口URL * @param params 参数map * @return */ /*public static String doPostSSL(String apiUrl, Map<String, Object> params) { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; try { httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> entry : params.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry .getValue().toString()); pairList.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8"))); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; }*/ /*public static String doPostSSLHeader(String apiUrl, Object json, Header[] headers){ CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); httpPost.setHeaders(headers); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { httpStr = EntityUtils.toString(entity, "utf-8"); return httpStr; } } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; }*/ /** * 发送 SSL POST 请求(HTTPS),JSON形式 * @param apiUrl API接口URL * @param json JSON对象 * @return */ /*public static String doPostSSL(String apiUrl, Object json) { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; }*/ /** * 创建SSL安全连接 * * @return */ /*private static SSLConnectionSocketFactory createSSLConnSocketFactory() { SSLConnectionSocketFactory sslsf = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } }); } catch (GeneralSecurityException e) { e.printStackTrace(); } return sslsf; }*/ }
e722750548fe62b42dc97ec3385be5c929a7827a
e3ba1b600f0431c02272466319a082c47439de9c
/guifengstation/src/Dao/loginDao.java
d11c3e95e306a93a53bd8e3ad14dfaf6726abadd
[]
no_license
Teamo-x/zhaojinsong
fc492945dde44bbdb33974394a3a402a7a7df974
c4bb76b201d9040d59a00582f1355a83a992fee4
refs/heads/master
2020-08-08T11:07:20.634588
2019-10-14T01:11:43
2019-10-14T01:11:43
213,817,918
0
0
null
null
null
null
UTF-8
Java
false
false
560
java
package Dao; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import Entity.Admin; import Utils.DataSourceUtil; public class loginDao { public Admin login(String name) throws SQLException { // TODO Auto-generated method stub QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource()); String sql="select * from admin where adminname=?"; Admin a = qr.query(sql,new BeanHandler<Admin>(Admin.class),name); return a; } }
6b4af6e21ac99b9f315c22597baba60204cf3cbb
d5e8a1f4f470e85414a6c975814f3ba6df520cf9
/Design-Patterns/src/main/java/com/epam3/Design_Patterns/Singleton.java
635924eaec1096950d7d53783f8f4bf7b771afb1
[]
no_license
greeshmathattepally/DesignPatterns
fa6a2fc39670fc609773aa97c311e9a862530640
9fccf13203abdd7fdba7baa964275759f96c8c02
refs/heads/master
2022-12-19T21:51:14.249173
2020-07-17T14:59:39
2020-07-17T14:59:39
280,450,491
0
0
null
2020-10-13T23:39:43
2020-07-17T14:49:11
Java
UTF-8
Java
false
false
277
java
package com.epam3.Design_Patterns; public class Singleton { static Singleton obj=null; private Singleton() { System.out.println("In singleton class"); } static Singleton getInstance() { if(obj==null) { obj=new Singleton(); } return obj; } }
6830075351a656338cb634e961e1ccd95f5f3e6f
032454dc882a4b6be2c6ed4be876ce2df4373bff
/multiModuleBuildUsingParentBuildFile/backend/src/main/java/Backend.java
d0e40b3c37442d71c9b8827ce8a4c78c502380c5
[ "MIT" ]
permissive
tklae/gradle-examples
1e387d249de2b194d1dd88564b1ef20687c16a9a
914d185ee7839b22a25f0bf3d35bc07ee77ccbe1
refs/heads/master
2020-04-05T22:53:42.831601
2014-01-15T14:31:04
2014-01-15T14:31:04
15,705,520
2
1
null
null
null
null
UTF-8
Java
false
false
219
java
public class Backend { public static final String RESPONSE_TEXT = "Response for: "; public SharedDataContainer invoke(String request) { return new SharedDataContainer(RESPONSE_TEXT + request); } }
be399e124e8441c309d543fcc3f5b28c22206658
7683d37dcfffde8be2b60d9ca9ffd254f72c960e
/app/src/main/java/com/example/android/bookapp2/UpdateActivity.java
48d12cf50bf67d886c169ade8037884efb83dc9a
[]
no_license
karanchhatwani1/BookApp2
aafe0166a5f69835dbf8600c0d425a6554620dd7
525202627f1ca152214ec895800c62c4b6e6d772
refs/heads/master
2022-11-18T22:41:42.313313
2020-07-18T20:14:07
2020-07-18T20:14:07
280,731,701
0
0
null
null
null
null
UTF-8
Java
false
false
3,090
java
package com.example.android.bookapp2; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class UpdateActivity extends AppCompatActivity { EditText title_input, author_input, pages_input; Button update_button, delete_button; String id,title,author,pages; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); title_input = findViewById(R.id.title_input2); author_input = findViewById(R.id.author_input2); pages_input = findViewById(R.id.pages_input2); update_button = findViewById(R.id.update_button); delete_button = findViewById(R.id.delete_button); getAndSetIntentData(); ActionBar ab = getSupportActionBar(); if(ab != null){ ab.setTitle(title); } update_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyDatabaseHelper myDB = new MyDatabaseHelper(UpdateActivity.this); myDB.updateData(id,title,author,pages); } }); delete_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirmDialog(); } }); } void getAndSetIntentData() { if (getIntent().hasExtra("id") && getIntent().hasExtra("title") && getIntent().hasExtra("author") && getIntent().hasExtra("pages")) { id = getIntent().getStringExtra("id"); title = getIntent().getStringExtra("title"); author = getIntent().getStringExtra("author"); pages = getIntent().getStringExtra("pages"); title_input.setText(title); author_input.setText(author); pages_input.setText(pages); } else{ Toast.makeText(this,"No Data", Toast.LENGTH_SHORT).show(); } } void confirmDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete "+ title + "?"); builder.setMessage("Are you sure you want to delete" + title + "?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyDatabaseHelper myDB = new MyDatabaseHelper(UpdateActivity.this); myDB.deleteOneRow(id); finish(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } }
f11082f413b212e96020edc3389b967856eb83b8
6aa464a8ae7299203e2a9be737ab82ea115b3d61
/Animation.java
f5a32c792f8007108b86dd58a487e981d8261e99
[]
no_license
glennismade/Artificial-Life-Simulator
dc1dde40de847619daee73771f992d097f0e9a87
440a81de90b850107a9499ba1ab6fed9f3a73476
refs/heads/master
2021-05-02T17:19:41.738892
2018-02-07T16:39:53
2018-02-07T16:39:53
120,642,065
0
0
null
null
null
null
UTF-8
Java
false
false
6,969
java
package glenn.healy; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.animation.TimelineBuilder; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Duration; import javafx.animation.Interpolator; import javafx.animation.KeyValue; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.WritableValue; public class Animation { /** * this is the animation class and contains the methods or */ //variables for the main simulation system ABug[] bugArray; Food[] FoodArray; double startTime; double startFoodTime; Timeline anim; public int numBugs = 5; int numFood = 10; static double screenWidth; static double screenHeight; double x = screenWidth / 2; double y = screenHeight / 2; double x2 = screenWidth / 2; double y2 = screenHeight / 2; boolean isPause = false; // keyframe animator controller. KeyFrame frame; /** * this is the aniamtion method and contains the implimentation od the animation class * @param stage // the window * @param scene // the container for the objects * @param sHeight // the scene height * @param sWidth // the scene width */ public Animation(Stage stage, Scene scene, int sHeight, int sWidth) { bugArray = new ABug[numBugs]; FoodArray = new Food[numFood]; screenWidth = sWidth; screenHeight = sHeight; // /get start time startTime = System.currentTimeMillis(); startFoodTime = System.currentTimeMillis(); start(stage, scene); } /** * this is the start method and is used to start the stage. * @param primaryStage the main stage in the program * @param scene the scene (act) of the window that contains the objects. */ public void start(Stage primaryStage, Scene scene) { final ABug singleBug = new ABug(); final StackPane root = new StackPane(); for (int i = 0; i < numBugs; i++) { bugArray[i] = new ABug(); root.getChildren().addAll(bugArray[i].GetCircle()); } // now do same for vegetables for (int i = 0; i < numFood; i++) { FoodArray[i] = new Food(); root.getChildren().addAll(FoodArray[i].GetCircle()); } ((VBox) scene.getRoot()).getChildren().addAll(root); frame = new KeyFrame(Duration.millis(27), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { if (!isPause) { for (int i = 0; i < numBugs; i++) { if (bugArray[i].GetCircle().getCenterX() + bugArray[i].GetCircle() .getTranslateX() < bugArray[i] .GetCircle().getRadius() || bugArray[i].GetCircle().getCenterX() + bugArray[i].GetCircle() .getTranslateX() > screenWidth - bugArray[i].GetCircle() .getRadius()) { float temp = bugArray[i].GetDX(); temp *= -1; bugArray[i].SetDX(temp); } if (bugArray[i].GetCircle().getCenterY() + bugArray[i].GetCircle() .getTranslateY() < bugArray[i] .GetCircle().getRadius() + 5 || bugArray[i].GetCircle().getCenterY() + bugArray[i].GetCircle() .getTranslateY() > screenHeight - bugArray[i].GetCircle() .getRadius() - 25) { float temp = bugArray[i].GetDY(); temp *= -1; bugArray[i].SetDY(temp); } } for (int i = 0; i < numBugs; i++) { double bugX = bugArray[i].GetCircle() .getTranslateX() + bugArray[i].GetCircle().getCenterX(); double bugY = bugArray[i].GetCircle() .getTranslateY() + bugArray[i].GetCircle().getCenterY(); for (int j = 0; j < numFood; j++) { double foodX = FoodArray[j].GetCircle() .getTranslateX() + FoodArray[j].GetCircle() .getCenterX(); double foodY = FoodArray[j].GetCircle() .getTranslateY() + FoodArray[j].GetCircle() .getCenterY(); if (dist(bugX, foodX, bugY, foodY) < bugArray[i].scanDistance && FoodArray[j].isAlive) { singleBug.isRandMove = false; if (bugX > foodX) { bugArray[i].deltaX -= 0.05f; } else { bugArray[i].deltaX += 0.05f; } if (bugY > foodY) { bugArray[i].deltaY -= 0.05f; } else { bugArray[i].deltaY += 0.05f; } } else { bugArray[i].isRandMove = true; } if (dist(bugX, foodX, bugY, foodY) < bugArray[i] .GetCircle().getRadius() * 2 && FoodArray[j].isAlive) { // collision with food FoodArray[j].isAlive = false; root.getChildren().remove( FoodArray[j].GetCircle()); // here after eating food, the bug // stands still till next random move bugArray[i].SetDX(0f); bugArray[i].SetDY(0f); } } } // choose random direction and speed every 5 seconds if (System.currentTimeMillis() > startTime + 5000) { startTime = System.currentTimeMillis(); for (int i = 0; i < numBugs; i++) { if (bugArray[i].isRandMove) { bugArray[i].RandMoveX(); bugArray[i].RandMoveY(); } } } // set translate x y for all bugs for (int i = 0; i < numBugs; i++) { bugArray[i].GetCircle().setTranslateX( bugArray[i].GetCircle().getTranslateX() + bugArray[i].GetDX()); bugArray[i].GetCircle().setTranslateY( bugArray[i].GetCircle().getTranslateY() + bugArray[i].GetDY()); } } } /** *this is the dist method, it contains the functions of double and is used to calcualate distance between objects. * @param posBall1x * @param posBall2x * @param posBall1y * @param posBall2y * @return */ private double dist(double posBall1x, double posBall2x, double posBall1y, double posBall2y) { // calc euclidean distance double diffX = posBall1x - posBall2x; double diffY = posBall1y - posBall2y; double distance = (diffX * diffX) + (diffY * diffY); distance = Math.sqrt(distance); // return euclidean distance return distance; } }); WritableValue<Number> startXVal = new SimpleDoubleProperty(100.0); anim = TimelineBuilder .create() .autoReverse(false) .keyFrames( frame, new KeyFrame(new Duration(13), new KeyValue(startXVal, 300.0, Interpolator.LINEAR))) .cycleCount(Timeline.INDEFINITE).build(); anim.play(); primaryStage.setTitle("Animation Running"); primaryStage.setScene(scene); primaryStage.setResizable(false); primaryStage.show(); } }
9971404d64773c817b709a0ef031aedfaff35aae
937e8067af70045bca4cd740da7161999af0bfcc
/src/main/java/threads/ConnectionPool.java
cfe24d5451becca3540afb759ee1efcafab2595e
[]
no_license
ndreddy/algo
81962f75dbbbf92f45509ddacc3307798814cdaf
3d9d14ff7d07c4d7dee2a4293c960f45dc52d729
refs/heads/master
2022-08-31T07:11:17.989968
2022-08-12T11:01:09
2022-08-12T11:01:09
101,049,317
0
0
null
2020-09-08T10:51:49
2017-08-22T10:04:22
Java
UTF-8
Java
false
false
2,101
java
package threads; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; interface Connection { int read() throws IOException; // reads an int from the connection void close() throws IOException; // closes the connection } class StreamConnection implements Connection { private final InputStream input = null; public int read() throws IOException { return input.read(); } public void close() throws IOException { input.close(); } } class StreamConnectionPool { List<StreamConnection> freeConnections; //openSomeConnectionsSomehow(); public StreamConnectionPool(int bound) { freeConnections = new ArrayList<>(bound); for (int i = 0; i < bound; i++) { freeConnections.add(new StreamConnection()); } } StreamConnection borrowConnection(){ if (freeConnections.isEmpty()) throw new IllegalStateException("No free connections"); return freeConnections.remove(0); } void returnConnection(StreamConnection conn){ freeConnections.add(conn); } } public class ConnectionPool { private final StreamConnectionPool streamPool; // ...; public ConnectionPool(int bound) { streamPool = new StreamConnectionPool(bound); } Connection getConnection() { final StreamConnection realConnection = streamPool.borrowConnection(); return new Connection(){ private boolean closed = false; public int read() throws IOException { if (closed) throw new IllegalStateException("Connection closed"); return realConnection.read(); } public void close() { if (!closed) { closed = true; streamPool.returnConnection(realConnection); } } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } }; } }
82a220210a3088868b2adeb44861a1beaad4e8f3
c03552af5d190af651b23e5f43b61bcdbd590bed
/app/src/main/java/com/example/a40136/arcore_measure/MainActivity.java
5c078da82707f9c0c07cc463fe87719a7f145cc7
[]
no_license
ljsdyspg/ARCore_Measure
2a34534829b8853592f3d55e19851fcfdc82e089
04b3d755a5abce46f2326eb2d5cd7cce86406f1b
refs/heads/master
2020-04-29T06:31:55.718928
2019-03-16T03:04:00
2019-03-16T03:04:00
175,918,887
6
0
null
null
null
null
UTF-8
Java
false
false
18,295
java
package com.example.a40136.arcore_measure; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.ar.core.Anchor; import com.google.ar.core.Frame; import com.google.ar.core.exceptions.NotYetAvailableException; import com.google.ar.sceneform.AnchorNode; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.Vector3; import com.google.ar.sceneform.rendering.Color; import com.google.ar.sceneform.rendering.MaterialFactory; import com.google.ar.sceneform.rendering.ModelRenderable; import com.google.ar.sceneform.rendering.ShapeFactory; import com.google.ar.sceneform.rendering.ViewRenderable; import com.google.ar.sceneform.ux.ArFragment; import com.google.ar.sceneform.ux.TransformableNode; import org.opencv.android.OpenCVLoader; import org.opencv.core.Point; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private static final Double MIN_OPENGL_VERSION = 3.0; private ArFragment arFragment; private Button btn_trans; private TextView tv_state; private ModelRenderable coordRenderable; private Frame frame; // 手机长宽 private int phone_width; private int phone_height; // 图像长宽 private int pic_width = 480; private int pic_height = 640; private ArrayList<AnchorNode> anchorNodes = new ArrayList<>(); private ArrayList<Node> nodeForLines = new ArrayList<>(); private ArrayList<Float> distances = new ArrayList<>(); private ArrayList<Node> infos = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (!checkIsSupportedDeviceOrFinish(this))return; initLoadOpenCV(); initModel(); initFragment(); init(); getWidthAndHeight(); } /** * 加载OpenCV */ private void initLoadOpenCV() { boolean success = OpenCVLoader.initDebug(); if (success) { Log.i(TAG, "OpenCV Libraries loaded..."); Toast.makeText(this, "OpenCV Libraries loaded...", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this.getApplicationContext(), "WARNING: Could not load OpenCV Libraries", Toast.LENGTH_SHORT).show(); } } /** * 初始化控件 */ private void init(){ btn_trans = findViewById(R.id.btn_trans); btn_trans.setOnClickListener(view ->{ Toast.makeText(this, "转换!", Toast.LENGTH_SHORT).show(); // 获取Bitmap用于角点检测 Bitmap bitmap = getBitmapFromView(); // 保存Bitmap到相册 saveBmp2Gallery(bitmap,"aaaa"); // 获取角点 ArrayList<Point> points = CornorDetect.getCorner(bitmap); if (points == null){ Toast.makeText(this, "检测失败", Toast.LENGTH_SHORT).show(); }else{ Log.d(TAG, "cornors: "+points.size()); Log.d(TAG, "p1"+points.get(0).x+", "+points.get(0).y); Log.d(TAG, "p2"+points.get(1).x+", "+points.get(1).y); Log.d(TAG, "p3"+points.get(2).x+", "+points.get(2).y); Log.d(TAG, "p4"+points.get(3).x+", "+points.get(3).y); Toast.makeText(this, "检测成功", Toast.LENGTH_SHORT).show(); addCornerAnchor(points); } }); tv_state = findViewById(R.id.tv_state); } /** * 初始化ArFragment,以及点击创建Model事件 */ private void initFragment() { arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment); arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> { if (coordRenderable == null){ return; } // 创建Anchor Anchor anchor = hitResult.createAnchor(); AnchorNode anchorNode = new AnchorNode(anchor); anchorNode.setParent(arFragment.getArSceneView().getScene()); // 添加进链表 anchorNodes.add(anchorNode); // 渲染各种Model drawModel(); // 获取信息 tv_state.setText(getString(distances)); // 将Model添加到Anchor TransformableNode coord = new TransformableNode(arFragment.getTransformationSystem()); coord.setParent(anchorNode); coord.setRenderable(coordRenderable); coord.select(); coord.setOnTouchListener((hitTestResult, motionEvent1) -> { if (motionEvent1.getAction() == MotionEvent.ACTION_UP){ Toast.makeText(MainActivity.this, "点中了", Toast.LENGTH_SHORT).show(); // 渲染Model drawModel(); // 获取信息 tv_state.setText(getString(distances)); } return false; }); }); } /** * 画出标点之间的连线并显示其长度 */ private void drawModel(){ if (anchorNodes.size()>=2){ if (nodeForLines.size()!=0){ for (Node node : nodeForLines) { node.setRenderable(null); } nodeForLines.clear(); } if(infos.size()!=0){ for (Node info: infos){ info.setRenderable(null); } infos.clear(); } // nodeForLines = new ArrayList<>(); distances = getAllDistance(anchorNodes); // nodeForLines.clear(); drawAllLines(anchorNodes); drawInfo(nodeForLines, distances); } } /** * 初始化Model资源 */ private void initModel() { ModelRenderable.builder() .setSource(this, Uri.parse("model.sfb")) .build() .thenAccept(renderable -> coordRenderable = renderable) .exceptionally(throwable -> { Log.e(TAG, "Unable to load Renderable.", throwable ); return null; }); } /** * 获取当前View中的图像,用于角点检测 * @return Bitmap图像 */ private Bitmap getBitmapFromView(){ Bitmap bitmap = null; try { Image image = arFragment.getArSceneView().getArFrame().acquireCameraImage(); byte[] bytes = UtilsBitmap.imageToByte(image); bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null); bitmap = UtilsBitmap.rotateBitmap(bitmap, 90); } catch (NotYetAvailableException e) { e.printStackTrace(); } return bitmap; } /** * 将检测到的角点作HitTest,再将Model放置在其结果上 * @param points 检测到的角点坐标 */ private void addCornerAnchor(ArrayList<Point> points){ frame = arFragment.getArSceneView().getArFrame(); for (Point point : points) { Anchor anchor = frame.hitTest(pic2screen(point)[0],pic2screen(point)[1]).get(0).createAnchor(); AnchorNode anchorNode = new AnchorNode(anchor); anchorNode.setParent(arFragment.getArSceneView().getScene()); // 添加进链表 anchorNodes.add(anchorNode); // 渲染各种Model drawModel(); // 获取信息 tv_state.setText(getString(distances)); // 将Model添加到Anchor TransformableNode coord = new TransformableNode(arFragment.getTransformationSystem()); coord.setParent(anchorNode); coord.setRenderable(coordRenderable); coord.select(); coord.setOnTouchListener((hitTestResult, motionEvent1) -> { if (motionEvent1.getAction() == MotionEvent.ACTION_DOWN){ Toast.makeText(MainActivity.this, "点中了", Toast.LENGTH_SHORT).show(); } return false; }); } } /** * 获取当前手机屏幕的宽高(单位:像素) */ private void getWidthAndHeight(){ Display display = getWindowManager().getDefaultDisplay(); android.graphics.Point outSize = new android.graphics.Point(); display.getSize(outSize); phone_width = outSize.x; phone_height = outSize.y; } private float[] pic2screen(Point point){ double x = point.x * phone_width / pic_width; double y = point.y * phone_height / pic_height; return new float[]{(float) x, (float) y}; } /** * 获取链表中所有点的距离 * * @param anchorNodes 锚点 * @return */ private ArrayList<Float> getAllDistance(ArrayList<AnchorNode> anchorNodes) { ArrayList<Float> distances = new ArrayList<>(); for (int i = 0; i < anchorNodes.size() - 1; i++) { float dis = distance(anchorNodes.get(i), anchorNodes.get(i + 1)); distances.add(dis); } return distances; } /** * 计算两个点之间的距离 * * @param node1 * @param node2 * @return */ private float distance(AnchorNode node1, AnchorNode node2) { float dx = node1.getWorldPosition().x - node2.getWorldPosition().x; float dy = node1.getWorldPosition().y - node2.getWorldPosition().y; float dz = node1.getWorldPosition().z - node2.getWorldPosition().z; float result = Float.valueOf(String.format("%.3f", Math.sqrt(dx * dx + dy * dy + dz * dz))); return result; } /** * 将所有计算结果表述出来 * * @param allDistance * @return */ private String getString(ArrayList<Float> allDistance) { String txt = "\n"; for (int i = 0; i < allDistance.size(); i++) { txt += "第" + i + "段距离为:" + allDistance.get(i) +"m"+ "\n"; } txt += "线数量" + nodeForLines.size() + "\n"; txt += "Info数量" + infos.size() + "\n"; txt += "标点数量" + anchorNodes.size(); return txt; } /** * 画出顺序点之间的连线 */ private void drawLine(AnchorNode node1, AnchorNode node2) { //Draw a line between two AnchorNodes Log.d(TAG, "drawLine"); Vector3 point1, point2; point1 = node1.getWorldPosition(); point2 = node2.getWorldPosition(); point1.x = Float.valueOf(String.format("%.3f", point1.x)); point1.y = Float.valueOf(String.format("%.3f", point1.y)); point1.z = Float.valueOf(String.format("%.3f", point1.z)); point2.x = Float.valueOf(String.format("%.3f", point2.x)); point2.y = Float.valueOf(String.format("%.3f", point2.y)); point2.z = Float.valueOf(String.format("%.3f", point2.z)); //First, find the vector extending between the two points and define a look rotation //in terms of this Vector. Node nodeForLine = new Node(); final Vector3 difference = Vector3.subtract(point1, point2); final Vector3 directionFromTopToBottom = difference.normalized(); final Quaternion rotationFromAToB = Quaternion.lookRotation(directionFromTopToBottom, Vector3.up()); MaterialFactory.makeOpaqueWithColor(getApplicationContext(), new Color(238, 238, 0)) .thenAccept( material -> { /* Then, create a rectangular prism, using ShapeFactory.makeCube() and use the difference vector to extend to the necessary length. */ Log.d(TAG, "drawLine insie .thenAccept"); ModelRenderable model = ShapeFactory.makeCube( new Vector3(.01f, .01f, difference.length()), Vector3.zero(), material); /* Last, set the world rotation of the node to the rotation calculated earlier and set the world position to the midpoint between the given points . */ nodeForLine.setParent(node2); nodeForLine.setRenderable(model); nodeForLine.setWorldPosition(Vector3.add(point1, point2).scaled(.5f)); nodeForLine.setWorldRotation(rotationFromAToB); nodeForLine.setEnabled(true); } ); nodeForLines.add(nodeForLine); } /** * 画出所有的连线 */ private void drawAllLines(ArrayList<AnchorNode> anchorNodes) { for (int i = 0; i < anchorNodes.size() - 1; i++) { drawLine(anchorNodes.get(i), anchorNodes.get(i + 1)); } } /** * 标记出连线的长度 */ private void drawInfo(ArrayList<Node> nodeForLines, ArrayList<Float> distances) { if (nodeForLines.size() != distances.size()) { String txt = "出带问题了!"; txt += "nodeForLines: " + nodeForLines.size() + " distances: " + distances.size(); Toast.makeText(this, txt, Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < nodeForLines.size(); i++) { Node info = new Node(); info.setParent(nodeForLines.get(i)); info.setEnabled(true); info.setLookDirection(new Vector3(0,-0.02f,0)); //info.setWorldRotation(new Quaternion(0,1,0,270)); //info.setLocalScale(new Vector3(0.5f,0.5f,0.5f)); info.setLocalPosition(new Vector3(0.0f, 0.01f, 0.0f)); int finalI = i; ViewRenderable.builder() .setView(this, R.layout.info_view) .build() .thenAccept( (renderable) -> { info.setRenderable(renderable); TextView textView = (TextView) renderable.getView(); textView.setText(String.valueOf(distances.get(finalI))); }); infos.add(info); } } } /** * @param bmp 获取的bitmap数据 * @param picName 自定义的图片名 */ public void saveBmp2Gallery(Bitmap bmp, String picName) { String fileName = null; //系统相册目录 String galleryPath= Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM +File.separator+"Camera"+File.separator; // 声明文件对象 File file = null; // 声明输出流 FileOutputStream outStream = null; try { // 如果有目标文件,直接获得文件对象,否则创建一个以filename为名称的文件 file = new File(galleryPath, picName+ ".jpg"); // 获得文件相对路径 fileName = file.toString(); // 获得输出流,如果文件中有内容,追加内容 outStream = new FileOutputStream(fileName); if (null != outStream) { bmp.compress(Bitmap.CompressFormat.PNG, 90, outStream); } } catch (Exception e) { e.getStackTrace(); }finally { try { if (outStream != null) { outStream.close(); } } catch (IOException e) { e.printStackTrace(); } } MediaStore.Images.Media.insertImage(getContentResolver(), bmp, fileName, null); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file); intent.setData(uri); sendBroadcast(intent); Toast.makeText(this, "完成保存!", Toast.LENGTH_SHORT).show(); } /** * Returns false and displays an error message if Sceneform can not run, true if Sceneform can run * on this device. * * <p>Sceneform requires Android N on the device as well as OpenGL 3.0 capabilities. * * <p>Finishes the activity if Sceneform can not run */ public static boolean checkIsSupportedDeviceOrFinish(final Activity activity) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { Log.e(TAG, "Sceneform requires Android N or later"); Toast.makeText(activity, "Sceneform requires Android N or later", Toast.LENGTH_LONG).show(); activity.finish(); return false; } String openGlVersionString = ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE)) .getDeviceConfigurationInfo() .getGlEsVersion(); if (Float.parseFloat(openGlVersionString) < MIN_OPENGL_VERSION) { Log.e(TAG, "Sceneform requires OpenGL ES 3.0 later"); Toast.makeText(activity, "Sceneform requires OpenGL ES 3.0 or later", Toast.LENGTH_LONG) .show(); activity.finish(); return false; } return true; } }
34c2d6b661a5ee178dec10bfbdbef6743ca17a4a
72484babab0e902b032201bd9d332c1f65054932
/src/TestCases/TestHomePage.java
2b61f4c9ace7f753ab0135e9a12aae83bd9e0a0a
[]
no_license
gitpley/test-automation
b46d111d7e504423d7f28e2cc77360b495725c4b
bfd5dd74a4f797e7c67f2a443c9e56640753b5aa
refs/heads/master
2020-04-17T08:14:41.178034
2015-02-13T17:58:12
2015-02-13T17:58:12
30,301,706
0
0
null
null
null
null
UTF-8
Java
false
false
418
java
package TestCases; import org.testng.annotations.Test; import Core.HomePage; import Core.TestCore; public class TestHomePage extends TestCore { @Test public void HomePage(){ HomePage hm = new HomePage(driver); //Verify that header name appears on the page hm.headername(); //Verify that Login button appears hm.login(); //Verify that Sign up button appears hm.signup(); } }
21bca784dd3596779e01c9e355449b30ec393037
653a0bc03eec49814dd9d423828fd7a50d2cf852
/src/main/java/org/embulk/input/hdfs/HdfsFileInputPlugin.java
f26485d2a4571c7635e7af25dd7f760deb7b0a25
[ "MIT" ]
permissive
sonots/embulk-input-hdfs
345e9ea4eff0e0e2e692674a0db37464becd7353
44323b1c58c4ce44259912cf99d3d5b096f1e56a
refs/heads/master
2020-07-10T03:18:14.813479
2015-11-06T09:10:23
2015-11-06T09:10:23
46,320,366
0
0
null
2015-11-17T03:18:37
2015-11-17T03:18:35
Java
UTF-8
Java
false
false
9,567
java
package org.embulk.input.hdfs; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathNotFoundException; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigInject; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; import org.embulk.spi.BufferAllocator; import org.embulk.spi.Exec; import org.embulk.spi.FileInputPlugin; import org.embulk.spi.TransactionalFileInput; import org.embulk.spi.util.InputStreamTransactionalFileInput; import org.jruby.embed.ScriptingContainer; import org.slf4j.Logger; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HdfsFileInputPlugin implements FileInputPlugin { private static final Logger logger = Exec.getLogger(HdfsFileInputPlugin.class); public interface PluginTask extends Task { @Config("config_files") @ConfigDefault("[]") public List<String> getConfigFiles(); @Config("config") @ConfigDefault("{}") public Map<String, String> getConfig(); @Config("path") public String getPath(); @Config("rewind_seconds") @ConfigDefault("0") public int getRewindSeconds(); @Config("partition") @ConfigDefault("true") public boolean getPartition(); @Config("num_partitions") // this parameter is the approximate value. @ConfigDefault("-1") // Default: Runtime.getRuntime().availableProcessors() public int getApproximateNumPartitions(); public List<HdfsPartialFile> getFiles(); public void setFiles(List<HdfsPartialFile> hdfsFiles); @ConfigInject public BufferAllocator getBufferAllocator(); } @Override public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); // listing Files String pathString = strftime(task.getPath(), task.getRewindSeconds()); try { List<String> originalFileList = buildFileList(getFs(task), pathString); if (originalFileList.isEmpty()) { throw new PathNotFoundException(pathString); } task.setFiles(allocateHdfsFilesToTasks(task, getFs(task), originalFileList)); logger.info("Loading target files: {}", originalFileList); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } // log the detail of partial files. for (HdfsPartialFile partialFile : task.getFiles()) { logger.info("target file: {}, start: {}, end: {}", partialFile.getPath(), partialFile.getStart(), partialFile.getEnd()); } // number of processors is same with number of targets int taskCount = task.getFiles().size(); logger.info("task size: {}", taskCount); return resume(task.dump(), taskCount, control); } @Override public ConfigDiff resume(TaskSource taskSource, int taskCount, FileInputPlugin.Control control) { control.run(taskSource, taskCount); ConfigDiff configDiff = Exec.newConfigDiff(); // usually, yo use last_path //if (task.getFiles().isEmpty()) { // if (task.getLastPath().isPresent()) { // configDiff.set("last_path", task.getLastPath().get()); // } //} else { // List<String> files = new ArrayList<String>(task.getFiles()); // Collections.sort(files); // configDiff.set("last_path", files.get(files.size() - 1)); //} return configDiff; } @Override public void cleanup(TaskSource taskSource, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalFileInput open(TaskSource taskSource, int taskIndex) { final PluginTask task = taskSource.loadTask(PluginTask.class); InputStream input; try { input = openInputStream(task, task.getFiles().get(taskIndex)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } return new InputStreamTransactionalFileInput(task.getBufferAllocator(), input) { @Override public void abort() { } @Override public TaskReport commit() { return Exec.newTaskReport(); } }; } private static HdfsPartialFileInputStream openInputStream(PluginTask task, HdfsPartialFile partialFile) throws IOException { FileSystem fs = getFs(task); InputStream original = fs.open(new Path(partialFile.getPath())); return new HdfsPartialFileInputStream(original, partialFile.getStart(), partialFile.getEnd()); } private static FileSystem getFs(final PluginTask task) throws IOException { Configuration configuration = new Configuration(); for (Object configFile : task.getConfigFiles()) { configuration.addResource(configFile.toString()); } configuration.reloadConfiguration(); for (Map.Entry<String, String> entry: task.getConfig().entrySet()) { configuration.set(entry.getKey(), entry.getValue()); } return FileSystem.get(configuration); } private String strftime(final String raw, final int rewind_seconds) { ScriptingContainer jruby = new ScriptingContainer(); Object resolved = jruby.runScriptlet( String.format("(Time.now - %s).strftime('%s')", String.valueOf(rewind_seconds), raw)); return resolved.toString(); } private List<String> buildFileList(final FileSystem fs, final String pathString) throws IOException { List<String> fileList = new ArrayList<>(); Path rootPath = new Path(pathString); final FileStatus[] entries = fs.globStatus(rootPath); // `globStatus` does not throw PathNotFoundException. // return null instead. // see: https://github.com/apache/hadoop/blob/branch-2.7.0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/Globber.java#L286 if (entries == null) { return fileList; } for (FileStatus entry : entries) { if (entry.isDirectory()) { fileList.addAll(lsr(fs, entry)); } else { fileList.add(entry.getPath().toString()); } } return fileList; } private List<String> lsr(final FileSystem fs, FileStatus status) throws IOException { List<String> fileList = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus entry : fs.listStatus(status.getPath())) { fileList.addAll(lsr(fs, entry)); } } else { fileList.add(status.getPath().toString()); } return fileList; } private List<HdfsPartialFile> allocateHdfsFilesToTasks(final PluginTask task, final FileSystem fs, final List<String> fileList) throws IOException { List<Path> pathList = Lists.transform(fileList, new Function<String, Path>() { @Nullable @Override public Path apply(@Nullable String input) { return new Path(input); } }); int totalFileLength = 0; for (Path path : pathList) { totalFileLength += fs.getFileStatus(path).getLen(); } // TODO: optimum allocation of resources int approximateNumPartitions = (task.getApproximateNumPartitions() <= 0) ? Runtime.getRuntime().availableProcessors() : task.getApproximateNumPartitions(); int partitionSizeByOneTask = totalFileLength / approximateNumPartitions; List<HdfsPartialFile> hdfsPartialFiles = new ArrayList<>(); for (Path path : pathList) { int fileLength = (int) fs.getFileStatus(path).getLen(); // declare `fileLength` here because this is used below. if (fileLength <= 0) { logger.info("Skip the 0 byte target file: {}", path); continue; } int numPartitions; if (path.toString().endsWith(".gz") || path.toString().endsWith(".bz2") || path.toString().endsWith(".lzo")) { numPartitions = 1; } else if (!task.getPartition()) { numPartitions = 1; } else { numPartitions = ((fileLength - 1) / partitionSizeByOneTask) + 1; } HdfsFilePartitioner partitioner = new HdfsFilePartitioner(fs, path, numPartitions); hdfsPartialFiles.addAll(partitioner.getHdfsPartialFiles()); } return hdfsPartialFiles; } }
545217c08b7e1a0074cc520a96c9fe2e00867071
76852b1b29410436817bafa34c6dedaedd0786cd
/sources-2020-07-19-tempmail/sources/com/tempmail/db/a.java
2722670cf43fc2a2afe926d5b1452d2dbf147723
[]
no_license
zteeed/tempmail-apks
040e64e07beadd8f5e48cd7bea8b47233e99611c
19f8da1993c2f783b8847234afb52d94b9d1aa4c
refs/heads/master
2023-01-09T06:43:40.830942
2020-11-04T18:55:05
2020-11-04T18:55:05
310,075,224
0
0
null
null
null
null
UTF-8
Java
false
false
2,440
java
package com.tempmail.db; import android.webkit.MimeTypeMap; import com.tempmail.utils.m; import java.io.Serializable; /* compiled from: AttachmentInfoTable */ public class a implements Serializable { /* renamed from: b reason: collision with root package name */ private Long f12279b; /* renamed from: c reason: collision with root package name */ private String f12280c; /* renamed from: d reason: collision with root package name */ private String f12281d; /* renamed from: e reason: collision with root package name */ private Integer f12282e; /* renamed from: f reason: collision with root package name */ private Long f12283f; private String g; private String h; public a(String str, String str2, Integer num, Long l, String str3, String str4) { this.f12280c = str; this.f12281d = str2; this.f12282e = num; this.f12283f = l; this.g = str3; this.h = str4; } public Integer a() { return this.f12282e; } public String b() { return this.h; } public String c() { return this.f12280c; } public String d() { return this.f12281d; } public Long e() { return this.f12279b; } public String f() { return c() + " " + a(); } public String g() { return this.g; } public Long h() { return this.f12283f; } public String i() { String simpleName = a.class.getSimpleName(); m.b(simpleName, "attachmentInfoTable mime type " + g()); String extensionFromMimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(g()); String d2 = d(); m.b(simpleName, "fileName " + d2); m.b(simpleName, "extension " + extensionFromMimeType); if (extensionFromMimeType == null || d2.contains(extensionFromMimeType)) { return d2; } String str = d2 + "." + extensionFromMimeType; m.b(simpleName, "fileName updated" + str); return str; } public void j(Long l) { this.f12279b = l; } public a() { } public a(Long l, String str, String str2, Integer num, Long l2, String str3, String str4) { this.f12279b = l; this.f12280c = str; this.f12281d = str2; this.f12282e = num; this.f12283f = l2; this.g = str3; this.h = str4; } }
6578ed00ba9f18d3937a271a9c06cd33b6587356
efc5f7c4657736e1fc054878255fedc638a0331f
/spring-demo-client/src/main/java/com/codingapi/example/client/ClientDemoMapper.java
d6c216000bb5178bf1b391b33fb33e39f1813cab
[]
no_license
yzw31/txlcn-demo
14eb1fd85d171a7cc8e11a9c658b06a0643a7a21
cba247ac11c2d9c8211994fba72b82685226b08f
refs/heads/master
2020-04-19T10:22:02.903308
2019-01-28T03:36:26
2019-01-28T03:36:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
272
java
package com.codingapi.example.client; import com.codingapi.example.common.db.mapper.DemoMapper; import org.apache.ibatis.annotations.Mapper; /** * Description: * Date: 2018/12/25 * * @author ujued */ @Mapper public interface ClientDemoMapper extends DemoMapper { }
0eb3c5f256f4d527ccac67c7632ddce7e7236268
f3891f53a8da5f44ee321839295844a920f52844
/jold/java/idsa/SelectionSort.java
c8b19ac1fe1c9ce62446daa32485c7cceb76e217
[]
no_license
arunras/breakthecode
7f6cf0e8ffdbb65e1ae62374a204d2c857058474
0f5c98b951d603e737e433ff798c0bd734187be6
refs/heads/master
2022-05-10T18:36:46.851409
2022-05-04T21:08:42
2022-05-04T21:08:42
108,296,246
0
2
null
null
null
null
UTF-8
Java
false
false
651
java
package idsa; import java.util.Arrays; public class SelectionSort { public static int[] selectionSort(int[] A) { int temp, minIndex = 0; for (int i = 0; i < A.length-1; i++) { minIndex = i; for (int j = i+1; j < A.length; j++) { if (A[minIndex] > A[j]) { minIndex = j; } } temp = A[minIndex]; A[minIndex] = A[i]; A[i] = temp; } return A; } public static void main (String[] args) { int[] A = {8, 5, 9, 2, 4, 6, 3, 7, 1}; System.out.println("Array: " + Arrays.toString(A)); System.out.println("Result:" + Arrays.toString(selectionSort(A))); } }
b502a1fa65e387fc89724fe23ad63b151c8ecfdb
957bbba8c0ca902528094563d397cee0c50ba309
/app/src/main/java/com/leaugematchschedule/util/listener/DataReloader.java
43e16cce69c352d20e31d407289e98d18af44ad8
[]
no_license
Mihir3646/LeagueMatchSchedule
52c72a265834b8c3620bb0d0bc8953237bf77002
398f7a7d95fb49240a88bfaac456e3674a9ee27a
refs/heads/master
2021-04-26T22:56:34.952923
2018-03-05T10:47:36
2018-03-05T10:47:36
123,900,014
0
0
null
null
null
null
UTF-8
Java
false
false
191
java
package com.leaugematchschedule.util.listener; /** * Provides the method to reload the data in view (from database, API etc.. ) */ public interface DataReloader { void reloadData(); }
9354fcdbdfde969b15c4c7d075030409dc02bd42
de9a364f438112fd81f5c03f97fb6ad6877d2fe8
/app/src/main/java/ru/example/routeassistant/DAL/remoteDAO/IRouteEventApi.java
803c68c67d47ffbe620897d071fb849cf7548711
[]
no_license
Max-Petrov/software_lifecycle_mobile_android
1d244464194399d67cfa7da521f68ad0ec9a30ba
9ac413508a0494995ee0bd05b78eb8e963eaefee
refs/heads/master
2020-04-07T06:24:06.854547
2018-12-12T23:07:48
2018-12-12T23:07:48
158,133,531
0
0
null
2018-12-12T23:05:27
2018-11-18T22:33:41
Java
UTF-8
Java
false
false
529
java
package ru.kenguru.driverassistant.DAL.remoteDAO; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; import retrofit2.http.Query; import ru.kenguru.driverassistant.DAL.entities.RouteEvent; public interface IRouteEventApi { @POST("route_events") Call<Void> sendEvent(@Body RouteEvent routeEvent, @Query("device_id") long deviceId); @POST("route_events?list=true") Call<Void> sendEvents(@Body List<RouteEvent> routeEvents, @Query("device_id") long deviceId); }
978b7679e32448659eb303f8719832a347461be6
5c4d67123d2908d2965a8d50584ab71d07c64fd5
/MySlidingProject/src/com/ihateflyingbugs/kidsm/uploadphoto/AlbumNameAdapter.java
c31d522a59c0f76b1095f2b129bdc2b0b533d573
[ "Apache-2.0" ]
permissive
xxx4u/kidsm_for_android
cc38bd473dd14501995bc643a17e2db4112557ba
eaf8797ff6099dfdc58070fd92269f5bb75f2daa
refs/heads/master
2021-01-22T12:08:03.793851
2013-12-02T05:36:57
2013-12-02T05:36:57
15,223,379
1
0
null
null
null
null
UHC
Java
false
false
1,871
java
package com.ihateflyingbugs.kidsm.uploadphoto; import java.util.ArrayList; import com.ihateflyingbugs.kidsm.ImageMaker; import com.ihateflyingbugs.kidsm.R; import com.ihateflyingbugs.kidsm.gallery.Album; import com.ihateflyingbugs.kidsm.menu.Children; import android.content.Context; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class AlbumNameAdapter extends BaseAdapter { LayoutInflater mInflater; ArrayList<Album> arSrc; Context context; public AlbumNameAdapter(Context context, ArrayList<Album> arItem) { mInflater = (LayoutInflater)context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); arSrc = arItem; this.context = context; } public int getCount() { return arSrc.size(); } public Album getItem(int position) { return arSrc.get(position); } public long getItemId(int position) { return position; } // getView가 생성하는 뷰의 개수를 리턴한다. 항상 같은 뷰를 생성하면 1을 리턴한다. // 이 메서드에서 개수를 제대로 조사해 주지 않으면 다운된다. public int getViewTypeCount() { return 1; } public View getView(int position, View convertView, ViewGroup parent) { // 최초 호출이면 항목 뷰를 생성한다. // 타입별로 뷰를 다르게 디자인할 수 있으며 높이가 달라도 상관없다. if (convertView == null) { convertView = mInflater.inflate(R.layout.uploadphoto_spinner_item, parent, false); } TextView txt = (TextView)convertView.findViewById(R.id.albumlistname); txt.setText(arSrc.get(position).album_name); convertView.setTag(arSrc.get(position).album_srl); return convertView; } }
588aa8c77dedf2ef5241da739f59a330a0c57343
78b6f4f72e2517bf6430dd8e1be0877de0afa68c
/src/main/java/com/fungames/rockpapersheetapi/model/UserQueueModel.java
e87a5d154f965ae8f590d9e05e113cc8fd40be83
[]
no_license
akolesnikovmakeapp/rpsserverapi
01bec361a5118328a83ceb25bcf293025d5b237b
1403f5a9de6415a94777f0963640e6e7eb9aea16
refs/heads/master
2020-08-29T14:06:45.884686
2019-10-30T13:05:10
2019-10-30T13:05:10
218,055,368
0
0
null
null
null
null
UTF-8
Java
false
false
692
java
package com.fungames.rockpapersheetapi.model; import lombok.Getter; import lombok.Setter; import java.util.UUID; @Getter @Setter public class UserQueueModel { private static final int ABANDONED_TIME = 2 * 60 * 60 * 1000; private static final int ACTIVE_TIME = 700; private UUID id; private UUID roomId; private long timestamp; public UserQueueModel(){ id = UUID.randomUUID(); timestamp = System.currentTimeMillis(); } public boolean isActive(){ return System.currentTimeMillis() - timestamp < ACTIVE_TIME; } public boolean isUselessModel(){ return System.currentTimeMillis() - timestamp > ABANDONED_TIME; } }
dc1ab29a047fadb1bb95ff06fbd82ac03a41b83c
f718840716668c96ab4d908f191e1b81534fe9e0
/app/src/main/java/at/devfest/app/utils/Analytics.java
51da44c203d7d26450d504218cd5d02795ac60ad
[ "Apache-2.0" ]
permissive
DevFestVienna/devfest-vienna-app
beb2d1ea6f5f1bc95ca304d5c9aace55d30baa07
f34c22541c3d6b011a892663d39630381403d4ef
refs/heads/master
2021-01-12T11:37:08.979296
2017-11-17T20:08:40
2017-11-17T20:08:40
72,230,743
1
1
null
null
null
null
UTF-8
Java
false
false
508
java
package at.devfest.app.utils; /** * Created by helmuth on 19/08/16. * <p> * This interface specifies functions to log analytics events and user properties. */ public interface Analytics { public void logViewSession(int id, String title); public void logViewSpeaker(int id, String name); public void logViewSessionSpeaker(int id, String name); public void logViewScreen(String screen); public void logSelectSession(int id); public void setNotificationFlag(boolean value); }
9a9824c30c46b3c5278fbc9a196954a2fc61b13a
f99ac6c6569cf5437a7d94f539b5db1eff9335f8
/web-hsdb-site/src/main/java/ru/bmn/web/hsdb/site/controller/domain/form/UserSettingsForm.java
8cac474b2a68320df47a11e9c10284c29ed07db6
[ "BSD-2-Clause" ]
permissive
bmn85/web-hsdb-basic
59ead52c89d845e6a2ea9b69d2976b54098fc840
3d7c2e10c7760a5b3bdd2087d1bf9bd0c7473337
refs/heads/master
2020-04-12T03:10:25.419085
2017-08-26T20:34:40
2017-08-26T20:34:40
61,432,801
0
0
null
null
null
null
UTF-8
Java
false
false
1,157
java
package ru.bmn.web.hsdb.site.controller.domain.form; import javax.validation.constraints.Size; public class UserSettingsForm { @Size(min=1, max=32) private String currentPassword; @Size(min=1, max=32) private String newPassword; @Size(min=1, max=32) private String newPasswordConfirm; @Size(min=3, max=32) private String hearthpwnUserName; public String getNewPassword() { return newPassword; } public UserSettingsForm setNewPassword(String newPassword) { this.newPassword = newPassword; return this; } public String getHearthpwnUserName() { return hearthpwnUserName; } public UserSettingsForm setHearthpwnUserName(String hearthpwnUserName) { this.hearthpwnUserName = hearthpwnUserName; return this; } public String getNewPasswordConfirm() { return newPasswordConfirm; } public UserSettingsForm setNewPasswordConfirm(String newPasswordConfirm) { this.newPasswordConfirm = newPasswordConfirm; return this; } public String getCurrentPassword() { return currentPassword; } public UserSettingsForm setCurrentPassword(String currentPassword) { this.currentPassword = currentPassword; return this; } }
943b0d28b6f88cf0e44ab7af8a1eaa12ea83b59e
9b2a3151a7de6271f1618a482adbe4137aca6824
/Coj/java/2434 - Mathematician Ana/main.java
dcaaabc07ef89c70a6aba71deafbe9850572d18b
[]
no_license
LuisEnriqueSosaHernandez/Programas-coj-otros
4bb8f24b785144366ad4ebd65fc41571fec44f4f
ef24094e347e0d7b21a021cdd1e32954ff72a486
refs/heads/master
2020-04-05T14:36:04.355386
2017-07-19T20:34:56
2017-07-19T20:34:56
94,712,937
0
0
null
null
null
null
UTF-8
Java
false
false
639
java
import java.util.Scanner; import java.util.ArrayList; import java.math.BigInteger; public class main{ public static void main(String[]args){ Scanner l=new Scanner(System.in); ArrayList<Integer> total=new ArrayList<Integer>(); while(true){ int n=l.nextInt(); if(n!=0) total.add(n); else break; } for (int j=0;j<total.size();j++){ BigInteger ja=new BigInteger("1"); for(int y=0;y<=total.get(j);y++){ if(y==2 || y==3 ||y==5 || y==7) ja = ja.multiply(new BigInteger(y +"")); else if(y%2!=0&&y%3!=0&&y%5!=0&&y%7!=0) ja=ja.multiply(new BigInteger(y +"")); } System.out.println(ja); } } }
624fb9c93d65425da78d0f0582020c13e9cd7bc1
ffb5e58d999b7981d7857b464aa5e8c77371aa17
/springmvc/src/main/java/com/pack/springmvc/model/Employee.java
69d98df50189a7d46ceb529986f978f27cc09ffa
[]
no_license
prasathth/Train
3180de77a959f9ecf80572b63739562adc7a6fe8
a08c305e5cd31f7fc6e00d7555d84fe74c18b800
refs/heads/master
2022-12-22T07:36:07.004443
2019-07-31T03:05:56
2019-07-31T03:05:56
195,202,636
0
0
null
2022-12-16T00:47:06
2019-07-04T08:38:14
Java
UTF-8
Java
false
false
1,543
java
package com.pack.springmvc.model; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Range; public class Employee { @Range(min=1,message="minimum length is 1") private int id; @Size(min=2,message="min 2 character") private String name; private String password; //@NotEmpty(message="enter age") @Range(min=1) private int age; private double salary; public Employee(int id, String name, String password, int age, double salary) { super(); this.id = id; this.name = name; this.password = password; this.age = age; this.salary = salary; } public Employee(String name, String password, int age, double salary) { super(); this.name = name; this.password = password; this.age = age; this.salary = salary; } public Employee() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", password=" + password + "]"; } }
11280a33d9c8cd74c98c1b4bc8ee2905e4516792
3417287f0a244c3680db1363c6de5d5e0b71beab
/src/lists/LockFreeList.java
20d7ccdf5a623ba0543fe93868746da3436bb827
[]
no_license
claudioscheer/concurrent-producer-consumer
6380522bd8ebd2449b295fd83c47c5d2f966ce25
2569895387aa8808a8058295e3e63950bf868ae2
refs/heads/master
2022-09-12T08:51:19.744324
2020-05-28T12:10:17
2020-05-28T12:10:17
254,986,070
0
0
null
null
null
null
UTF-8
Java
false
false
5,059
java
/* * LockFreeList.java * * Created on January 4, 2006, 2:41 PM * Updated on May 19, 2020, 3:36 PM, by Claudio Scheer * * From "Multiprocessor Synchronization and Concurrent Data Structures", by Maurice Herlihy and Nir Shavit. * Copyright 2006 Elsevier Inc. All rights reserved. */ package lists; import java.util.concurrent.atomic.AtomicMarkableReference; import interfaces.GenericListInterface; /** * Lock-free List based on M. Michael's algorithm. * * @param T Item type. * @author Maurice Herlihy */ public class LockFreeList<T> implements GenericListInterface<T> { // First list node. private Node head; public LockFreeList() { this.head = new Node(Integer.MIN_VALUE); Node tail = new Node(Integer.MAX_VALUE); while (!head.next.compareAndSet(null, tail, false, false)) { } } /** * Add an element. * * @param item Element to add. * @return True iff element was not there already. */ public boolean add(T item) { int key = item.hashCode(); while (true) { // Find predecessor and curren entries. Window window = find(this.head, key); Node pred = window.pred, curr = window.curr; // Is the key present? if (curr.key == key) { return false; } else { // Splice in new node. Node node = new Node(item); node.next = new AtomicMarkableReference(curr, false); if (pred.next.compareAndSet(curr, node, false, false)) { return true; } } } } /** * Remove an element. * * @param item Element to remove. * @return True iff element was present. */ public boolean remove(T item) { int key = item.hashCode(); boolean snip; while (true) { // Find predecessor and curren entries. Window window = find(this.head, key); Node pred = window.pred, curr = window.curr; // Is the key present? if (curr.key != key) { return false; } else { // Snip out matching node. Node succ = curr.next.getReference(); snip = curr.next.compareAndSet(succ, succ, false, true); if (!snip) { continue; } pred.next.compareAndSet(curr, succ, false, false); return true; } } } /** * Test whether element is present. * * @param item Element to test. * @return True iff element is present. */ public boolean contains(T item) { boolean[] marked = { false }; int key = item.hashCode(); Node curr = head; while (curr.key < key) { curr = curr.next.getReference(); Node succ = curr.next.get(marked); } return (curr.key == key && !marked[0]); } @Override public int size() { Node pred = this.head; Node curr = pred.next.getReference(); int count = 0; while (curr.item != null) { ++count; pred = curr; curr = curr.next.getReference(); } return count; } /** * List Node. */ private class Node { // Actual item. T item; // Item's hash code. int key; // Next Node in list. AtomicMarkableReference<Node> next; /** * Constructor for usual Node. * * @param item Element in list. */ Node(T item) { this.item = item; this.key = item.hashCode(); this.next = new AtomicMarkableReference<Node>(null, false); } /** * Constructor for sentinel Node. * * @param key Should be min or max int value. */ Node(int key) { this.item = null; this.key = key; this.next = new AtomicMarkableReference<Node>(null, false); } } /** * Pair of adjacent list entries. */ class Window { // Earlier node. public Node pred; // Later node. public Node curr; Window(Node pred, Node curr) { this.pred = pred; this.curr = curr; } } /** * If element is present, returns Node and predecessor. If absent, returns Node * with least larger key. * * @param head Start of list. * @param key Key to search for. * @return If element is present, returns Node and predecessor. If absent, * returns Node with least larger key. */ public Window find(Node head, int key) { Node pred = null, curr = null, succ = null; boolean[] marked = { false }; boolean snip; retry: while (true) { pred = head; curr = pred.next.getReference(); while (true) { succ = curr.next.get(marked); while (marked[0]) { snip = pred.next.compareAndSet(curr, succ, false, false); if (!snip) { continue retry; } curr = succ; succ = curr.next.get(marked); } if (curr.key >= key) { return new Window(pred, curr); } pred = curr; curr = succ; } } } }
d01a0a131812d6c1d18f6361844c1f2738babb85
e9fe4d7603802f7df9ea8352a1df690924aec086
/ECommerceApplication/src/main/java/com/app/ecom/controller/UserController.java
bf505ae23bf774c91a341bd28c318587e68d182c
[]
no_license
jaykumar2192/Application
0a9b53a75c8847b5c87848f385d75cefc034ff1b
16d2fd12f079a92b1984794ae0c85d19852860d2
refs/heads/main
2023-01-07T13:45:15.807444
2020-11-05T06:37:03
2020-11-05T06:37:03
309,383,048
0
0
null
null
null
null
UTF-8
Java
false
false
2,708
java
package com.app.ecom.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.app.ecom.exception.UserException; import com.app.ecom.pojo.Categories; import com.app.ecom.pojo.Orders; import com.app.ecom.pojo.Products; import com.app.ecom.pojo.UserCartDetails; import com.app.ecom.pojo.Users; import com.app.ecom.pojo.UsersCart; import com.app.ecom.service.UserService; @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @GetMapping("/getProducts") public List<Products> getAllProducts() { return userService.getAllProducts(); } @GetMapping("/getProductsByName") public List<Products> getAllProducts(@RequestParam String productName) { return userService.getAllProducts(productName); } @PostMapping("/addToCart") public String addToCart(@RequestBody UsersCart userCart) throws UserException { String response = userService.addToCart(userCart); if (response != null) return response; throw new UserException("Error adding item to cart"); } @GetMapping("/getCartByUserId") public List<UserCartDetails> getCartByUserID(@RequestParam Integer userId) throws UserException { return userService.getCartByUserID(userId); } @GetMapping("/emptyCart") public String emptyUserCart(@RequestParam int userId) { String response = userService.emptyUserCart(userId); if (response != null) return response; throw new UserException("Error emptying user cart"); } @GetMapping("/processOrder") public String processOrder(@RequestParam int userId, @RequestParam String paymentInfo) throws UserException { String response = userService.processOrder(userId, paymentInfo); if (response != null) return response; throw new UserException("Error processing Order, please try again"); } @GetMapping("/getOrdersByUserId") public List<Orders> getOrdersByUserId(@RequestParam int userId) { return userService.getOrdersByUserId(userId); } @PostMapping("/createUser") public String createUser(@RequestBody Users user) { return userService.createUser(user); } @GetMapping("/getAllCategories") public List<Categories> getCartByUserID() throws UserException { return userService.getAllCategories(); } }
[ "TiaaUser@LAPTOP-4ML26RSJ" ]
TiaaUser@LAPTOP-4ML26RSJ
8d12555f74ac32dc1ee3148041e9af1ec288470b
004832e529873885f1559eb8c864384b3e1cda3f
/dist/gameserver/data/scripts/ai/HekatonPrime.java
4a3f93d5aa8c131db709dac3ac90f210b4ac5528
[]
no_license
wks1222/mobius-source
02323e79316eabd4ce7e5b29f8cd5749c930d098
325a49fa23035f4d529e5a34b809b83c68d19cad
refs/heads/master
2021-01-10T02:22:17.746138
2015-01-17T20:08:13
2015-01-17T20:08:13
36,601,733
1
0
null
null
null
null
UTF-8
Java
false
false
1,913
java
/* * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ai; import lineage2.gameserver.ai.Fighter; import lineage2.gameserver.model.Creature; import lineage2.gameserver.model.instances.NpcInstance; /** * @author Mobius * @version $Revision: 1.0 $ */ public final class HekatonPrime extends Fighter { private long _lastTimeAttacked; /** * Constructor for HekatonPrime. * @param actor NpcInstance */ public HekatonPrime(NpcInstance actor) { super(actor); } /** * Method onEvtSpawn. */ @Override protected void onEvtSpawn() { super.onEvtSpawn(); _lastTimeAttacked = System.currentTimeMillis(); } /** * Method thinkActive. * @return boolean */ @Override protected boolean thinkActive() { if ((_lastTimeAttacked + 600000) < System.currentTimeMillis()) { if (getActor().getMinionList().hasMinions()) { getActor().getMinionList().deleteMinions(); } getActor().deleteMe(); return true; } return false; } /** * Method onEvtAttacked. * @param attacker Creature * @param damage int */ @Override protected void onEvtAttacked(Creature attacker, int damage) { _lastTimeAttacked = System.currentTimeMillis(); super.onEvtAttacked(attacker, damage); } }
a444a5b68d74159c5a186a2d37aef6a70b2f4a72
53e0056c0696b3fbdc663567937f8cfd973d48cb
/src/main/java/org/docksidestage/mysql/dbflute/cbean/cq/ciq/WhiteVariantRelationReferrerCIQ.java
50749e77e9f0ebab3416f9ca7430344397851a65
[ "Apache-2.0" ]
permissive
dbflute-test/dbflute-test-dbms-mysql
cc22df45e25990f6f17b44dea38bd0888d464d48
096950eb304b0be8225ecebe90202ccfc27f6032
refs/heads/master
2023-08-10T23:56:02.770203
2023-07-19T18:43:53
2023-07-19T18:43:53
25,118,057
0
0
Apache-2.0
2022-06-21T07:16:23
2014-10-12T11:58:50
Java
UTF-8
Java
false
false
6,547
java
/* * Copyright 2004-2013 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.mysql.dbflute.cbean.cq.ciq; import java.util.Map; import org.dbflute.cbean.*; import org.dbflute.cbean.ckey.*; import org.dbflute.cbean.coption.ConditionOption; import org.dbflute.cbean.cvalue.ConditionValue; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.exception.IllegalConditionBeanOperationException; import org.docksidestage.mysql.dbflute.cbean.*; import org.docksidestage.mysql.dbflute.cbean.cq.bs.*; import org.docksidestage.mysql.dbflute.cbean.cq.*; /** * The condition-query for in-line of white_variant_relation_referrer. * @author DBFlute(AutoGenerator) */ public class WhiteVariantRelationReferrerCIQ extends AbstractBsWhiteVariantRelationReferrerCQ { // =================================================================================== // Attribute // ========= protected BsWhiteVariantRelationReferrerCQ _myCQ; // =================================================================================== // Constructor // =========== public WhiteVariantRelationReferrerCIQ(ConditionQuery referrerQuery, SqlClause sqlClause , String aliasName, int nestLevel, BsWhiteVariantRelationReferrerCQ myCQ) { super(referrerQuery, sqlClause, aliasName, nestLevel); _myCQ = myCQ; _foreignPropertyName = _myCQ.xgetForeignPropertyName(); // accept foreign property name _relationPath = _myCQ.xgetRelationPath(); // accept relation path _inline = true; } // =================================================================================== // Override about Register // ======================= protected void reflectRelationOnUnionQuery(ConditionQuery bq, ConditionQuery uq) { throw new IllegalConditionBeanOperationException("InlineView cannot use Union: " + bq + " : " + uq); } @Override protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col) { regIQ(k, v, cv, col); } @Override protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col, ConditionOption op) { regIQ(k, v, cv, col, op); } @Override protected void registerWhereClause(String wc) { registerInlineWhereClause(wc); } @Override protected boolean isInScopeRelationSuppressLocalAliasName() { if (_onClause) { throw new IllegalConditionBeanOperationException("InScopeRelation on OnClause is unsupported."); } return true; } // =================================================================================== // Override about Query // ==================== protected ConditionValue xgetCValueReferrerId() { return _myCQ.xdfgetReferrerId(); } public String keepReferrerId_ExistsReferrer_WhiteVariantRelationReferrerRefList(WhiteVariantRelationReferrerRefCQ sq) { throwIICBOE("ExistsReferrer"); return null; } public String keepReferrerId_NotExistsReferrer_WhiteVariantRelationReferrerRefList(WhiteVariantRelationReferrerRefCQ sq) { throwIICBOE("NotExistsReferrer"); return null; } public String keepReferrerId_SpecifyDerivedReferrer_WhiteVariantRelationReferrerRefList(WhiteVariantRelationReferrerRefCQ sq) { throwIICBOE("(Specify)DerivedReferrer"); return null; } public String keepReferrerId_QueryDerivedReferrer_WhiteVariantRelationReferrerRefList(WhiteVariantRelationReferrerRefCQ sq) { throwIICBOE("(Query)DerivedReferrer"); return null; } public String keepReferrerId_QueryDerivedReferrer_WhiteVariantRelationReferrerRefListParameter(Object vl) { throwIICBOE("(Query)DerivedReferrer"); return null; } protected ConditionValue xgetCValueVariantMasterId() { return _myCQ.xdfgetVariantMasterId(); } protected ConditionValue xgetCValueMasterTypeCode() { return _myCQ.xdfgetMasterTypeCode(); } protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String pp) { return null; } public String keepScalarCondition(WhiteVariantRelationReferrerCQ sq) { throwIICBOE("ScalarCondition"); return null; } public String keepSpecifyMyselfDerived(WhiteVariantRelationReferrerCQ sq) { throwIICBOE("(Specify)MyselfDerived"); return null;} public String keepQueryMyselfDerived(WhiteVariantRelationReferrerCQ sq) { throwIICBOE("(Query)MyselfDerived"); return null;} public String keepQueryMyselfDerivedParameter(Object vl) { throwIICBOE("(Query)MyselfDerived"); return null;} public String keepMyselfExists(WhiteVariantRelationReferrerCQ sq) { throwIICBOE("MyselfExists"); return null;} protected void throwIICBOE(String name) { throw new IllegalConditionBeanOperationException(name + " at InlineView is unsupported."); } // =================================================================================== // Very Internal // ============= // very internal (for suppressing warn about 'Not Use Import') protected String xinCB() { return WhiteVariantRelationReferrerCB.class.getName(); } protected String xinCQ() { return WhiteVariantRelationReferrerCQ.class.getName(); } }
949901cfff17fe3fc336d81163c966c8c1554a8b
b791cbad3be7d50067697bcd7bd3da956849f849
/src/com/ccsi/leetcode2/LC274HIndex.java
c6cb4f98c913c1b68583114465ec58773233d0bd
[]
no_license
liugxiami/Leetcode2017
999e7ebb78fcb94bcf38273d2ef2cd80247684cf
029326163564ec4ced4263dc085d2c1247a4a296
refs/heads/master
2021-01-01T16:44:25.617019
2019-03-13T03:27:45
2019-03-13T03:27:45
97,907,256
1
0
null
null
null
null
UTF-8
Java
false
false
2,718
java
package com.ccsi.leetcode2; import java.util.Arrays; import java.util.Random; /** * Created by gxliu on 2018/1/2. */ public class LC274HIndex { public static void main(String[] args) { int[] citations={0}; System.out.println(hIndex1(citations)); } //nlgn public static int hIndex(int[] citations){ if(citations==null||citations.length==0)return 0; int len=citations.length; //先对数组进行逆序排列,因为Arrays.sort()并无此功能,所以先将其乘以-1,升序排列,再乘以-1. for (int i = 0; i < len; i++) { citations[i]*=-1; } Arrays.sort(citations); for (int i = 0; i < len; i++) { citations[i]*=-1; } int min=1; int max=1; //关键步骤,h-index = max {min(citations[i],i)};贪心算法 for (int i = 0; i < len; i++) { min=Math.min(i+1,citations[i]); //发表的文章实际是以1-base的,所以是i+1; max=Math.max(max,min); } return max; } //method2 partition public static int hIndex1(int[] citations){ if(citations==null||citations.length==0)return 0; int len=citations.length; int start=0; int end=len-1; int h=0; while(start<=end){ int curr=partion(citations,start,end);//curr is index if(curr+1<=citations[curr]){ h=curr+1; start=curr+1; }else{ end=curr-1; } } return h; } //这个partion与正常的快排不一样的地方是:是大于等于pivot的在前面,小于pivot的在后面。 private static int partion(int[] citations,int start,int end){ if(start==end)return start; int ran=new Random().nextInt(end-start)+start; swap(citations,start,ran); int pivot=citations[start]; // int left=start; // int right=end+1; // while(true){ // while(++left<=end&&citations[left]>=pivot); // while(--right>=start&&citations[right]<pivot); // if(left>right)break; // swap(citations,left,right); // } // swap(citations,start,right); // return right; int head=start+1; for (int i = start+1; i <=end ; i++) { if(citations[i]>=pivot){ swap(citations,head++,i); } } swap(citations,start,head-1); return head-1; } private static void swap(int[] citations,int p,int q){ if(p==q)return; int temp=citations[p]; citations[p]=citations[q]; citations[q]=temp; } }
c24c34d408879eb2044a6729bee41e614e5200d9
395db7bc1c7c166ecfdfa092434634f907001c87
/ma-gpro-gs/ma-gpro-gs-domaine/src/main/java/com/gpro/consulting/tiers/gs/domaine/impl/ArticleEntreeDomaineImpl.java
e20827b7acec90b521474aeaa38c9ef5e100359a
[]
no_license
anouarbensaad/habillement
2c4aea85511bae5cef00b5b0fc200b8c1973219f
4d6c395300c3eff0a81b38d68d0e0873c130f7b6
refs/heads/master
2022-02-19T10:14:15.442154
2019-09-26T19:09:02
2019-09-26T19:09:02
204,194,945
0
0
null
null
null
null
UTF-8
Java
false
false
4,481
java
package com.gpro.consulting.tiers.gs.domaine.impl; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.gpro.consulting.tiers.commun.coordination.value.ArticleValue; import com.gpro.consulting.tiers.commun.coordination.value.RecherecheMulticritereArticleValue; import com.gpro.consulting.tiers.commun.coordination.value.ResultatRechecheArticleValue; import com.gpro.consulting.tiers.commun.service.IArticleService; import com.gpro.consulting.tiers.gs.coordination.value.ArticleEntreeValue; import com.gpro.consulting.tiers.gs.coordination.value.EntiteStockValue; import com.gpro.consulting.tiers.gs.coordination.value.ResultatRechecheArticleEntreeValue; import com.gpro.consulting.tiers.gs.domaine.IArticleEntreeDomaine; import com.gpro.consulting.tiers.gs.persitance.IEntiteStockPersistance; @Component public class ArticleEntreeDomaineImpl implements IArticleEntreeDomaine{ @Autowired IArticleService articleService; @Autowired IEntiteStockPersistance entiteStockPersistance; @Override public ResultatRechecheArticleEntreeValue rechercherArticleMultiCritere( RecherecheMulticritereArticleValue pRechercheArticleMulitCritere,Long idMagasin) { ResultatRechecheArticleEntreeValue vResultFinal=new ResultatRechecheArticleEntreeValue(); java.util.List <ArticleEntreeValue> list=new ArrayList<ArticleEntreeValue>(); ResultatRechecheArticleValue vResult=articleService.rechercherArticleMultiCritere(pRechercheArticleMulitCritere); if(vResult!=null && vResult.getNombreResultaRechercher()>0) { for (ArticleValue art:vResult.getArticleValues()){ ArticleEntreeValue artEntree=new ArticleEntreeValue(); artEntree.setId(art.getId()); artEntree.setRef(art.getRef()); artEntree.setDesignation(art.getDesignation()); artEntree.setSousFamille(art.getSousFamilleArtEntiteDesignation()); artEntree.setFamilleArticleDesignation(art.getFamilleArticleDesignation()); artEntree.setPmp(art.getPmp()); artEntree.setPu(art.getPu()); artEntree.setCodeFournisseur(art.getCodeFournisseur()); artEntree.setCouleur(art.getCouleur()); //artEntree.setPrixTotal(prixTotal); //TODO a changer integration de Lots // EntiteStockValue entiteStock=entiteStockPersistance.rechercheEntiteStockByArticleMagasin(art.getId(), idMagasin); // // if (entiteStock!=null){ // artEntree.setQuantiteActuelle(entiteStock.getQteActuelle()); // artEntree.setNombreConeAct(entiteStock.getConesActuel()); // artEntree.setNombreFinConeAct(entiteStock.getConesActuel()); // artEntree.setNombreRouleauxAct(entiteStock.getRouleauxActuel()); // artEntree.setEmplacement(entiteStock.getEmplacement()); // artEntree.setPoidsActuel(entiteStock.getPoidsActuel()); // } list.add(artEntree); } } vResultFinal.setNombreResultaRechercher(new Long (list.size())); vResultFinal.setArticleEntree(list); return vResultFinal; } @Override public ResultatRechecheArticleEntreeValue rechercherArticleMultiCritereFB( RecherecheMulticritereArticleValue pRechercheArticleMulitCritere) { ResultatRechecheArticleEntreeValue vResultFinal=new ResultatRechecheArticleEntreeValue(); java.util.List <ArticleEntreeValue> list=new ArrayList<ArticleEntreeValue>(); ResultatRechecheArticleValue vResult=articleService.rechercherArticleMultiCritere(pRechercheArticleMulitCritere); if(vResult!=null && vResult.getNombreResultaRechercher()>0) { for (ArticleValue art:vResult.getArticleValues()){ ArticleEntreeValue artEntree=new ArticleEntreeValue(); artEntree.setId(art.getId()); artEntree.setRef(art.getRef()); artEntree.setCodeFournisseur(art.getCodeFournisseur()); artEntree.setDesignation(art.getDesignation()); artEntree.setSousFamille(art.getSousFamilleArtEntiteDesignation()); artEntree.setFamilleArticleDesignation(art.getFamilleArticleDesignation()); artEntree.setPmp(art.getPmp()); artEntree.setPu(art.getPu()); //artEntree.setPrixTotal(prixTotal); //TODO a changer integration de Lots list.add(artEntree); } } vResultFinal.setNombreResultaRechercher(new Long (list.size())); vResultFinal.setArticleEntree(list); return vResultFinal; } }
80f76d94375edecf384497aec0a07c3b05e69b8b
dc3e53f15daff933c3cc6cdd3a5e0ee22e38035d
/service/src/main/java/cn/people/cms/modules/block/model/MenuItem.java
cc54788a5c00c774ce88ebb1c7afd975b5a2deac
[]
no_license
nickel-fang/cms
fcb8578a620acf9ee4aa645085a28f5692bd9c24
5f68840a2a41e44b0597fa4551efa7c5508be705
refs/heads/master
2022-12-20T16:50:10.819191
2020-03-05T07:57:14
2020-03-05T07:57:14
245,101,730
0
0
null
2022-12-09T01:19:50
2020-03-05T07:56:30
JavaScript
UTF-8
Java
false
false
1,298
java
package cn.people.cms.modules.block.model; import cn.people.cms.entity.BaseEntity; import cn.people.cms.modules.cms.model.Article; import lombok.Data; import lombok.NoArgsConstructor; import org.nutz.dao.entity.annotation.ColDefine; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Comment; import org.nutz.dao.entity.annotation.Table; import java.util.List; /** * Created by lml on 2018/4/13. */ @Data @NoArgsConstructor @Table("cms_block_relation_menu") public class MenuItem extends BaseEntity { @Column @Comment("频道编号") private Integer categoryId; @Column(hump = true) @Comment("是否自动导入") private Boolean isAutoImport; @Column @Comment("文章数量") private Integer count = 10; @Column @Comment("链接") private String url; @Column @Comment("名称") private String title; @Column @Comment("描述") private String description; @Column(hump = true) @Comment("原始名称") private String oriName; @Column @Comment("说明") @ColDefine(width = 1000) private String info; private List<MenuItem> children; private List<Article>items; public MenuItem(Integer categoryId){ this.categoryId = categoryId; } }
816ac2c45e94e64602d9e2018689477181197faa
d971441506631fd919d9a74bed14d10f8c75394d
/app/src/main/java/com/mediatek/factorymode/DeviceInfo.java
0f8165aa70e9c4dae506b848b2db357fb0e36d32
[]
no_license
sengeiou/FactoryModeA2
89885ac53b6984160db3fbed0c258f9de9804dc3
a8a08c87d44459792f85ee28a326209417d7f1c9
refs/heads/master
2021-10-11T13:20:43.204097
2019-01-26T12:20:20
2019-01-26T12:20:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,517
java
package com.mediatek.factorymode; import android.app.Activity; import android.os.IBinder; import android.os.Parcel; import android.os.SystemProperties; import android.os.ServiceManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.BatteryManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.LinearLayout; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; //import android.util.TpdFWNative; import android.app.ActionBar; import android.view.Gravity; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.util.regex.Pattern; public class DeviceInfo extends BaseTestActivity implements OnClickListener { public static final String TAG = "DeviceInfo"; private TextView mStatus; private TextView mLevel; private TextView mMeid; private TextView mImei; private TextView mSn; private TextView mWifiMac; private TextView mTpFWVersion; private TextView mRfInfo; private TextView mBaInfo; private LinearLayout mMeidLayout; private LinearLayout mTpFWLayout; private TextView mToEM; private Button mBtOK; private Button mBtFailed; private TelephonyManager telephony; private WifiManager mWifi; private WifiInfo mWifiInfo; private SharedPreferences mSp; private String meid; private String imei1, imei2, MotherBoader; private String snStr; private String meidStr = null; private String imeiStr = null; private String wifiMacStr = null; private String rfCheck; private IBinder binder; private static int TYPE_GET_PHASECHECK = 5; private final static String CUSTOM_VERSION="ro.build.display.id"; private final static String CUSTOM_VERSION_DATE="ro.build.date"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar.LayoutParams lp =new ActionBar.LayoutParams( android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); View mView = LayoutInflater.from(this).inflate(R.layout.title, new LinearLayout(this), false); TextView mTextView = (TextView) mView.findViewById(R.id.action_bar_title); getActionBar().setCustomView(mView, lp); mTextView.setText(getTitle()); getActionBar().setDisplayShowHomeEnabled(false); getActionBar().setDisplayShowTitleEnabled(false); getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getActionBar().setDisplayShowCustomEnabled(true); getActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); setContentView(R.layout.device_info); mSp = getSharedPreferences("FactoryMode", Context.MODE_PRIVATE); telephony = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); imei1 = telephony.getDeviceId(); imei2 = telephony.getDeviceId(); snStr = SystemProperties.get("ro.boot.serialno"); binder = ServiceManager.getService("phasechecknative"); rfCheck = getPhaseCheck(); MotherBoader = "DSL_L321_011"; // if(SystemProperties.getBoolean("ro.project.a873", false)) { // MotherBoader = "A873"; // } } @Override public void onResume() { super.onResume(); mStatus = (TextView) findViewById(R.id.status); mLevel = (TextView) findViewById(R.id.level); mMeid = (TextView) findViewById(R.id.meid); mImei = (TextView) findViewById(R.id.imei); mSn = (TextView) findViewById(R.id.sn); mWifiMac = (TextView) findViewById(R.id.wifi_mac); mRfInfo = (TextView) findViewById(R.id.rf_info); mBaInfo = (TextView) findViewById(R.id.battery_info); mMeidLayout = (LinearLayout) findViewById(R.id.device_meid_layout); if(!SystemProperties.getBoolean("ro.mtk_c2k_support", false)) { mMeidLayout.setVisibility(View.GONE); } mTpFWLayout = (LinearLayout) findViewById(R.id.tp_version_layout); mTpFWVersion = (TextView) findViewById(R.id.tp_version); if(FactoryModeFeatureOption.CENON_TP_FW_VERSION_SUPPORT) { mTpFWLayout.setVisibility(View.VISIBLE); mTpFWVersion.setText(getTpFWVersion()); } mToEM = (TextView) findViewById(R.id.to_engineer_mode); if("1".equals(SystemProperties.get("ro.mtk_gemini_support"))) { imei1 = SystemProperties.get("gsm.mtk.imei1"); imei2 = SystemProperties.get("gsm.mtk.imei2"); } else { imei1 = SystemProperties.get("gsm.mtk.imei1"); } if(SystemProperties.getBoolean("ro.mtk_c2k_support", false)) { meid = SystemProperties.get("gsm.mtk.meid"); } meidStr = meid; // imeiStr = (FactoryModeFeatureOption.MTK_GEMINI_SUPPORT) ? (imei1+"\n"+imei2): (imei1); imeiStr = telephony.getDeviceId(); mStatus.setText(MotherBoader); mLevel.setText(setTextValue(CUSTOM_VERSION)); mMeid.setText(meidStr); mImei.setText(imeiStr); mSn.setText(snStr); updateWifiAddress(); mRfInfo.setText(rfCheck); mBaInfo.setText(readInfo("/sys/class/power_supply/battery/battery_id")); mBtOK = (Button) findViewById(R.id.deviceinfo_bt_ok); mBtOK.setOnClickListener(this); mBtFailed = (Button) findViewById(R.id.deviceinfo_bt_failed); mBtFailed.setOnClickListener(this); mToEM.setOnClickListener(this); } public void onClick(View v) { if(v.getId() == mToEM.getId()) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.sprd.engineermode", "com.sprd.engineermode.EngineerModeActivity"); startActivity(intent); } else { Utils.SetPreferences(this, mSp, R.string.device_info, (v.getId() == mBtOK.getId()) ? AppDefine.FT_SUCCESS : AppDefine.FT_FAILED); finish(); } } private String setTextValue(String string){ String buildver = "unknow"; try { buildver = SystemProperties.get(string,""); return buildver; } catch (Exception e) { e.printStackTrace(); } return buildver; } private static String readFile(File fn) { FileReader f; int len; f = null; try { f = new FileReader(fn); String s = ""; char[] cbuf = new char[200]; while ((len = f.read(cbuf, 0, cbuf.length)) >= 0) { s += String.valueOf(cbuf, 0, len); } s = s.substring(2, s.length() - 1); //ellery add return s; } catch (IOException ex) { return "0"; } finally { if (f != null) { try { f.close(); } catch (IOException ex) { return "0"; } } } } public String readInfo(String path) { File file = new File(path); if(!file.exists()) { return "未知(文件不存在)"; } try { FileReader localFileReader = new FileReader(path); BufferedReader localBufferedReader = new BufferedReader( localFileReader, 300); String str2 = localBufferedReader.readLine(); Log.e("##sunshine##", "read = " + str2); if(null != str2) { return str2; } localBufferedReader.close(); } catch (IOException e) { e.printStackTrace(); return "错误"; } return "未知"; } private void updateWifiAddress() { mWifiInfo = mWifi.getConnectionInfo(); wifiMacStr = mWifiInfo.getMacAddress(); if(!mWifi.isWifiEnabled() && wifiMacStr.startsWith("02")) { mWifi.setWifiEnabled(true); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mWifiInfo = mWifi.getConnectionInfo(); wifiMacStr = mWifiInfo.getMacAddress(); mWifiMac.setText(wifiMacStr); mWifi.setWifiEnabled(false); } }, 5000); } else { mWifiMac.setText(wifiMacStr); } } private String getTpFWVersion() { // TpdFWNative.openDev(); byte[] buff = new byte[2]; // TpdFWNative.SetTpdFWVersion(buff); // TpdFWNative.closeDev(); Log.v(TAG, "TpVersion: " + buff[0] + ", " + buff[1]); return buff[0] + "." + buff[1]; } public String getPhaseCheck() { String result = null; try{ Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); binder.transact(TYPE_GET_PHASECHECK, data, reply, 0); Log.e(TAG, "transact SUCESS!!"); int testSign = reply.readInt(); int item = reply.readInt(); String stationName = reply.readString(); String []str = stationName.split(Pattern.quote("|")); String strTestSign = Integer.toBinaryString(testSign); String strItem = Integer.toBinaryString(item); char[] charSign = strTestSign.toCharArray(); char[] charItem = strItem.toCharArray(); StringBuffer sb = new StringBuffer(); Log.e(TAG, "strTestSign = " + strTestSign + " strItem = " + strItem); Log.e(TAG, "charSign = " + charSign + " charItem = " + charItem); Log.e(TAG, "str.length = " + str.length); for(int i=0; i<str.length; i++) { sb.append(str[i]+":"+StationTested(charSign[charSign.length-i-1], charItem[charItem.length-i-1])+"\n"); } result = sb.toString(); data.recycle(); reply.recycle(); }catch (Exception ex) { Log.e(TAG, "huasong Exception " + ex.getMessage()); result = "get phasecheck fail:" + ex.getMessage(); } return result; } private String StationTested(char testSign, char item) { Log.e(TAG, "testSign = " + testSign); Log.e(TAG, "item = " + item); if(testSign=='0' && item=='0') { return "PASS"; } if(testSign=='0' && item=='1'){ return "FAIL"; } return "UnTested"; } }
949f0d6ffe75bbf8498f37ab3a3bb14bd278edbe
e028f99ba470de1c5ecef073e8a408194ab12f03
/src/main/java/cn/ifxcode/bbs/service/QuickNavigationService.java
ce8428e80fc768e00fb2dd20ebd01b95974c716c
[]
no_license
dongbow/BBS
e4a8a29760dfb81c3aa86853cb68bb488673ad2a
500fc3cb7b9ff0d39e3c4ef81414629ef7b34e25
refs/heads/master
2020-12-02T15:11:34.534039
2017-07-21T12:16:16
2017-07-21T12:16:16
67,324,759
8
1
null
null
null
null
UTF-8
Java
false
false
579
java
package cn.ifxcode.bbs.service; import java.util.List; import cn.ifxcode.bbs.bean.Page; import cn.ifxcode.bbs.entity.QuickNavigation; public interface QuickNavigationService { public List<QuickNavigation> getAllQuickNavigations(); public List<QuickNavigation> getAllQuickNavigations(Page page); public int addQuick(String name, String link, String color, int sort, int status); public QuickNavigation getQuickNavigation(int id); public int updateQuick(int id, String name, String link, String color, int sort, int status); public int deleteQuick(String ids); }
72015a77d368f4884715b1aaf680c08a91517b4c
e66f52b1bfd9bf9a1d2b1382068370cf4f9f7336
/src/main/java/io/gearstack/props/ServiceProps.java
df664aa52c4208919de4c5eb221c8f0446a6dfd0
[]
no_license
clmoten84/gearstack-webapp
288e59d07168b08163299e4897024148516b2a53
2a0819a9c4c0cce500179753ff0060d37c0ee5c0
refs/heads/master
2021-03-30T17:51:12.067973
2018-03-21T03:36:46
2018-03-21T03:36:46
119,633,829
0
0
null
null
null
null
UTF-8
Java
false
false
255
java
package io.gearstack.props; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * ServiceProps * * Centralized configuration data utility class */ @Component public class ServiceProps { }
e1aa0a3f177879146b04c2432dfff7240ee0cce2
b2729da6628654bc64d2ca13dea0bcd4e01b29d9
/src/nasm/AsmPrinter.java
557174d6d1db66a27df1667750c3bea9953f2c91
[]
no_license
OolongQian/MQCompiler
f3954a220d3231cce2b095dbc19347d59108433e
9413232854e1262626e5d11f2e04dee8efb9af6d
refs/heads/master
2020-04-25T19:25:25.725111
2019-05-13T17:25:02
2019-05-13T17:25:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,043
java
package nasm; import ir.structure.StringLiteral; import nasm.inst.*; import nasm.reg.GlobalMem; import nasm.reg.PhysicalReg; import nasm.reg.Reg; import nasm.reg.StackMem; import java.io.*; import java.util.Map; import java.util.Set; import static config.Config.DEBUGPRINT_VREG; import static ir.Utility.unescape; import static nasm.Utils.FunctRenamer; import static nasm.Utils.StringLiteralRenamer; import static nasm.Utils.reg64TOreg32; public class AsmPrinter { protected PrintStream fout = System.out; /************************** Config ************************/ public void ConfigOutput (String filename) throws Exception { if (filename != null) fout = new PrintStream(new FileOutputStream(filename)); } /************************ Header print *********************************/ public void PrintHeaders (Map<String, AsmFunct> functs, Map<String, GlobalMem> globals) { for (String s : functs.keySet()) if (!s.equals("_init_")) fout.println("global " + FunctRenamer(s)); for (GlobalMem gMem : globals.values()) fout.println("global " + gMem.hintName); fout.println(); } public void PrintStringLabels (Set<StringLiteral> globals) { for (StringLiteral str : globals) { StringBuilder db = new StringBuilder(); String literal = unescape(str.val); // eliminate "" in head and tail. literal = literal.substring(1, literal.length() - 1); // print label id. as its label. _S_0: fout.println(StringLiteralRenamer(str.name) + ":"); // print string constant's length 8 bytes in advance. PrintLine("dq", Integer.toString(literal.length())); for (int i = 0; i < literal.length(); ++i) db.append(String.format("%02XH, ", (int) literal.charAt(i))); db.append("00H"); // string label name should be renamed. PrintLine("db", db.toString()); } } public void PrintGVar (Map<String, GlobalMem> globals) { for (GlobalMem g : globals.values()) { if (!g.isString) { fout.println(g.hintName + ":"); PrintLine("resq", "1"); } } } /************************* Extern print ******************************/ public void PrintExtern () { fout.println("extern memset"); fout.println("extern strcmp"); fout.println("extern snprintf"); fout.println("extern __stack_chk_fail"); fout.println("extern strcpy"); fout.println("extern malloc"); fout.println("extern strlen"); fout.println("extern memcpy"); fout.println("extern __isoc99_scanf"); fout.println("extern puts"); fout.println("extern strcmp"); fout.println("extern printf"); fout.println("extern __sprintf_chk"); fout.println("extern __printf_chk"); fout.println(); } /************************** Section print **********************/ public enum SECTION { text, data, bss } public void PrintSection (SECTION sec) { fout.println("SECTION ." + sec.name()); fout.println(); } /******************* Body print *************************/ public void Print (AsmFunct asmFunct) { fout.println(asmFunct.name + ":"); asmFunct.bbs.forEach(this::Print); } public void Print (AsmBB asmbb) { // comment basic block name. fout.println(asmbb.hintName + ":"); asmbb.insts.forEach(this::Print); fout.println(); } public void Print (Inst inst) { inst.AcceptPrint(this); } public void Print (Mov asm) { if (asm.extend) { assert asm.dst.GetText().equals("rax"); PrintLine("movzx", "rax", "al"); } else { if (DEBUGPRINT_VREG) PrintLine("mov", asm.dst.GetText(), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); else PrintLine("mov", asm.dst.GetText(), asm.src.GetText()); } } public void Print (Oprt asm) { if (DEBUGPRINT_VREG) { if (asm.op == Oprt.Op.IDIV) { assert asm.dst == null && asm.src != null; assert reg64TOreg32.containsKey(asm.src.GetText()); System.err.println(asm.src.GetText()); PrintLine(asm.op.name(), reg64TOreg32.get(asm.src.GetText()), ";", asm.src.GetVreg()); return; } if (asm.dst == null) PrintLine(asm.op.name(), asm.src.GetText(), ";", asm.src.GetVreg()); else if (asm.src == null) PrintLine(asm.op.name(), asm.dst.GetText(), ";", asm.dst.GetVreg()); else PrintLine(asm.op.name(), asm.dst.GetText(), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); return ; } if (asm.op == Oprt.Op.IDIV) { assert asm.dst == null && asm.src != null; assert reg64TOreg32.containsKey(asm.src.GetText()); System.err.println(asm.src.GetText()); PrintLine(asm.op.name(), reg64TOreg32.get(asm.src.GetText())); return; } if (asm.dst == null) PrintLine(asm.op.name(), asm.src.GetText()); else if (asm.src == null) PrintLine(asm.op.name(), asm.dst.GetText()); else PrintLine(asm.op.name(), asm.dst.GetText(), asm.src.GetText()); } public void Print (Jmp asm) { PrintLine(asm.jpOp.toString(), asm.label); } public void Print (Push asm) { if (DEBUGPRINT_VREG) PrintLine("push", asm.src.GetText(), ";", asm.src.GetVreg()); else PrintLine("push", asm.src.GetText()); } public void Print (Pop asm) { if (DEBUGPRINT_VREG) PrintLine("pop", asm.dst.GetText(), ";", asm.dst.GetVreg()); else PrintLine("pop", asm.dst.GetText()); } public void Print (Ret asm) { PrintLine("ret"); } public void Print (Cmp asm) { if (DEBUGPRINT_VREG) PrintLine("cmp", asm.dst.GetText(), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); else PrintLine("cmp", asm.dst.GetText(), asm.src.GetText()); // if jump directly, no need to do this routine. if (!asm.jmp) { String lowerReg = PhysicalReg.wide2lower.get(asm.flagReg.color.phyReg); String phyReg = asm.flagReg.color.phyReg.name(); PrintLine(asm.Cmp2Set(), lowerReg); PrintLine("movzx", phyReg, lowerReg); } } public void Print (Call asm) { PrintLine("call", asm.functName); } // can load from regs or globals public void Print (Load asm) { if (DEBUGPRINT_VREG) { if (asm.src instanceof Reg) PrintLine("mov", asm.dst.GetText(), String.format("[%s]", asm.src.GetText()), ";", asm.dst.GetVreg(), asm.src.GetVreg()); else PrintLine("mov", asm.dst.GetText(), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); return ; } if (asm.src instanceof Reg) PrintLine("mov", asm.dst.GetText(), String.format("[%s]", asm.src.GetText())); else PrintLine("mov", asm.dst.GetText(), asm.src.GetText()); } // can store into usual reg or globals. public void Print (Store asm) { if (DEBUGPRINT_VREG) { if (asm.dst instanceof Reg) PrintLine("mov", String.format("qword [%s]", asm.dst.GetText()), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); else PrintLine("mov", asm.dst.GetText(), asm.src.GetText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); return ; } if (asm.dst instanceof Reg) PrintLine("mov", String.format("qword [%s]", asm.dst.GetText()), asm.src.GetText()); else PrintLine("mov", asm.dst.GetText(), asm.src.GetText()); } public void Print (Lea asm) { if (DEBUGPRINT_VREG) { PrintLine("lea", asm.dst.GetText(), ((StackMem) asm.src).GetLeaText(), ";", asm.dst.GetVreg(), asm.src.GetVreg()); return ; } PrintLine("lea", asm.dst.GetText(), ((StackMem) asm.src).GetLeaText()); } public void Print (Msg asm) { fout.print("MSG\t " + asm.msg); } /******************* Utility ***************************/ protected void PrintLine(String inst, String... args) { StringBuilder line = new StringBuilder(String.format("\t\t%-8s", inst)); boolean comment = false; for (int i = 0; i < args.length; ++i) { if (args[i].equals(";")) comment = true; if (i != 0) { if (!comment) line.append(", "); else line.append(" ") ; } line.append(args[i]); } fout.println(line.toString()); } public void pasteLibFunction() throws IOException { File file = new File("lib/libO3.asm"); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { fout.println(line); } } }
9d046a9f33d6a03e461ce6691474c0a1de392395
b0c675243947807e065cec4149c6ec159c5db9af
/app/src/main/java/com/example/instagramclone/MainActivity.java
b5cf64dedf6d98ec69f59dd3988883afb382b11c
[ "Apache-2.0" ]
permissive
dev-lester94/InstagramClone
b310897d87bcd0eb7a36702458efa30c0626a2ff
12bcb4711672c6f32a3a6c0b6f7e9a7ae1a5003d
refs/heads/master
2023-03-12T01:13:08.134616
2021-03-03T03:42:08
2021-03-03T03:42:08
341,317,895
1
0
null
null
null
null
UTF-8
Java
false
false
2,641
java
package com.example.instagramclone; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import com.example.instagramclone.fragments.ComposeFragment; import com.example.instagramclone.fragments.PostsFragment; import com.example.instagramclone.fragments.ProfileFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity" ; final FragmentManager fragmentManager = getSupportFragmentManager(); private BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottomNavigationView = findViewById(R.id.bottomNavigation); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment; switch (item.getItemId()) { case R.id.action_home: // do something here //Toast.makeText(MainActivity.this, "Home", Toast.LENGTH_SHORT).show(); fragment = new PostsFragment(); break; case R.id.action_compose: // do something here //Toast.makeText(MainActivity.this, "Compose", Toast.LENGTH_SHORT).show(); fragment = new ComposeFragment(); break; case R.id.action_profile: // do something here //Toast.makeText(MainActivity.this, "Profile", Toast.LENGTH_SHORT).show(); default: fragment = new ProfileFragment(); break; } fragmentManager.beginTransaction().replace(R.id.flContainer, fragment).commit(); return true; } }); // Set default selection bottomNavigationView.setSelectedItemId(R.id.action_home); } }
1e552fc86da058a8f64b8749c6741e5f967f408f
c0d78db003e483b62cdcb2ba931d705f48b96b4d
/src/main/java/com/great/bench/StaffController.java
71a52e71692022fa526d0c75016742b6951ec9e2
[]
no_license
Kadavi/greatbench
27eb60746d28272b4770b569d6c5bd25a8688b17
2b49a0f1b05b8019ca7602903c782dd301416fcc
refs/heads/master
2016-09-06T17:23:58.295758
2014-04-14T05:08:14
2014-04-14T05:08:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,100
java
package com.great.bench; import com.mongodb.WriteResult; import com.stripe.Stripe; import com.stripe.model.Customer; import com.stripe.model.Plan; import com.stripe.model.Subscription; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @Controller public class StaffController { @Autowired SpringMailSender mail; @Autowired private MongoTemplate mango; @RequestMapping(value = "/api/register", method = RequestMethod.POST) public ModelAndView register(HttpServletRequest req, HttpServletResponse resp) throws Exception { String card = req.getParameter("card"); String email = req.getParameter("email"); String password = req.getParameter("password"); Map<String, Object> customerParams = new HashMap<String, Object>(); customerParams.put("email", email); boolean isEmailUnique = !(mango.exists(new Query(Criteria.where("email").is(email)), "user")); if (isEmailUnique) { customerParams.put("card", card); customerParams.put("description", "Customer for the basic plan."); Customer newMember = Customer.create(customerParams); if (newMember.getEmail().equalsIgnoreCase(email)) { Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", "basic"); newMember.createSubscription(subscriptionParams); mango.insert(new Member(email, password, newMember.getId(), "stripe", null, null)); } customerParams.put("status", "success"); } else { customerParams.put("status", "error"); } return new ModelAndView("hello", customerParams); } @RequestMapping(value = "/api/deactivate", method = RequestMethod.POST) public ModelAndView deactivate(HttpServletRequest req, HttpServletResponse resp) throws Exception { String email = req.getParameter("email"); // TODO: Validate token before critical operations Member member = mango.findOne(new Query(Criteria.where("email").is(email)), Member.class); Subscription subscription = Customer.retrieve(member.stripeId).cancelSubscription(); Map<String, Object> response = new HashMap<String, Object>(); response.put("status", subscription.getStatus() == "canceled" ? "success" : "error"); return new ModelAndView("hello", response); } @RequestMapping(value = "/api/reactivate", method = RequestMethod.POST) public ModelAndView reactivate(HttpServletRequest req, HttpServletResponse resp) throws Exception { String email = req.getParameter("email"); Member member = mango.findOne(new Query(Criteria.where("email").is(email)), Member.class); Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", "basic"); Subscription subscription = Customer.retrieve(member.stripeId).createSubscription(subscriptionParams); Map<String, Object> response = new HashMap<String, Object>(); response.put("status", subscription.getStatus() == "active" ? "success" : "error"); return new ModelAndView("hello", response); } @RequestMapping(value = "/api/login", method = RequestMethod.POST) public @ResponseBody String login(HttpServletRequest req, HttpServletResponse resp) throws Exception { String email = req.getParameter("email"); String password = req.getParameter("password"); String sessionToken = Member.randomSessionToken(); WriteResult mangoResult = mango.updateFirst(new Query(Criteria.where("email").is(email).and("password").is(password)), Update.update("sessionToken", sessionToken), Member.class); if (mangoResult.getN() > 0) { return "SessionToken: " + sessionToken; } else { return "error"; } } @RequestMapping(value = "/api/logout", method = RequestMethod.POST) public ModelAndView logout(HttpServletRequest req, HttpServletResponse resp) throws Exception { String email = req.getParameter("email"); WriteResult mangoResult = mango.updateFirst(new Query(Criteria.where("email").is(email)), Update.update("sessionToken", null), Member.class); Map<String, Object> response = new HashMap<String, Object>(); if (mangoResult.getN() > 0) { response.put("status", "success"); } else { response.put("status", "error"); } return new ModelAndView("hello", response); } @RequestMapping(value = "/api/forgot", method = RequestMethod.POST) public ModelAndView sendForgotPasswordEmail(HttpServletRequest req, HttpServletResponse resp) throws Exception { String email = req.getParameter("email"); WriteResult mangoResult = mango.updateFirst(new Query(Criteria.where("email").is(email)), Update.update("resetCode", Member.randomResetCode()), Member.class); mail.sendMail(new String[]{email}, "Welcome to the Banch", "Dear %s,<br><br>Confirm your membership. <a href=\"http://www.neopets.com/[email protected]&code=TREre53\">LOOK!</a><br><br>Thanks,<br/>%s", new String[]{"dahling", "Polite Stare"}); Map<String, Object> response = new HashMap<String, Object>(); response.put("status", "success"); return new ModelAndView("hello", response); } @RequestMapping(value = "/api/change", method = RequestMethod.POST) public ModelAndView changePassword(HttpServletRequest req, HttpServletResponse resp) throws Exception { Map<String, Object> response = new HashMap<String, Object>(); String email = req.getParameter("email"); String code = req.getParameter("code"); String password = req.getParameter("newPassword"); Member member = mango.findOne(new Query(Criteria.where("email").is(email).and("resetCode").is(code)), Member.class); try { member.password = password; member.sessionToken = Member.randomSessionToken(); member.resetCode = null; mango.save(member); response.put("sessionToken", member.sessionToken); response.put("status", "success"); } catch (Exception e) { response.put("status", "error"); e.printStackTrace(); } return new ModelAndView("hello", response); } static { Stripe.apiKey = "sk_test_cAefVlVMmXfcSKMZOKLhielX"; /* Making sure a 'basic' plan exists on Stripe if not already. */ try { Plan.retrieve("basic"); } catch (Exception e) { Map<String, Object> planParams = new HashMap<String, Object>(); planParams.put("amount", 200); planParams.put("interval", "month"); planParams.put("name", "Basic"); planParams.put("currency", "usd"); planParams.put("id", "basic"); try { Plan.create(planParams); } catch (Exception ignored) { ignored.printStackTrace(); } } } }
950924430eaa335635abf48372287e9b79c1d17e
eda98a2f8dda4efca7fa614ccf2e1c8d6853ab82
/src/com/game/render/fbo/psRender/EscapyPostIterative.java
44875add65a02d9ef08e9712ac81a81b9f7f2bf6
[ "Apache-2.0" ]
permissive
henryco/Escapy
8acc253c31f79b826594416a431df4233e3c03d1
6c6d65cdae20e9946df76035029b6520c7606e6c
refs/heads/master
2020-05-22T02:49:53.270042
2018-03-06T13:26:53
2018-03-06T13:26:53
63,279,340
11
1
null
null
null
null
UTF-8
Java
false
false
490
java
package com.game.render.fbo.psRender; import com.game.render.fbo.EscapyFBO; import com.game.utils.translationVec.TransVec; public interface EscapyPostIterative extends EscapyPostRenderer { /** * * @param fbo - frameBufferObject, <b>see: {@link EscapyFBO} </b> * @param translationVec - transtalion vector * @param times - 3 is default for void frameBuffer * @return fbo - same but filled fbo */ EscapyFBO postRender(EscapyFBO fbo, TransVec translationVec, int times); }
e61a0c3489f4ad06af2b3c96e0375e7fa5b229ea
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_2ea08ea9611585d9ea7c890f35ba03156092b28f/InternalResourceTempTopicFile/2_2ea08ea9611585d9ea7c890f35ba03156092b28f_InternalResourceTempTopicFile_t.java
5e2cc6ebb4be5354c5e4b2bcceb1a6f1f125df8e
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
8,048
java
package org.jboss.pressgang.ccms.restserver.webdav.resources.hierarchy.topics.topic.fields; import net.java.dev.webdav.jaxrs.xml.elements.*; import net.java.dev.webdav.jaxrs.xml.properties.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.jboss.pressgang.ccms.restserver.webdav.constants.WebDavConstants; import org.jboss.pressgang.ccms.restserver.webdav.resources.InternalResource; import org.jboss.pressgang.ccms.restserver.webdav.resources.MultiStatusReturnValue; import org.jboss.pressgang.ccms.restserver.webdav.resources.ByteArrayReturnValue; import org.jboss.pressgang.ccms.restserver.webdav.managers.DeleteManager; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.logging.Logger; import static javax.ws.rs.core.Response.Status.OK; /** * Handles access to temporary files. */ public class InternalResourceTempTopicFile extends InternalResource { private static final Logger LOGGER = Logger.getLogger(InternalResourceTempTopicFile.class.getName()); public InternalResourceTempTopicFile(@NotNull final UriInfo uriInfo, @NotNull final DeleteManager deleteManager, @Nullable final String remoteAddress, @NotNull final String path) { super(uriInfo, deleteManager, remoteAddress, path); } @Override public int write(@NotNull final byte[] contents) { LOGGER.info("ENTER InternalResourceTempTopicFile.write() " + getStringId()); try { final File directory = new java.io.File(WebDavConstants.TEMP_LOCATION); final String fileLocation = buildTempFileName(getStringId()); if (!directory.exists()) { directory.mkdirs(); } else if (!directory.isDirectory()) { directory.delete(); directory.mkdirs(); } final File file = new File(fileLocation); if (!file.exists()) { file.createNewFile(); } FileUtils.writeByteArrayToFile(file, contents); return Response.Status.NO_CONTENT.getStatusCode(); } catch (final IOException e) { } return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); } @Override public ByteArrayReturnValue get() { LOGGER.info("ENTER InternalResourceTempTopicFile.get() " + getStringId()); final String fileLocation = buildTempFileName(getStringId()); try { if (!exists(fileLocation)) { return new ByteArrayReturnValue(Response.Status.NOT_FOUND.getStatusCode(), null); } final FileInputStream inputStream = new FileInputStream(fileLocation); try { final byte[] fileContents = IOUtils.toByteArray(inputStream); return new ByteArrayReturnValue(Response.Status.OK.getStatusCode(), fileContents); } catch (final Exception ex) { } finally { try { inputStream.close(); } catch (final Exception ex) { } } } catch (final FileNotFoundException e) { return new ByteArrayReturnValue(Response.Status.NOT_FOUND.getStatusCode(), null); } return new ByteArrayReturnValue(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), null); } /** Temp files only live for a short period of time. This method determines if the temp file should be visible. */ public static boolean exists(@NotNull final String fileLocation) { return exists(new File(fileLocation)); } /** Temp files only live for a short period of time. This method determines if the temp file should be visible. */ public static boolean exists(@NotNull final File file) { if (file.exists()) { final Calendar window = Calendar.getInstance(); window.add(Calendar.SECOND, -WebDavConstants.TEMP_WINDOW); final Date lastModified = new Date(file.lastModified()); if (lastModified.before(window.getTime())) { file.delete(); } else { return true; } } return false; } @Override public int delete() { LOGGER.info("ENTER InternalResourceTempTopicFile.delete() " + getStringId()); final String fileLocation = buildTempFileName(getStringId()); final File file = new File(fileLocation); if (file.exists()) { file.delete(); return Response.Status.OK.getStatusCode(); } return Response.Status.NOT_FOUND.getStatusCode(); } @Override public MultiStatusReturnValue propfind(final int depth) { if (getUriInfo() == null) { throw new IllegalStateException("Can not perform propfind without uriInfo"); } try { final String fileLocation = InternalResourceTempTopicFile.buildTempFileName(getUriInfo().getPath()); final File file = new File(fileLocation); if (file.exists()) { final net.java.dev.webdav.jaxrs.xml.elements.Response response = getProperties(getUriInfo(), file, true); final MultiStatus st = new MultiStatus(response); return new MultiStatusReturnValue(207, st); } } catch (final NumberFormatException ex) { return new MultiStatusReturnValue(404); } return new MultiStatusReturnValue(404); } public static String buildTempFileName(final String path) { return WebDavConstants.TEMP_LOCATION + "/" + path.replace("/", "_"); } public static String buildWebDavFileName(final String path, final File file) { return file.getName().replaceFirst(path.replace("/", "_"), ""); } /** * @param uriInfo The uri that was used to access this resource * @param file The file that this content represents * @param local true if we are building the properties for the resource at the given uri, and false if we are building * properties for a child resource. * @return */ public static net.java.dev.webdav.jaxrs.xml.elements.Response getProperties(final UriInfo uriInfo, final File file, final boolean local) { final HRef hRef = local ? new HRef(uriInfo.getRequestUri()) : new HRef(uriInfo.getRequestUriBuilder().path(InternalResourceTempTopicFile.buildWebDavFileName(uriInfo.getPath(), file)).build()); final GetLastModified getLastModified = new GetLastModified(new Date(file.lastModified())); final GetContentType getContentType = new GetContentType(MediaType.APPLICATION_OCTET_STREAM); final GetContentLength getContentLength = new GetContentLength(file.length()); final DisplayName displayName = new DisplayName(file.getName()); final SupportedLock supportedLock = new SupportedLock(); final LockDiscovery lockDiscovery = new LockDiscovery(); final Prop prop = new Prop(getLastModified, getContentType, getContentLength, displayName, supportedLock, lockDiscovery); final Status status = new Status((javax.ws.rs.core.Response.StatusType) OK); final PropStat propStat = new PropStat(prop, status); final net.java.dev.webdav.jaxrs.xml.elements.Response davFile = new net.java.dev.webdav.jaxrs.xml.elements.Response(hRef, null, null, null, propStat); return davFile; } }
58a3da4eed702b015a401e824472e4778798949c
124212a1038bc37caa971f5c525bc0502b49fecf
/Test/AudioSession.java
5decb85db514c90df881eaa783c3d0b6b32b2fdb
[ "Apache-2.0" ]
permissive
PasanT9/VoCe
cfb810e5d5eb50abc19dc896db49bbad1703c7af
8f3b391beaf29234e5cca17f2b266297d786f68d
refs/heads/master
2020-07-08T01:05:41.504694
2019-10-22T00:55:42
2019-10-22T00:55:42
203,524,358
0
1
Apache-2.0
2019-10-15T05:56:13
2019-08-21T06:49:33
Java
UTF-8
Java
false
false
8,575
java
import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.*; public class AudioSession implements Runnable{ //Mixer settings boolean stopCapture = false; ByteArrayOutputStream byteArrayOutputStream; AudioFormat audioFormat; TargetDataLine targetDataLine; AudioInputStream audioInputStream; SourceDataLine sourceDataLine; //To change packet size static final int packetSize = 500; byte tempBuffer[] = new byte[packetSize+2]; //Connection data Session peer; //Unique id to each user([-500,500]) static byte userId; //Flags to stop recording static boolean sFlag = false; static boolean fFlag = false; //Flags to mute audio static boolean mFlag = false; //Extra data for testing int totalPackets = 0; int corruptedPackets = 0; public AudioSession(Session peer) { this.peer = peer; } public AudioSession(){ } //Thread to recieve User inputs public void run(){ Scanner read= new Scanner(System.in); System.out.println("Commands:"); System.out.println("\texit-Exit program"); System.out.println("\tmute-Stop hearing audio"); System.out.println("\tunmute-Undo mute operation"); while(true){ System.out.println("Wish to Speak(y):"); String input = read.nextLine(); if(input.equals("y")){ fFlag = true; } else if(input.equals("exit")){ System.exit(0); } else if(input.equals("mute")){ System.out.println("Mute: ON"); mFlag = true; } else if(input.equals("unmute")){ System.out.println("Mute: OFF"); mFlag = false; } } } private AudioFormat getAudioFormat() { float sampleRate = 16000.0F; int sampleSizeInBits = 16; int channels = 2; boolean signed = true; boolean bigEndian = true; return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); } public void captureAudio() { try { Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); //get available mixers Mixer mixer = null; for (int cnt = 0; cnt < mixerInfo.length; cnt++) { mixer = AudioSystem.getMixer(mixerInfo[cnt]); Line.Info[] lineInfos = mixer.getTargetLineInfo(); if (lineInfos.length >= 1 && lineInfos[0].getLineClass().equals(TargetDataLine.class)) { break; } } audioFormat = getAudioFormat(); //get the audio format DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat); targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo); targetDataLine.open(audioFormat); targetDataLine.start(); DataLine.Info dataLineInfo1 = new DataLine.Info(SourceDataLine.class, audioFormat); sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo1); sourceDataLine.open(audioFormat); sourceDataLine.start(); //Setting the maximum volume FloatControl control = (FloatControl)sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN); control.setValue(control.getMaximum()); } catch (LineUnavailableException e) { System.out.println(e); System.exit(0); } } //Capture packets public void capture() { //Update User Id getHashId(); System.out.println("User ID: "+ userId); byteArrayOutputStream = new ByteArrayOutputStream(); stopCapture = false; try { int seq = 0; //Thread to get user inputs Thread i = new Thread(new AudioSession()); i.start(); while (!stopCapture) { //Read from mic and store in temp buffer targetDataLine.read(tempBuffer, 0, tempBuffer.length-2); //capture sound into tempBuffer //Sequence numbers for packet [0,15] seq = seq%16; //To stop recording if(fFlag){ sFlag = true; fFlag = false; seq = 0; } //write recorded data to buffer tempBuffer[packetSize+1] = (byte)seq++; tempBuffer[packetSize] = userId; DatagramPacket packet = new DatagramPacket(tempBuffer, tempBuffer.length, peer.ip, peer.port); //Send whats in buffer to the server using sockets if(sFlag){ peer.socket.send(packet); } } byteArrayOutputStream.close(); } catch (IOException e) { System.out.println(e); System.exit(0); } } //Hash function that updates User ID private void getHashId(){ String ip=""; try{ ip = InetAddress.getLocalHost().toString(); } catch(Exception ex){ ex.printStackTrace(); } int port = (int)(Math.random()*500); int id = 1; for(int i=0;i<ip.length();++i) { id *= ((ip.charAt(i)+100)%500); } id *= port; if(id<0){ id *= (-1); } userId = (byte)(id%500); } //Play recieved audio pacekts public void play() { byteArrayOutputStream = new ByteArrayOutputStream(); stopCapture = false; try { //Data to remeber State of packets and user int seqNum= 0; int prevUserId = 0; //To test the program //--------------------------------------------------------------------------------------------- /*PacketOrder.packetLoss = 0; PacketOrder.outOfOrderPackets = 0; PacketOrder.bufferHits = 0; TimerTask task = new TimerTask(){ public void run(){ System.out.println("Total Packets: "+ totalPackets); System.out.println("Corrupted Packets: "+ corruptedPackets); System.out.println("Out Of Order Packets: "+ PacketOrder.outOfOrderPackets); System.out.println("Buffer Hits: "+ PacketOrder.bufferHits); totalPackets = 0; corruptedPackets = 0; PacketOrder.outOfOrderPackets = 0; PacketOrder.bufferHits = 0; } }; Timer timer = new Timer(); timer.schedule(task, new Date(), 1000*60);*/ //---------------------------------------------------------------------------------------------------- //Play non-stop while (!stopCapture) { byte[] buffer=new byte[packetSize+2]; DatagramPacket packet=new DatagramPacket(buffer, buffer.length); //Get data recieved to socket peer.socket0.receive(packet); buffer = packet.getData(); //Drop corrupted packets here if (buffer[packetSize+1] >= 0 && buffer[packetSize+1] <= 15) { //Get data from recieved bytes array int currentPacket = buffer[packetSize+1]; int speaker = buffer[packetSize]; //To stop playing your own records if(speaker != userId){ if(prevUserId == 0){ prevUserId = speaker; } else if(prevUserId != speaker){ seqNum = 0; prevUserId = speaker; } sFlag = false; } else if(speaker == userId){; sFlag = true; continue; } ++totalPackets; // System.out.println("Expected: "+seqNum+" "+"Arrived: "+currentPacket); //If packets are outof order if(currentPacket != seqNum) { //System.out.println("Not in Sequence"); //Create PacketOrder object get correct packet order PacketOrder packetData = new PacketOrder(seqNum,currentPacket, buffer); buffer = Arrays.copyOf(packetData.getOrder(),packetSize+2); if(buffer[packetSize+1]==-1) { seqNum = buffer[packetSize]; continue; } } PacketOrder.packetLoss = 0; //If not mute play audio if(!mFlag){ byteArrayOutputStream.write(buffer, 0, packetSize); //System.out.println("Playing("+speaker+"): "+buffer[packetSize+1]); sourceDataLine.write(buffer, 0, packetSize); //playing audio available in tempBuffer } //Updates sequence number ++seqNum; seqNum %= 16; //After 15 packets flush memory buffer if(seqNum == 0){ PacketOrder.memBufferToNull(); } } else{ ++corruptedPackets; } } byteArrayOutputStream.close(); } catch (IOException e) { System.out.println(e); System.exit(0); } } }
a1cef46d8d0d1ff2c21249302057262997b205ec
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project59/src/main/java/org/gradle/test/performance59_3/Production59_285.java
2dfe0d4a74ad46e12fcdc4843aea48683861eac5
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
305
java
package org.gradle.test.performance59_3; public class Production59_285 extends org.gradle.test.performance15_3.Production15_285 { private final String property; public Production59_285() { this.property = "foo"; } public String getProperty() { return property; } }
e474f16a8af48c51c0184d9b09f3e6580eb64617
a39ab7417d052a2938d55d4bf120ae14bfe1a417
/yingshi-android/app/src/main/java/com/yingshixiezuovip/yingshi/custom/PhonePayWindow.java
4f4848b198302399b13ec4a22a0916fe33a35f95
[]
no_license
SunshineWorkSpace/YzApp
c8f1a66085152b23ad9fdc62c9c6bca18292b370
0e7fbde54dea726282f5a41ab7d7e98605fa8e80
refs/heads/master
2020-04-03T19:45:11.198531
2019-02-13T06:42:00
2019-02-13T06:42:00
155,534,328
0
0
null
null
null
null
UTF-8
Java
false
false
2,466
java
package com.yingshixiezuovip.yingshi.custom; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.View; import android.widget.TextView; import com.yingshixiezuovip.yingshi.MainAuthenticationMoneyActivity; import com.yingshixiezuovip.yingshi.R; import com.yingshixiezuovip.yingshi.base.BasePopupWindow; import com.yingshixiezuovip.yingshi.model.DetailsPayModel; /** * Created by Resmic on 2017/8/10. * Email:[email protected] * <p> * <p> * describe: */ public class PhonePayWindow extends BasePopupWindow { private String phone; private String price; private int userID; public PhonePayWindow(Context mContext) { super(mContext, false, false); setWidthHeight(true, -1, -1); getView().setOnClickListener(this); findViewById(R.id.phonepay_btn_buy).setOnClickListener(this); findViewById(R.id.phonepay_btn_service).setOnClickListener(this); findViewById(R.id.phonepay_btn_cancel).setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.phonepay_btn_buy: intent = new Intent(mContext, MainAuthenticationMoneyActivity.class); intent.putExtra("pay_model", new DetailsPayModel(price, userID)); break; case R.id.phonepay_btn_service: intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); break; } cancel(); if (intent != null) { mContext.startActivity(intent); } } public void show(int type, String price, String phone, int userID) { if (type == 5 || type == 6) { ((TextView) findViewById(R.id.phonepay_btn_vip)).setText("学生用户无法直接看到用户电话"); } else { ((TextView) findViewById(R.id.phonepay_btn_vip)).setText("去认证成为会员"); } this.phone = phone; this.userID = userID; this.price = price; ((TextView) findViewById(R.id.phonepay_btn_buy)).setText("花费" + price + "元获取该用户电话"); ((TextView) findViewById(R.id.phonepay_btn_service)).setText("拨打客服电话:" + phone); super.show(); } @Override public View createView() { return View.inflate(mContext, R.layout.view_phone_pay_layout, null); } }
d2cf81e6ad9cd27844456b3d484969de0fbb0dfb
a10cedb2a57326ebe67961070322ef2ee77e5614
/IdeaProjects/Servlet/src/main/java/ua/goit/java/module_8/controller/AllTasks.java
f08d99ac697ee0babe271a3dedb06e31e050f863
[]
no_license
4594400/Servlet
19605569ac57e7b189b87cfca7f7733cd4f68373
796ec5e03b02373b6a1a7160937d3aa97fa18d19
refs/heads/master
2020-12-11T05:23:23.546802
2016-09-26T20:47:57
2016-09-26T20:47:57
68,372,966
0
0
null
null
null
null
UTF-8
Java
false
false
2,223
java
package ua.goit.java.module_8.controller; import ua.goit.java.module_8.Task; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet (name = "AllTasks", urlPatterns = {"/list"}) public class AllTasks extends HttpServlet{ private List<Task> tasks = new ArrayList<>(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Task task1 = new Task(1, "Read book", "Reading", true); Task task2 = new Task(2, "Write letter", "Writing", true); Task task3 = new Task(3, "Run 10 km", "Running", false); tasks.add(task1); tasks.add(task2); tasks.add(task3); request.setAttribute("tasks", tasks); HttpSession session = request.getSession(); session.setAttribute("tasks", tasks); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/jsp/tasks.jsp"); requestDispatcher.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Task task = new Task(); task.setId(Integer.parseInt(request.getParameter("id"))); task.setName(request.getParameter("name")); task.setCategory(request.getParameter("category")); task.setComplete(Boolean.parseBoolean(request.getParameter("complete"))); tasks.add(task); HttpSession session = request.getSession(); /*String username = (String)request.getAttribute("un");*/ session.setAttribute("tasks", tasks); response.sendRedirect("/jsp/tasks.jsp"); /*RequestDispatcher requestDispatcher = request.getRequestDispatcher("/jsp/tasks.jsp"); requestDispatcher.forward(request, response);*/ } @Override public void init() throws ServletException { } }
2b206ff4178cea70de8b125df1f27352e4705c3f
3119279587a4665213cc77cb94f1750ee8a73af2
/Spring/Spring-Patient/src/com/abc/service/PatientService.java
3466592f4a90efc8020fce3b3b7bd92a7aad00b5
[]
no_license
Scamprotection/CTS-Fullstack-Pune
55d03fef1f4b2726d92ac417a5ccd4a54d9a4ad8
12b8ce6ba4a61a0d378442736a2fd5c4645059d9
refs/heads/master
2022-03-23T21:16:19.031862
2017-11-16T12:59:51
2017-11-16T12:59:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
167
java
package com.abc.service; import com.abc.entitity.Patient; public interface PatientService { boolean savePatient(Patient patient); Patient findById(int patId); }
cfa4214a40e60c61f1230bfc588da1cb32b83d93
f827f0d5eff478e3391101a663e4b08f0b5cf873
/src/LAB5/ex_array2.java
718a36392c75e4518e963499698b853566b8c2a6
[]
no_license
chayut2/OOP
ee28ae800f535c59139c00f82f71429bdafdbe92
2679aa01fe7464f7bd7123331d591054174b7347
refs/heads/master
2023-03-15T22:59:55.672639
2021-03-09T04:18:32
2021-03-09T04:18:32
327,338,404
1
0
null
null
null
null
UTF-8
Java
false
false
1,490
java
package LAB5; import java.util.Scanner; public class ex_array2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num[] = new int[5]; num = inputData(num); DisplayArray(num); int total = totalValue(num); System.out.print("Total is value is : "+total); System.out.print("Average value in array : "+(total/num.length)); fineMax(num); fineMin(num); } private static void fineMin(int[] num) { int min = num[0]; for (int v:num) { if(min>v) min = v; } System.out.print("Minimum : "+min); } private static void fineMax(int[] num) { int max = num[0]; for (int v:num) { if(max>v) max = v; } System.out.print("Maximum : "+max); } private static int totalValue(int[] num) { int total = 0; for (int v:num) { total += v; } return total; } private static void DisplayArray(int[] num) { System.out.println("Data in array : "); for (int v:num) { System.out.print(v+" "); } } private static int[] inputData(int[] num) { Scanner sc = new Scanner(System.in); for (int i = 0; i < num.length; i++) { System.out.print("Enter Integer : "); num[i] = sc.nextInt(); } return num; } }