hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0372f2fff54d3f636b167d65591d7f06e69760 | 5,465 | java | Java | onos-master/core/api/src/main/java/org/onosproject/event/AbstractEventAccumulator.java | CingHu/test-onos | f1e9c98a7464a0eb4245bd1d652e468b8ee8cc79 | [
"Apache-2.0"
] | null | null | null | onos-master/core/api/src/main/java/org/onosproject/event/AbstractEventAccumulator.java | CingHu/test-onos | f1e9c98a7464a0eb4245bd1d652e468b8ee8cc79 | [
"Apache-2.0"
] | null | null | null | onos-master/core/api/src/main/java/org/onosproject/event/AbstractEventAccumulator.java | CingHu/test-onos | f1e9c98a7464a0eb4245bd1d652e468b8ee8cc79 | [
"Apache-2.0"
] | null | null | null | 32.724551 | 81 | 0.644831 | 1,412 | /*
* Copyright 2014 Open Networking Laboratory
*
* 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.onosproject.event;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Base implementation of an event accumulator. It allows triggering based on
* event inter-arrival time threshold, maximum batch life threshold and maximum
* batch size.
*/
public abstract class AbstractEventAccumulator implements EventAccumulator {
private Logger log = LoggerFactory.getLogger(AbstractEventAccumulator.class);
private final Timer timer;
private final int maxEvents;
private final int maxBatchMillis;
private final int maxIdleMillis;
private TimerTask idleTask = new ProcessorTask();
private TimerTask maxTask = new ProcessorTask();
private List<Event> events = Lists.newArrayList();
/**
* Creates an event accumulator capable of triggering on the specified
* thresholds.
*
* @param timer timer to use for scheduling check-points
* @param maxEvents maximum number of events to accumulate before
* processing is triggered
* @param maxBatchMillis maximum number of millis allowed since the first
* event before processing is triggered
* @param maxIdleMillis maximum number millis between events before
* processing is triggered
*/
protected AbstractEventAccumulator(Timer timer, int maxEvents,
int maxBatchMillis, int maxIdleMillis) {
this.timer = checkNotNull(timer, "Timer cannot be null");
checkArgument(maxEvents > 1, "Maximum number of events must be > 1");
checkArgument(maxBatchMillis > 0, "Maximum millis must be positive");
checkArgument(maxIdleMillis > 0, "Maximum idle millis must be positive");
this.maxEvents = maxEvents;
this.maxBatchMillis = maxBatchMillis;
this.maxIdleMillis = maxIdleMillis;
}
@Override
public void add(Event event) {
idleTask = cancelIfActive(idleTask);
events.add(event);
// Did we hit the max event threshold?
if (events.size() == maxEvents) {
maxTask = cancelIfActive(maxTask);
schedule(1);
} else {
// Otherwise, schedule idle task and if this is a first event
// also schedule the max batch age task.
idleTask = schedule(maxIdleMillis);
if (events.size() == 1) {
maxTask = schedule(maxBatchMillis);
}
}
}
// Schedules a new processor task given number of millis in the future.
private TimerTask schedule(int millis) {
TimerTask task = new ProcessorTask();
timer.schedule(task, millis);
return task;
}
// Cancels the specified task if it is active.
private TimerTask cancelIfActive(TimerTask task) {
if (task != null) {
task.cancel();
}
return task;
}
// Task for triggering processing of accumulated events
private class ProcessorTask extends TimerTask {
@Override
public void run() {
try {
idleTask = cancelIfActive(idleTask);
maxTask = cancelIfActive(maxTask);
processEvents(finalizeCurrentBatch());
} catch (Exception e) {
log.warn("Unable to process batch due to {}", e.getMessage());
}
}
}
// Demotes and returns the current batch of events and promotes a new one.
private synchronized List<Event> finalizeCurrentBatch() {
List<Event> toBeProcessed = events;
events = Lists.newArrayList();
return toBeProcessed;
}
/**
* Returns the backing timer.
*
* @return backing timer
*/
public Timer timer() {
return timer;
}
/**
* Returns the maximum number of events allowed to accumulate before
* processing is triggered.
*
* @return max number of events
*/
public int maxEvents() {
return maxEvents;
}
/**
* Returns the maximum number of millis allowed to expire since the first
* event before processing is triggered.
*
* @return max number of millis a batch is allowed to last
*/
public int maxBatchMillis() {
return maxBatchMillis;
}
/**
* Returns the maximum number of millis allowed to expire since the last
* event arrival before processing is triggered.
*
* @return max number of millis since the last event
*/
public int maxIdleMillis() {
return maxIdleMillis;
}
}
|
3e03730c8b2bd40ed487b8ba2f1e7e732ec44e45 | 482 | java | Java | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/sportcentre/daos/AssistantRepository.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/sportcentre/daos/AssistantRepository.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/sportcentre/daos/AssistantRepository.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | 40.166667 | 87 | 0.848548 | 1,413 | package es.upm.miw.apaw_practice.adapters.mongodb.sportcentre.daos;
import es.upm.miw.apaw_practice.adapters.mongodb.sportcentre.entities.AssistantEntity;
import es.upm.miw.apaw_practice.adapters.mongodb.sportcentre.entities.InstructorEntity;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;
public interface AssistantRepository extends MongoRepository<AssistantEntity, String> {
Optional<AssistantEntity> findById(String id);
}
|
3e0373701f53b5ae1628d2d2f741ff6281c2a2ce | 454 | java | Java | core/src/test/java/org/jfantasy/framework/util/ognl/OgnlBean.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-08-13T15:25:01.000Z | 2021-08-13T15:25:01.000Z | core/src/test/java/org/jfantasy/framework/util/ognl/OgnlBean.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | 1 | 2021-09-11T01:28:09.000Z | 2021-09-11T13:33:40.000Z | core/src/test/java/org/jfantasy/framework/util/ognl/OgnlBean.java | limaofeng/jfantasy-framework | 781246acef1b32ba3a20dc0d988dcd31df7e3e21 | [
"MIT"
] | null | null | null | 15.655172 | 41 | 0.77533 | 1,414 | package org.jfantasy.framework.util.ognl;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OgnlBean {
private String name;
private Long number;
private String[] names;
private List<String> listNames;
private List<OgnlBean> list;
private OgnlBean bean;
private OgnlBean[] array;
}
|
3e03746f5c24def2f90101bcc0f18d149568bfad | 7,526 | java | Java | Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationHandler.java | 0x6d696368/ghidra | 91e4fd7fb7e00a970c8f35f05c4590133937e174 | [
"Apache-2.0"
] | 3 | 2019-11-14T13:11:35.000Z | 2019-12-02T20:51:49.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationHandler.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 3 | 2019-07-17T22:51:04.000Z | 2019-12-04T05:43:56.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/relocation/ElfRelocationHandler.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 3 | 2019-12-02T13:36:50.000Z | 2019-12-04T05:40:12.000Z | 40.681081 | 94 | 0.735716 | 1,415 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.bin.format.elf.relocation;
import java.util.Map;
import ghidra.app.util.bin.format.elf.*;
import ghidra.app.util.importer.MessageLog;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.classfinder.ExtensionPoint;
import ghidra.util.exception.NotFoundException;
/**
* <code>ElfRelocationHandler</code> provides the base class for processor specific
* ELF relocation handlers.
*/
abstract public class ElfRelocationHandler implements ExtensionPoint {
abstract public boolean canRelocate(ElfHeader elf);
/**
* Relocation context for a specific Elf image and relocation table. The relocation context
* is used to process relocations and manage any data required to process relocations.
* @param loadHelper Elf load helper
* @param relocationTable Elf relocation table
* @param symbolMap Elf symbol placement map
*/
public ElfRelocationContext createRelocationContext(ElfLoadHelper loadHelper,
ElfRelocationTable relocationTable, Map<ElfSymbol, Address> symbolMap) {
return null;
}
/**
* Perform relocation fixup
* @param elfRelocationContext relocation context
* @param relocation ELF relocation
* @param relocationAddress relocation target address (fixup location)
* @throws MemoryAccessException memory access failure
* @throws NotFoundException required relocation data not found
*/
abstract public void relocate(ElfRelocationContext elfRelocationContext,
ElfRelocation relocation, Address relocationAddress)
throws MemoryAccessException, NotFoundException;
/**
* Generate error log entry and bookmark at relocationAddress indicating
* an unhandled relocation.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param symbolIndex associated symbol index within symbol table
* @param symbolName associated symbol name
* @param log import log
*/
public static void markAsUnhandled(Program program, Address relocationAddress, long type,
long symbolIndex, String symbolName, MessageLog log) {
symbolName = symbolName == null ? "<no name>" : symbolName;
log.appendMsg("Unhandled Elf Relocation: Type = " + type + " (0x" + Long.toHexString(type) +
") at " + relocationAddress + " (Symbol = " + symbolName + ")");
BookmarkManager bookmarkManager = program.getBookmarkManager();
bookmarkManager.setBookmark(relocationAddress, BookmarkType.ERROR,
"Relocation Type " + type,
"Unhandled Elf Relocation: Type = " + type + " (0x" + Long.toHexString(type) +
") Symbol = " + symbolName + " (0x" + Long.toHexString(symbolIndex) + ").");
}
/**
* Generate error log entry and bookmark at relocationAddress where
* import failed to transition block to initialized while processing relocation.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param symbolIndex associated symbol index within symbol table
* @param symbolName associated symbol name
* @param log import log
*/
public static void markAsUninitializedMemory(Program program, Address relocationAddress,
long type, long symbolIndex, String symbolName, MessageLog log) {
symbolName = symbolName == null ? "<no name>" : symbolName;
log.appendMsg("Unable to perform relocation: Type = " + type + " (0x" +
Long.toHexString(type) + ") at " + relocationAddress + " (Symbol = " + symbolName +
") - uninitialized memory");
BookmarkManager bookmarkManager = program.getBookmarkManager();
bookmarkManager.setBookmark(relocationAddress, BookmarkType.ERROR,
"Relocation_Type_" + type,
"Unable to perform relocation: Type = " + type + " (0x" + Long.toHexString(type) +
") Symbol = " + symbolName + " (0x" + Long.toHexString(symbolIndex) +
") - uninitialized memory.");
}
/**
* Generate error log entry and bookmark at relocationAddress where
* import failed to be applied.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param symbolName associated symbol name
* @param log import log
*/
public static void markAsError(Program program, Address relocationAddress, long type,
String symbolName, String msg, MessageLog log) {
markAsError(program, relocationAddress, type + " (0x" + Long.toHexString(type) + ")",
symbolName, msg, log);
}
/**
* Generate error log entry and bookmark at relocationAddress where
* import failed to be applied.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param symbolName associated symbol name
* @param msg additional error message
* @param log import log
*/
public static void markAsError(Program program, Address relocationAddress, String type,
String symbolName, String msg, MessageLog log) {
symbolName = symbolName == null ? "<no name>" : symbolName;
log.appendMsg("Elf Relocation Error: Type = " + type + " at " + relocationAddress +
", Symbol = " + symbolName + ": " + msg);
BookmarkManager bookmarkManager = program.getBookmarkManager();
bookmarkManager.setBookmark(relocationAddress, BookmarkType.ERROR, "Relocation_" + type,
"Elf Relocation Error: Symbol = " + symbolName + ": " + msg);
}
/**
* Generate warning log entry and bookmark at relocationAddress where
* import issue occurred.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param msg message associated with warning
* @param log import log
*/
public static void markAsWarning(Program program, Address relocationAddress, String type,
String msg, MessageLog log) {
markAsWarning(program, relocationAddress, type, null, 0, msg, log);
}
/**
* Generate warning log entry and bookmark at relocationAddress where
* import issue occurred.
* @param program
* @param relocationAddress relocation address to be bookmarked
* @param type relocation type
* @param symbolName symbol name
* @param symbolIndex symbol index
* @param msg message associated with warning
* @param log import log
*/
public static void markAsWarning(Program program, Address relocationAddress, String type,
String symbolName, long symbolIndex, String msg, MessageLog log) {
symbolName = symbolName == null ? "<no name>" : symbolName;
log.appendMsg("Elf Relocation Warning: Type = " + type + " at " + relocationAddress +
", Symbol = " + symbolName + ": " + msg);
BookmarkManager bookmarkManager = program.getBookmarkManager();
bookmarkManager.setBookmark(relocationAddress, BookmarkType.WARNING,
"Relocation_Type_" + type,
"Unhandled Elf relocation ("+type+") at address: " + relocationAddress +
". Symbol = " + symbolName + " (" + Long.toHexString(symbolIndex) + ")" +
". " + msg);
}
}
|
3e03749e561cac86dbcec2f824566104f185eb5c | 9,887 | java | Java | sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java | JasonBeiJing/sharding-sphere | c502c7a1b8f7c16a438ee43957fe8f4a3290d6d6 | [
"Apache-2.0"
] | 1 | 2018-08-20T15:06:33.000Z | 2018-08-20T15:06:33.000Z | sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java | JasonBeiJing/sharding-sphere | c502c7a1b8f7c16a438ee43957fe8f4a3290d6d6 | [
"Apache-2.0"
] | null | null | null | sharding-core/src/test/java/io/shardingsphere/core/optimizer/InsertOptimizeEngineTest.java | JasonBeiJing/sharding-sphere | c502c7a1b8f7c16a438ee43957fe8f4a3290d6d6 | [
"Apache-2.0"
] | null | null | null | 64.201299 | 142 | 0.758268 | 1,416 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.core.optimizer;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import io.shardingsphere.core.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.core.optimizer.condition.ShardingConditions;
import io.shardingsphere.core.optimizer.insert.InsertOptimizeEngine;
import io.shardingsphere.core.optimizer.insert.InsertShardingCondition;
import io.shardingsphere.core.parsing.parser.context.condition.AndCondition;
import io.shardingsphere.core.parsing.parser.context.condition.Column;
import io.shardingsphere.core.parsing.parser.context.condition.Condition;
import io.shardingsphere.core.parsing.parser.context.insertvalue.InsertValue;
import io.shardingsphere.core.parsing.parser.context.table.Table;
import io.shardingsphere.core.parsing.parser.expression.SQLPlaceholderExpression;
import io.shardingsphere.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingsphere.core.parsing.parser.token.InsertValuesToken;
import io.shardingsphere.core.parsing.parser.token.TableToken;
import io.shardingsphere.core.routing.router.sharding.GeneratedKey;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.core.yaml.sharding.YamlShardingConfiguration;
import io.shardingsphere.core.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.core.optimizer.condition.ShardingConditions;
import io.shardingsphere.core.optimizer.insert.InsertOptimizeEngine;
import io.shardingsphere.core.optimizer.insert.InsertShardingCondition;
import io.shardingsphere.core.parsing.parser.context.condition.AndCondition;
import io.shardingsphere.core.parsing.parser.context.condition.Column;
import io.shardingsphere.core.parsing.parser.context.condition.Condition;
import io.shardingsphere.core.parsing.parser.context.insertvalue.InsertValue;
import io.shardingsphere.core.parsing.parser.context.table.Table;
import io.shardingsphere.core.parsing.parser.expression.SQLPlaceholderExpression;
import io.shardingsphere.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingsphere.core.parsing.parser.token.InsertValuesToken;
import io.shardingsphere.core.parsing.parser.token.TableToken;
import io.shardingsphere.core.routing.router.sharding.GeneratedKey;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.core.yaml.sharding.YamlShardingConfiguration;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
public final class InsertOptimizeEngineTest {
private ShardingRule shardingRule;
private InsertStatement insertStatement;
private List<Object> parameters;
@Before
public void setUp() throws IOException {
URL url = InsertOptimizeEngineTest.class.getClassLoader().getResource("yaml/optimize-rule.yaml");
Preconditions.checkNotNull(url, "Cannot found rewrite rule yaml configuration.");
YamlShardingConfiguration yamlShardingConfig = YamlShardingConfiguration.unmarshal(new File(url.getFile()));
shardingRule = yamlShardingConfig.getShardingRule(yamlShardingConfig.getDataSources().keySet());
insertStatement = new InsertStatement();
insertStatement.getTables().add(new Table("t_order", Optional.<String>absent()));
insertStatement.setParametersIndex(4);
insertStatement.setInsertValuesListLastPosition(45);
insertStatement.getSqlTokens().add(new TableToken(12, "t_order"));
insertStatement.getSqlTokens().add(new InsertValuesToken(39, "t_order"));
AndCondition andCondition1 = new AndCondition();
andCondition1.getConditions().add(new Condition(new Column("user_id", "t_order"), new SQLPlaceholderExpression(0)));
insertStatement.getConditions().getOrCondition().getAndConditions().add(andCondition1);
AndCondition andCondition2 = new AndCondition();
andCondition2.getConditions().add(new Condition(new Column("user_id", "t_order"), new SQLPlaceholderExpression(2)));
insertStatement.getConditions().getOrCondition().getAndConditions().add(andCondition2);
insertStatement.getInsertValues().getInsertValues().add(new InsertValue("(?, ?)", 2));
insertStatement.getInsertValues().getInsertValues().add(new InsertValue("(?, ?)", 2));
parameters = new ArrayList<>(4);
parameters.add(10);
parameters.add("init");
parameters.add(11);
parameters.add("init");
}
@Test
public void assertOptimizeWithGeneratedKey() {
GeneratedKey generatedKey = new GeneratedKey(new Column("order_id", "t_order"));
generatedKey.getGeneratedKeys().add(1);
generatedKey.getGeneratedKeys().add(2);
ShardingConditions actual = new InsertOptimizeEngine(shardingRule, insertStatement, parameters, generatedKey).optimize();
assertFalse(actual.isAlwaysFalse());
assertThat(actual.getShardingConditions().size(), is(2));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().size(), is(3));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().size(), is(3));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().get(0), CoreMatchers.<Object>is(10));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().get(1), CoreMatchers.<Object>is("init"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().get(2), CoreMatchers.<Object>is(1));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().get(0), CoreMatchers.<Object>is(11));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().get(1), CoreMatchers.<Object>is("init"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().get(2), CoreMatchers.<Object>is(2));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getInsertValueExpression(), is("(?, ?, ?)"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getInsertValueExpression(), is("(?, ?, ?)"));
assertThat(actual.getShardingConditions().get(0).getShardingValues().size(), is(2));
assertThat(actual.getShardingConditions().get(1).getShardingValues().size(), is(2));
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(0).getShardingValues().get(0), 1);
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(0).getShardingValues().get(1), 10);
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(1).getShardingValues().get(0), 2);
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(1).getShardingValues().get(1), 11);
}
@Test
public void assertOptimizeWithoutGeneratedKey() {
insertStatement.setGenerateKeyColumnIndex(1);
ShardingConditions actual = new InsertOptimizeEngine(shardingRule, insertStatement, parameters, null).optimize();
assertFalse(actual.isAlwaysFalse());
assertThat(actual.getShardingConditions().size(), is(2));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().size(), is(2));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().size(), is(2));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().get(0), CoreMatchers.<Object>is(10));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getParameters().get(1), CoreMatchers.<Object>is("init"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().get(0), CoreMatchers.<Object>is(11));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getParameters().get(1), CoreMatchers.<Object>is("init"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(0)).getInsertValueExpression(), is("(?, ?)"));
assertThat(((InsertShardingCondition) actual.getShardingConditions().get(1)).getInsertValueExpression(), is("(?, ?)"));
assertThat(actual.getShardingConditions().get(0).getShardingValues().size(), is(1));
assertThat(actual.getShardingConditions().get(1).getShardingValues().size(), is(1));
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(0).getShardingValues().get(0), 10);
assertShardingValue((ListShardingValue) actual.getShardingConditions().get(1).getShardingValues().get(0), 11);
}
private void assertShardingValue(final ListShardingValue actual, final int expected) {
assertThat(actual.getValues().size(), is(1));
assertThat((int) actual.getValues().iterator().next(), is(expected));
}
}
|
3e0374d94cc6b3bef13b4ea96ce96edebabd46ad | 1,607 | java | Java | viewers/restfulobjects/viewer/src/main/java/org/apache/isis/viewer/restfulobjects/viewer/resources/ResourceDescriptor.java | ecpnv-devops/isis | aeda00974e293e2792783090360b155a9d1a6624 | [
"Apache-2.0"
] | 665 | 2015-01-01T06:06:28.000Z | 2022-03-27T01:11:56.000Z | viewers/restfulobjects/viewer/src/main/java/org/apache/isis/viewer/restfulobjects/viewer/resources/ResourceDescriptor.java | jalexmelendez/isis | ddf3bd186cad585b959b7f20d8c9ac5e3f33263d | [
"Apache-2.0"
] | 176 | 2015-02-07T11:29:36.000Z | 2022-03-25T04:43:12.000Z | viewers/restfulobjects/viewer/src/main/java/org/apache/isis/viewer/restfulobjects/viewer/resources/ResourceDescriptor.java | jalexmelendez/isis | ddf3bd186cad585b959b7f20d8c9ac5e3f33263d | [
"Apache-2.0"
] | 337 | 2015-01-02T03:01:34.000Z | 2022-03-21T15:56:28.000Z | 33.479167 | 96 | 0.742999 | 1,417 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.isis.viewer.restfulobjects.viewer.resources;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.viewer.restfulobjects.applib.RepresentationType;
import org.apache.isis.viewer.restfulobjects.rendering.service.RepresentationService;
import lombok.Value;
/**
*
* @since 2.0
*/
@Value(staticConstructor = "of")
public class ResourceDescriptor {
RepresentationType representationType;
Where where;
RepresentationService.Intent intent;
public static ResourceDescriptor generic(Where where, RepresentationService.Intent intent) {
return of(RepresentationType.GENERIC, where, intent);
}
public static ResourceDescriptor empty() {
// in support of testing
return of(null, null, null);
}
}
|
3e03753687f1c2a3b869390361668af9ccb8f8a5 | 1,720 | java | Java | src/main/java/bdv/TransformEventHandlerFactory.java | theazgra/bigdataviewer-core | 7ee89b472b4b66414d0a77bb6327dafb5481f5f5 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/bdv/TransformEventHandlerFactory.java | theazgra/bigdataviewer-core | 7ee89b472b4b66414d0a77bb6327dafb5481f5f5 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/bdv/TransformEventHandlerFactory.java | theazgra/bigdataviewer-core | 7ee89b472b4b66414d0a77bb6327dafb5481f5f5 | [
"BSD-2-Clause"
] | null | null | null | 40 | 79 | 0.756395 | 1,418 | /*
* #%L
* BigDataViewer core classes with minimal dependencies.
* %%
* Copyright (C) 2012 - 2020 BigDataViewer developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 HOLDERS 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.
* #L%
*/
package bdv;
/**
* Factory for {@code TransformEventHandler}.
*
* @author Tobias Pietzsch
*/
public interface TransformEventHandlerFactory
{
/**
* Create a new {@code TransformEventHandler}.
*/
TransformEventHandler create( TransformState transformState );
}
|
3e03753ebf31b2bc9a5c2c71e020a2c06ee98b97 | 5,172 | java | Java | artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java | Danielzhulin/activemq-artemis | fe42fd9155929a30e4bf4e42b5a971fbb4b313e1 | [
"Apache-2.0"
] | 868 | 2015-05-07T07:38:19.000Z | 2022-03-22T08:36:33.000Z | artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java | Danielzhulin/activemq-artemis | fe42fd9155929a30e4bf4e42b5a971fbb4b313e1 | [
"Apache-2.0"
] | 2,100 | 2015-04-29T15:29:35.000Z | 2022-03-31T20:21:54.000Z | artemis-protocols/artemis-amqp-protocol/src/test/java/org/apache/activemq/artemis/protocol/amqp/util/NettyWritableTest.java | qihongxu/activemq-artemis | b80a78d885e2568af41fc133b0185399385eda0c | [
"Apache-2.0"
] | 967 | 2015-05-03T14:28:27.000Z | 2022-03-31T11:53:21.000Z | 29.554286 | 100 | 0.679041 | 1,419 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.activemq.artemis.protocol.amqp.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.apache.qpid.proton.codec.ReadableBuffer;
import org.junit.Test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/**
* Tests for behavior of NettyWritable
*/
public class NettyWritableTest {
@Test
public void testGetBuffer() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertSame(buffer, writable.getByteBuf());
}
@Test
public void testLimit() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(buffer.capacity(), writable.limit());
}
@Test
public void testRemaining() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(buffer.maxCapacity(), writable.remaining());
writable.put((byte) 0);
assertEquals(buffer.maxCapacity() - 1, writable.remaining());
}
@Test
public void testHasRemaining() {
ByteBuf buffer = Unpooled.buffer(100, 100);
NettyWritable writable = new NettyWritable(buffer);
assertTrue(writable.hasRemaining());
writable.put((byte) 0);
assertTrue(writable.hasRemaining());
buffer.writerIndex(buffer.maxCapacity());
assertFalse(writable.hasRemaining());
}
@Test
public void testGetPosition() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(0, writable.position());
writable.put((byte) 0);
assertEquals(1, writable.position());
}
@Test
public void testSetPosition() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(0, writable.position());
writable.position(1);
assertEquals(1, writable.position());
}
@Test
public void testPutByteBuffer() {
ByteBuffer input = ByteBuffer.allocate(1024);
input.put((byte) 1);
input.flip();
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(0, writable.position());
writable.put(input);
assertEquals(1, writable.position());
}
@Test
public void testPutByteBuf() {
ByteBuf input = Unpooled.buffer();
input.writeByte((byte) 1);
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(0, writable.position());
writable.put(input);
assertEquals(1, writable.position());
}
@Test
public void testPutReadableBuffer() {
doPutReadableBufferTestImpl(true);
doPutReadableBufferTestImpl(false);
}
@Test
public void testPutReadableBufferWithOffsetAndNonZeroPosition() {
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
ByteBuffer source = ByteBuffer.allocate(20);
source.put(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19});
source.position(5);
source.limit(10);
writable.put(source);
assertEquals(5, writable.position());
assertEquals(5, buffer.readableBytes());
byte[] check = new byte[5];
buffer.readBytes(check);
assertTrue(Arrays.equals(new byte[] {5, 6, 7, 8, 9}, check));
}
private void doPutReadableBufferTestImpl(boolean readOnly) {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte) 1);
buf.flip();
if (readOnly) {
buf = buf.asReadOnlyBuffer();
}
ReadableBuffer input = new ReadableBuffer.ByteBufferReader(buf);
if (readOnly) {
assertFalse("Expected buffer not to hasArray()", input.hasArray());
} else {
assertTrue("Expected buffer to hasArray()", input.hasArray());
}
ByteBuf buffer = Unpooled.buffer(1024);
NettyWritable writable = new NettyWritable(buffer);
assertEquals(0, writable.position());
writable.put(input);
assertEquals(1, writable.position());
}
}
|
3e0375843fc32b5d052c56121fcc9c9de463a1b1 | 701 | java | Java | src/calculadora/domain/Calculo.java | GabrielMochi/calculadora | 67ca5aa353ec245f1b375dba9b7e37afb7aa25cf | [
"MIT"
] | null | null | null | src/calculadora/domain/Calculo.java | GabrielMochi/calculadora | 67ca5aa353ec245f1b375dba9b7e37afb7aa25cf | [
"MIT"
] | null | null | null | src/calculadora/domain/Calculo.java | GabrielMochi/calculadora | 67ca5aa353ec245f1b375dba9b7e37afb7aa25cf | [
"MIT"
] | null | null | null | 20.028571 | 84 | 0.601997 | 1,420 | package calculadora.domain;
public class Calculo {
private String formula;
private String resultado;
public Calculo(String formula, String resultado) {
this.formula = formula;
this.resultado = resultado;
}
public String getFormula() {
return formula;
}
public void setFormula(String formula) {
this.formula = formula;
}
public String getResultado() {
return resultado;
}
public void setResultado(String resultado) {
this.resultado = resultado;
}
@Override
public String toString() {
return "Calculo{" + "formula=" + formula + ", resultado=" + resultado + '}';
}
}
|
3e0375ac31cdda71918b161c6cafa5bb58e669ce | 678 | java | Java | src/main/java/broadwick/io/package-info.java | EPICScotland/Broadwick | b9c17e26baea943d0786b0203797fa1e0a26726b | [
"Apache-2.0"
] | 4 | 2015-01-13T18:05:25.000Z | 2018-07-02T13:18:33.000Z | Broadwick1.1/src/main/java/broadwick/io/package-info.java | EPICScotland/Broadwick | b9c17e26baea943d0786b0203797fa1e0a26726b | [
"Apache-2.0"
] | 4 | 2021-08-13T18:32:58.000Z | 2022-01-21T23:14:26.000Z | src/main/java/broadwick/io/package-info.java | EPICScotland/Broadwick | b9c17e26baea943d0786b0203797fa1e0a26726b | [
"Apache-2.0"
] | null | null | null | 30.818182 | 75 | 0.725664 | 1,421 | /*
* Copyright 2013 University of Glasgow.
*
* 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.
*/
/**
* Provides useful IO utilities.
* <p>
*/
package broadwick.io;
|
3e03768fac60d477e851a21aa13a4a5e446c1ba2 | 1,395 | java | Java | Week3/Main.java | believe563/ARTSWeeks | 923e9e51debe4d719caae383a6266ad4ace2b2e4 | [
"MIT"
] | null | null | null | Week3/Main.java | believe563/ARTSWeeks | 923e9e51debe4d719caae383a6266ad4ace2b2e4 | [
"MIT"
] | null | null | null | Week3/Main.java | believe563/ARTSWeeks | 923e9e51debe4d719caae383a6266ad4ace2b2e4 | [
"MIT"
] | null | null | null | 16.607143 | 41 | 0.486022 | 1,422 | package test1;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import javax.management.QueryExp;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(romanToInt(s));
}
public static int romanToInt(String s) {
int num = 0;
for (int i = 0; i < s.length(); i++) {
char x = s.charAt(i);
char x1;
if (i < s.length() - 1) {
x1 = s.charAt(i + 1);
}else {
x1='0';
}
switch (x) {
case 'M':
num = num + 1000;
break;
case 'D':
num = num + 500;
break;
case 'C':
if (x1 == 'D') {
num = num + 400;
i++;
} else if (x1 == 'M') {
num = num + 900;
i++;
} else {
num = num + 100;
}
break;
case 'L':
num = num + 50;
break;
case 'X':
if (x1 == 'L') {
num = num + 40;
i++;
} else if (x1 == 'C') {
num = num + 90;
i++;
} else {
num = num + 10;
}
break;
case 'V':
num = num + 5;
break;
case 'I':
if (x1 == 'V') {
num = num + 4;
i++;
} else if (x1 == 'X') {
num = num + 9;
i++;
} else {
num = num + 1;
}
break;
}
}
return num;
}
}
|
3e03773d8cadb1788f08f451c8eba6d75df4a53f | 3,646 | java | Java | uberfire-workbench/uberfire-workbench-client-views-patternfly/src/main/java/org/uberfire/client/views/pfly/widgets/InlineNotification.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 157 | 2017-09-26T17:42:08.000Z | 2022-03-11T06:48:15.000Z | uberfire-workbench/uberfire-workbench-client-views-patternfly/src/main/java/org/uberfire/client/views/pfly/widgets/InlineNotification.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 940 | 2017-03-21T08:15:36.000Z | 2022-03-25T13:18:36.000Z | uberfire-workbench/uberfire-workbench-client-views-patternfly/src/main/java/org/uberfire/client/views/pfly/widgets/InlineNotification.java | LeonidLapshin/appformer | 2cf15393aeb922cab813938aee2c665d51ede57f | [
"Apache-2.0"
] | 178 | 2017-03-14T10:44:31.000Z | 2022-03-28T23:02:29.000Z | 28.263566 | 77 | 0.639331 | 1,423 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.uberfire.client.views.pfly.widgets;
import java.util.List;
import java.util.stream.Stream;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.jboss.errai.common.client.api.IsElement;
import org.jboss.errai.common.client.dom.Button;
import org.jboss.errai.common.client.dom.Div;
import org.jboss.errai.common.client.dom.Document;
import org.jboss.errai.common.client.dom.HTMLElement;
import org.jboss.errai.common.client.dom.Span;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import static org.jboss.errai.common.client.dom.DOMUtil.*;
@Templated(stylesheet = "InlineNotification.css")
@Dependent
public class InlineNotification implements IsElement {
@Inject
@DataField("alert")
private Div alert;
@Inject
@DataField("message")
private Span message;
@Inject
@DataField("icon")
private Span icon;
@Inject
@DataField("dismiss")
private Button dismiss;
@Inject
private Document document;
@Override
public HTMLElement getElement() {
return alert;
}
public void setMessage(final String message) {
this.message.setTextContent(message);
}
public void setMessage(final List<String> messages) {
removeAllElementChildren(this.message);
final HTMLElement ul = document.createElement("ul");
addCSSClass(ul,
"list-unstyled");
for (String message : messages) {
final HTMLElement li = document.createElement("li");
li.setTextContent(message);
ul.appendChild(li);
}
this.message.appendChild(ul);
}
public void setDismissable() {
addCSSClass(alert,
"alert-dismissable");
removeCSSClass(dismiss,
"hidden");
}
public void setType(final InlineNotificationType type) {
Stream.of(InlineNotificationType.values()).forEach(availableType -> {
removeCSSClass(alert, availableType.getCssClass());
removeCSSClass(icon, availableType.getIcon());
});
addCSSClass(alert,
type.getCssClass());
addCSSClass(icon,
type.getIcon());
}
public enum InlineNotificationType {
SUCCESS("alert-success",
"pficon-ok"),
INFO("alert-info",
"pficon-info"),
WARNING("alert-warning",
"pficon-warning-triangle-o"),
DANGER("alert-danger",
"pficon-error-circle-o");
private String cssClass;
private String icon;
InlineNotificationType(final String cssClass,
final String icon) {
this.cssClass = cssClass;
this.icon = icon;
}
public String getCssClass() {
return cssClass;
}
public String getIcon() {
return icon;
}
}
}
|
3e03776a6df5d4ec6bfadb101b0dce4b2a59346a | 863 | java | Java | smart-sso/smart-sso-client/src/main/java/com/smart/sso/rpc/AuthenticationRpcService.java | shenhaoguangDayDayUp/small_admin | 3a33cf3f99e851af13d71db2f7697ffbd7b5230d | [
"MIT"
] | null | null | null | smart-sso/smart-sso-client/src/main/java/com/smart/sso/rpc/AuthenticationRpcService.java | shenhaoguangDayDayUp/small_admin | 3a33cf3f99e851af13d71db2f7697ffbd7b5230d | [
"MIT"
] | null | null | null | smart-sso/smart-sso-client/src/main/java/com/smart/sso/rpc/AuthenticationRpcService.java | shenhaoguangDayDayUp/small_admin | 3a33cf3f99e851af13d71db2f7697ffbd7b5230d | [
"MIT"
] | null | null | null | 16.921569 | 78 | 0.584009 | 1,424 | package com.smart.sso.rpc;
import java.util.List;
/**
* 身份认证授权服务接口
*
* @author Joe
*/
public interface AuthenticationRpcService {
/**
* 验证是否已经登录
*
* @param token
* 授权码
* @return
*/
public boolean validate(String token);
/**
* 根据登录的Token和应用编码获取授权用户信息
*
* @param token
* 授权码
* @param appCode
* 应用编码
* @return
*/
public RpcUser findAuthInfo(String token);
/**
* 获取当前应用所有权限(含菜单)
*
* @param token
* 授权码 (如果token不为空,获取当前用户的所有权限)
* @param appCode
* 应用编码
* @return
*/
public List<RpcPermission> findPermissionList(String token, String appCode);
public String findUserByChargeUserId(Integer userId);
public String findRoleBusiCode(Integer userId);
public void removeToken(String token);
}
|
3e0377d8f72ff55ad87ca6bad1848494653ac261 | 2,179 | java | Java | DataStructure/list/Reverselinkedlist.java | aiter/cs | 4357c0c70bc323f4184ffc3087a553245ec864c4 | [
"Apache-2.0"
] | null | null | null | DataStructure/list/Reverselinkedlist.java | aiter/cs | 4357c0c70bc323f4184ffc3087a553245ec864c4 | [
"Apache-2.0"
] | 6 | 2019-06-04T00:06:18.000Z | 2019-08-03T23:12:18.000Z | DataStructure/list/Reverselinkedlist.java | aiter/cs | 4357c0c70bc323f4184ffc3087a553245ec864c4 | [
"Apache-2.0"
] | null | null | null | 24.211111 | 75 | 0.500688 | 1,425 | public class Reverselinkedlist {
static Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/**
* Function to reverse the linked list
*
* 单向链表
*/
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
// 1. next前移 2. current.next翻转 3. pre前移 4. current前移
// 结束条件是什么? 一定是current会不断的后移
while (current != null) {
//向链表后移动,会到null
next = current.next;
//当前Node的后续node,指向原来的前向节点
current.next = prev;
// 注意这一步,避免前序node丢失
prev = current;
//
current = next;
}
node = prev;
return node;
}
public void addFirst(int object) {
//这个地方如果要插入在链表第一个位置,复杂一点
Node newNode = new Node(object);
newNode.next = head;
head = newNode;
}
public void addLast(int object) { // here I don't need a tail reference
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = new Node(object);
}
// prints content of double linked list
void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args)
{
Reverselinkedlist list = new Reverselinkedlist();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
System.out.println("");
list.addFirst(77);
System.out.println("add item to first linked list ");
list.printList(head);
System.out.println("");
}
} |
3e03789abd8393c9c216cf7e4e5bc0bd4d25f235 | 1,648 | java | Java | phonesearch/src/main/java/cn/edu/hbcit/phonesearch/Controller/IndexController.java | RelentlessFlow/PhoneSerachSystem | 16f17da16b1df54a58589f5bc6334549957119fb | [
"MIT"
] | null | null | null | phonesearch/src/main/java/cn/edu/hbcit/phonesearch/Controller/IndexController.java | RelentlessFlow/PhoneSerachSystem | 16f17da16b1df54a58589f5bc6334549957119fb | [
"MIT"
] | null | null | null | phonesearch/src/main/java/cn/edu/hbcit/phonesearch/Controller/IndexController.java | RelentlessFlow/PhoneSerachSystem | 16f17da16b1df54a58589f5bc6334549957119fb | [
"MIT"
] | null | null | null | 29.963636 | 103 | 0.729369 | 1,426 | package cn.edu.hbcit.phonesearch.Controller;
import cn.edu.hbcit.phonesearch.service.AccountServer;
import cn.edu.hbcit.phonesearch.service.PhoneServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
public class IndexController {
@Autowired
AccountServer accountServer;
@Autowired
PhoneServer phoneServer;
@RequestMapping("index")
public String Index() {
return "index";
}
@RequestMapping("index/search")
public String phoneSearch(HttpServletRequest request, RedirectAttributes attributes, Model model) {
if (accountServer.getIfLogin(request)) {
List recentPhone = phoneServer.findRecentPhoneInfo(50);
model.addAttribute("lists",recentPhone);
return "search";
} else {
attributes.addFlashAttribute("result", "请您登陆后再使用");
return "redirect:/user/login";
}
}
@RequestMapping("hello")
public ModelAndView hello(HttpServletResponse response) throws IOException {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("hello");
// modelAndView.addObject("username", "libai");
return modelAndView;
}
} |
3e0378a934ffc0f6f9959e07bc44649ffe330811 | 1,491 | java | Java | src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/ContraptionEntityRenderer.java | tansheron/Create | 9fe4aee271522cbdd3bbe1987891f2d62383d0bb | [
"MIT"
] | 188 | 2021-03-15T18:50:21.000Z | 2022-01-02T20:12:18.000Z | src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/ContraptionEntityRenderer.java | tansheron/Create | 9fe4aee271522cbdd3bbe1987891f2d62383d0bb | [
"MIT"
] | 60 | 2021-03-15T21:09:06.000Z | 2022-01-02T01:50:41.000Z | src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/ContraptionEntityRenderer.java | tansheron/Create | 9fe4aee271522cbdd3bbe1987891f2d62383d0bb | [
"MIT"
] | 31 | 2021-03-15T21:03:37.000Z | 2022-01-01T20:10:03.000Z | 32.413043 | 112 | 0.802146 | 1,427 | package com.simibubi.create.content.contraptions.components.structureMovement;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionRenderDispatcher;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.resources.ResourceLocation;
public class ContraptionEntityRenderer<C extends AbstractContraptionEntity> extends EntityRenderer<C> {
public ContraptionEntityRenderer(EntityRendererProvider.Context context) {
super(context);
}
@Override
public ResourceLocation getTextureLocation(C entity) {
return null;
}
@Override
public boolean shouldRender(C entity, Frustum clippingHelper, double cameraX, double cameraY,
double cameraZ) {
if (entity.getContraption() == null)
return false;
if (!entity.isAlive())
return false;
return super.shouldRender(entity, clippingHelper, cameraX, cameraY, cameraZ);
}
@Override
public void render(C entity, float yaw, float partialTicks, PoseStack ms, MultiBufferSource buffers,
int overlay) {
super.render(entity, yaw, partialTicks, ms, buffers, overlay);
Contraption contraption = entity.getContraption();
if (contraption != null) {
ContraptionRenderDispatcher.renderFromEntity(entity, contraption, buffers);
}
}
}
|
3e0378b88d0783b15e816862d399c03322ecb3ca | 309 | java | Java | test/org/com1027/question1/AllTests.java | SassyShiba/JavaSummative | 0e473b558df019390a8f31fabdc0ffdb1172b293 | [
"MIT"
] | null | null | null | test/org/com1027/question1/AllTests.java | SassyShiba/JavaSummative | 0e473b558df019390a8f31fabdc0ffdb1172b293 | [
"MIT"
] | null | null | null | test/org/com1027/question1/AllTests.java | SassyShiba/JavaSummative | 0e473b558df019390a8f31fabdc0ffdb1172b293 | [
"MIT"
] | null | null | null | 25.75 | 116 | 0.805825 | 1,428 | package org.com1027.question1;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ AgencyTest.class, HouseTest.class, PropertyManagementTest.class, RoomTest.class, TenantTest.class })
public class AllTests {
}
|
3e037a507d961842ee169bd4f6558b10a8fadace | 2,860 | java | Java | core/src/test/java/google/registry/testing/DualDatabaseTestInvocationContextProviderTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 1,644 | 2016-10-18T15:05:43.000Z | 2022-03-19T21:45:23.000Z | core/src/test/java/google/registry/testing/DualDatabaseTestInvocationContextProviderTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 332 | 2016-10-18T15:33:58.000Z | 2022-03-30T12:48:37.000Z | core/src/test/java/google/registry/testing/DualDatabaseTestInvocationContextProviderTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 270 | 2016-10-18T14:56:43.000Z | 2022-03-27T17:54:07.000Z | 33.255814 | 97 | 0.766084 | 1,429 | // Copyright 2020 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.testing;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import google.registry.model.ofy.DatastoreTransactionManager;
import google.registry.persistence.transaction.JpaTransactionManager;
import google.registry.persistence.transaction.TransactionManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* Test to verify that {@link DualDatabaseTestInvocationContextProvider} extension executes tests
* with corresponding {@link TransactionManager}.
*/
@DualDatabaseTest
public class DualDatabaseTestInvocationContextProviderTest {
private static int testBothDbsOfyCounter = 0;
private static int testBothDbsSqlCounter = 0;
private static int testOfyOnlyOfyCounter = 0;
private static int testOfyOnlySqlCounter = 0;
private static int testSqlOnlyOfyCounter = 0;
private static int testSqlOnlySqlCounter = 0;
@RegisterExtension
public final AppEngineExtension appEngine =
AppEngineExtension.builder().withDatastoreAndCloudSql().build();
@TestOfyAndSql
void testToVerifyBothOfyAndSqlTmAreUsed() {
if (tm() instanceof DatastoreTransactionManager) {
testBothDbsOfyCounter++;
}
if (tm() instanceof JpaTransactionManager) {
testBothDbsSqlCounter++;
}
}
@TestOfyOnly
void testToVerifyOnlyOfyTmIsUsed() {
if (tm() instanceof DatastoreTransactionManager) {
testOfyOnlyOfyCounter++;
}
if (tm() instanceof JpaTransactionManager) {
testOfyOnlySqlCounter++;
}
}
@TestSqlOnly
void testToVerifyOnlySqlTmIsUsed() {
if (tm() instanceof DatastoreTransactionManager) {
testSqlOnlyOfyCounter++;
}
if (tm() instanceof JpaTransactionManager) {
testSqlOnlySqlCounter++;
}
}
@AfterAll
static void assertEachTransactionManagerIsUsed() {
assertThat(testBothDbsOfyCounter).isEqualTo(1);
assertThat(testBothDbsSqlCounter).isEqualTo(1);
assertThat(testOfyOnlyOfyCounter).isEqualTo(1);
assertThat(testOfyOnlySqlCounter).isEqualTo(0);
assertThat(testSqlOnlyOfyCounter).isEqualTo(0);
assertThat(testSqlOnlySqlCounter).isEqualTo(1);
}
}
|
3e037b245dcd800d5199f5c57bfea58261068ba0 | 6,709 | java | Java | src/test/java/no/ssb/subsetsservice/util/UtilsTest.java | runejo/klass-subsets-api | 3e6254389e5b007bae6cb997aaea6856c7dc9624 | [
"Apache-2.0"
] | 3 | 2020-06-02T16:35:21.000Z | 2020-08-26T08:25:59.000Z | src/test/java/no/ssb/subsetsservice/util/UtilsTest.java | statisticsnorway/klass-subsets-api | e0684167776b2008ee1fd9cbeeb57371a6fcb401 | [
"Apache-2.0"
] | 84 | 2020-05-20T08:04:26.000Z | 2022-03-25T13:33:40.000Z | src/test/java/no/ssb/subsetsservice/util/UtilsTest.java | runejo/klass-subsets-api | 3e6254389e5b007bae6cb997aaea6856c7dc9624 | [
"Apache-2.0"
] | 3 | 2020-05-06T13:27:51.000Z | 2022-02-04T08:43:18.000Z | 37.272222 | 98 | 0.685199 | 1,430 | package no.ssb.subsetsservice.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import no.ssb.subsetsservice.entity.Field;
import no.ssb.subsetsservice.util.Utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UtilsTest {
final String s0 = "";
final String s1 = "a";
final String s2 = "A";
final String s3 = "!";
final String s4 = ",1";
final String s5 = "2-";
final String s6 = "3,3";
final String s7 =" 4.4";
final String s8 = "5";
final String s9 = "";
final String YYYY_MM_DD_true_1 = "2020-01-01";
final String YYYY_MM_DD_true_2 = "1990-12-31";
final String YYYY_MM_DD_false_0 = "";
final String YYYY_MM_DD_false_1 = "2020-00-01";
final String YYYY_MM_DD_false_2 = "2020-13-01";
final String YYYY_MM_DD_false_3 = "2020-01-00";
final String YYYY_MM_DD_false_4 = "100-01-01";
final String YYYY_MM_DD_false_5 = "10000-01-01";
final String YYYY_MM_DD_false_6 = "2000-1-1";
final String YYYY_MM_DD_false_7 = "2000-01-1";
final String YYYY_MM_DD_false_8 = "2000-1-01";
final String YYYY_MM_DD_false_9 = "0200-01-01";
final String version_true_1 = "1";
final String version_true_2 = "2.2";
final String version_true_3 = "3.3.3";
final String version_false_0 = "";
final String version_false_1 = "v1";
final String version_false_2 = "v2.2";
final String version_false_3 = "v3.3.3";
final String version_false_4 = "version 1";
final String version_false_5 = "1,1";
final String version_false_6 = "1,1";
final String clean_true_1 = "aasdukrjiklmklv";
final String clean_true_2 = "SDFGHJKKKKKMNBVCFGHJK";
final String clean_true_3 = "084375887498234756";
final String clean_true_4 = "SDFfgjhFGJHhlvbmk";
final String clean_true_5 = "SDF946fgjh6794FGJHhlvb468mk";
final String clean_true_6 = "TEST_test-94300";
final String clean_true_7 = "-TEST_test-94300";
final String clean_true_8 = "_TEST_test-94300";
final String clean_false_1 = "test test";
final String clean_false_2 = "test/";
final String clean_false_3 = "test?";
final String clean_false_4 = "test&";
final String clean_false_5 = "test%";
final String clean_false_6 = "test&";
final String clean_false_7 = "Robert'); DROP TABLE Students;--";
final String clean_false_8 = "test'";
final String clean_false_9 = "test\"";
final String clean_false_10 = "test;";
final String clean_false_11 = "test:";
final String clean_false_12 = "test{}[]<>^^¨¨~=¤#@!|§";
@Test
void isYearMonthDay() {
assertTrue(Utils.isYearMonthDay(YYYY_MM_DD_true_1));
assertTrue(Utils.isYearMonthDay(YYYY_MM_DD_true_2));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_0));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_1));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_2));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_3));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_4));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_5));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_6));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_7));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_8));
assertFalse(Utils.isYearMonthDay(YYYY_MM_DD_false_9));
}
@Test
void isVersion() {
assertTrue(Utils.isVersion(version_true_1));
assertTrue(Utils.isVersion(version_true_2));
assertTrue(Utils.isVersion(version_true_3));
assertFalse(Utils.isVersion(version_false_0));
assertFalse(Utils.isVersion(version_false_1));
assertFalse(Utils.isVersion(version_false_2));
assertFalse(Utils.isVersion(version_false_3));
assertFalse(Utils.isVersion(version_false_4));
assertFalse(Utils.isVersion(version_false_5));
assertFalse(Utils.isVersion(version_false_6));
}
@Test
void isClean() {
assertTrue(Utils.isClean(clean_true_1));
assertTrue(Utils.isClean(clean_true_2));
assertTrue(Utils.isClean(clean_true_3));
assertTrue(Utils.isClean(clean_true_4));
assertTrue(Utils.isClean(clean_true_5));
assertTrue(Utils.isClean(clean_true_6));
assertTrue(Utils.isClean(clean_true_7));
assertTrue(Utils.isClean(clean_true_8));
assertFalse(Utils.isClean(clean_false_1));
assertFalse(Utils.isClean(clean_false_2));
assertFalse(Utils.isClean(clean_false_3));
assertFalse(Utils.isClean(clean_false_4));
assertFalse(Utils.isClean(clean_false_5));
assertFalse(Utils.isClean(clean_false_6));
assertFalse(Utils.isClean(clean_false_7));
assertFalse(Utils.isClean(clean_false_8));
assertFalse(Utils.isClean(clean_false_9));
assertFalse(Utils.isClean(clean_false_10));
assertFalse(Utils.isClean(clean_false_11));
assertFalse(Utils.isClean(clean_false_12));
}
@Test
void isNumeric() {
assertFalse(Utils.isNumeric(s0));
assertFalse(Utils.isNumeric(s1));
assertFalse(Utils.isNumeric(s2));
assertFalse(Utils.isNumeric(s3));
assertFalse(Utils.isNumeric(s4));
assertFalse(Utils.isNumeric(s5));
assertFalse(Utils.isNumeric(s6));
assertTrue(Utils.isNumeric(s7));
assertTrue(Utils.isNumeric(s8));
}
@Test
void isInteger() {
assertFalse(Utils.isInteger(s0));
assertFalse(Utils.isInteger(s1));
assertFalse(Utils.isInteger(s2));
assertFalse(Utils.isInteger(s3));
assertFalse(Utils.isInteger(s4));
assertFalse(Utils.isInteger(s5));
assertFalse(Utils.isInteger(s6));
assertFalse(Utils.isInteger(s7));
assertTrue(Utils.isInteger(s8));
}
@Test
void getSelfLinkObject() {
}
@Test
void cleanSubsetVersion() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode subset = mapper.createObjectNode();
subset.put(Field.VERSION_ID, version_true_1);
assertEquals("1", Utils.cleanV1SubsetVersionField(subset).get(Field.VERSION_ID).asText());
subset.put(Field.VERSION_ID, version_true_2);
assertEquals("2", Utils.cleanV1SubsetVersionField(subset).get(Field.VERSION_ID).asText());
subset.put(Field.VERSION_ID, version_true_3);
assertEquals("3", Utils.cleanV1SubsetVersionField(subset).get(Field.VERSION_ID).asText());
}
@Test
void getLatestMajorVersion() {
}
@Test
void sortByVersionValidFrom() {
}
@Test
void versionComparator() {
}
}
|
3e037b52926fa36a3ba12d25d6a20b9bd90bb22f | 1,349 | java | Java | src/main/java/com/reachauto/hkr/si/utils/wxpay/sdk/WXPayXmlUtil.java | openhkr/hkr-si | 917ae2a035fc91d11271b4eb49418324993d79ea | [
"Apache-2.0"
] | 13 | 2018-09-13T10:00:33.000Z | 2020-10-21T08:55:11.000Z | src/main/java/com/reachauto/hkr/si/utils/wxpay/sdk/WXPayXmlUtil.java | openhkr/hkr-si | 917ae2a035fc91d11271b4eb49418324993d79ea | [
"Apache-2.0"
] | 1 | 2019-02-27T00:46:02.000Z | 2019-02-27T00:46:02.000Z | src/main/java/com/reachauto/hkr/si/utils/wxpay/sdk/WXPayXmlUtil.java | openhkr/hkr-si | 917ae2a035fc91d11271b4eb49418324993d79ea | [
"Apache-2.0"
] | 4 | 2019-02-22T02:18:54.000Z | 2020-01-14T01:41:11.000Z | 43.516129 | 115 | 0.778354 | 1,431 | package com.reachauto.hkr.si.utils.wxpay.sdk;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* 2018/7/3
*/
public final class WXPayXmlUtil {
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
return documentBuilderFactory.newDocumentBuilder();
}
public static Document newDocument() throws ParserConfigurationException {
return newDocumentBuilder().newDocument();
}
}
|
3e037c30df42cf1192025a04de0024b8248e2d49 | 1,486 | java | Java | src/java/org/apache/cassandra/db/IMutation.java | nlalevee/cassandra | 93a6625378d3569c082766e6db82e3815d02ae97 | [
"Apache-2.0"
] | 1 | 2016-08-02T06:14:46.000Z | 2016-08-02T06:14:46.000Z | src/java/org/apache/cassandra/db/IMutation.java | Jacky1/cassandra | 9aace4836ebbb1ddd93c5c9e27e0008a70f734ea | [
"Apache-2.0"
] | null | null | null | src/java/org/apache/cassandra/db/IMutation.java | Jacky1/cassandra | 9aace4836ebbb1ddd93c5c9e27e0008a70f734ea | [
"Apache-2.0"
] | null | null | null | 33.022222 | 75 | 0.730148 | 1,432 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.cassandra.db;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.UUID;
public interface IMutation
{
public String getKeyspaceName();
public Collection<UUID> getColumnFamilyIds();
public ByteBuffer key();
public long getTimeout();
public String toString(boolean shallow);
public void addAll(IMutation m);
public Collection<ColumnFamily> getColumnFamilies();
/**
* Call to increment underlying network buffer refcount
* So we can avoid recycling too soon
*/
public void retain();
/**
* Call to decrement underlying network buffer refcount
*/
public void release();
}
|
3e037c5312bfca1cf9bdc8dfa569fe94f826b639 | 3,660 | java | Java | src/main/java/javax/visrec/ml/classification/NeuralNetBinaryClassifier.java | shareef-ragab/visrec-api | d11e25ff4ac669e7391604d2f25963526e2484c0 | [
"Apache-2.0"
] | 1 | 2021-09-21T12:53:54.000Z | 2021-09-21T12:53:54.000Z | src/main/java/javax/visrec/ml/classification/NeuralNetBinaryClassifier.java | shareef-ragab/visrec-api | d11e25ff4ac669e7391604d2f25963526e2484c0 | [
"Apache-2.0"
] | null | null | null | src/main/java/javax/visrec/ml/classification/NeuralNetBinaryClassifier.java | shareef-ragab/visrec-api | d11e25ff4ac669e7391604d2f25963526e2484c0 | [
"Apache-2.0"
] | null | null | null | 28.818898 | 114 | 0.603552 | 1,433 | package javax.visrec.ml.classification;
import javax.visrec.ml.ClassifierCreationException;
import javax.visrec.spi.ServiceProvider;
import java.io.File;
import java.util.Map;
public interface NeuralNetBinaryClassifier<T> extends BinaryClassifier<T> {
static NeuralNetBinaryClassifier.Builder<?> builder() {
return new NeuralNetBinaryClassifier.Builder<>();
}
class BuildingBlock<T> {
private Class<T> inputCls;
private int inputsNum;
private int[] hiddenLayers;
private float maxError;
private int maxEpochs;
private float learningRate;
private File trainingFile;
private BuildingBlock() {
}
public Class<T> getInputClass() {
return inputCls;
}
public int getInputsNum() {
return inputsNum;
}
public int[] getHiddenLayers() {
return hiddenLayers;
}
public float getMaxError() {
return maxError;
}
public int getMaxEpochs() {
return maxEpochs;
}
public float getLearningRate() {
return learningRate;
}
public File getTrainingFile() {
return trainingFile;
}
private static <R> BuildingBlock<R> copyWithNewTargetClass(BuildingBlock<?> block, Class<R> cls) {
BuildingBlock<R> newBlock = new BuildingBlock<>();
newBlock.inputCls = cls;
newBlock.inputsNum = block.inputsNum;
newBlock.hiddenLayers = block.hiddenLayers;
newBlock.maxError = block.maxError;
newBlock.maxEpochs = block.maxEpochs;
newBlock.learningRate = block.learningRate;
newBlock.trainingFile = block.trainingFile;
return newBlock;
}
}
class Builder<T> {
private NeuralNetBinaryClassifier.BuildingBlock<T> block;
private Builder() {
this(new NeuralNetBinaryClassifier.BuildingBlock<>());
}
private Builder(BuildingBlock<T> block) {
this.block = block;
}
public <R> Builder<R> inputClass(Class<R> cls) {
BuildingBlock<R> newBlock = BuildingBlock.copyWithNewTargetClass(block, cls);
return new Builder<>(newBlock);
}
public Builder<T> inputsNum(int inputsNum) {
block.inputsNum = inputsNum;
return this;
}
public Builder<T> hiddenLayers(int... hiddenLayers) {
block.hiddenLayers = hiddenLayers;
return this;
}
public Builder<T> maxError(float maxError) {
block.maxError = maxError;
return this;
}
public Builder<T> maxEpochs(int maxEpochs) {
block.maxEpochs = maxEpochs;
return this;
}
public Builder<T> learningRate(float learningRate) {
block.learningRate = learningRate;
return this;
}
public Builder<T> trainingFile(File trainingFile) {
block.trainingFile = trainingFile;
return this;
}
public NeuralNetBinaryClassifier.BuildingBlock<T> getBuildingBlock() {
return block;
}
public BinaryClassifier<T> build() throws ClassifierCreationException {
return ServiceProvider.current().getClassifierFactoryService().createNeuralNetBinaryClassifier(block);
}
public BinaryClassifier<T> build(Map<String, Object> configuration) throws ClassifierCreationException {
throw new IllegalStateException("not implemented yet");
}
}
}
|
3e037dd73353429a2e74217789e369e3e1c13b6c | 5,899 | java | Java | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/billingAccount/control/term/BillingAccountTermController.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | 1 | 2020-09-28T08:23:11.000Z | 2020-09-28T08:23:11.000Z | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/billingAccount/control/term/BillingAccountTermController.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | null | null | null | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/billingAccount/control/term/BillingAccountTermController.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | null | null | null | 39.590604 | 163 | 0.800814 | 1,434 | package com.skytala.eCommerce.domain.accounting.relations.billingAccount.control.term;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.base.Splitter;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.command.term.AddBillingAccountTerm;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.command.term.DeleteBillingAccountTerm;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.command.term.UpdateBillingAccountTerm;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.event.term.BillingAccountTermAdded;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.event.term.BillingAccountTermDeleted;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.event.term.BillingAccountTermFound;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.event.term.BillingAccountTermUpdated;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.mapper.term.BillingAccountTermMapper;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.model.term.BillingAccountTerm;
import com.skytala.eCommerce.domain.accounting.relations.billingAccount.query.term.FindBillingAccountTermsBy;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Scheduler;
import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*;
@RestController
@RequestMapping("/accounting/billingAccount/billingAccountTerms")
public class BillingAccountTermController {
private static Map<String, RequestMethod> validRequests = new HashMap<>();
public BillingAccountTermController() {
validRequests.put("find", RequestMethod.GET);
validRequests.put("add", RequestMethod.POST);
validRequests.put("update", RequestMethod.PUT);
validRequests.put("removeById", RequestMethod.DELETE);
}
/**
*
* @param allRequestParams
* all params by which you want to find a BillingAccountTerm
* @return a List with the BillingAccountTerms
* @throws Exception
*/
@GetMapping("/find")
public ResponseEntity<List<BillingAccountTerm>> findBillingAccountTermsBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception {
FindBillingAccountTermsBy query = new FindBillingAccountTermsBy(allRequestParams);
if (allRequestParams == null) {
query.setFilter(new HashMap<>());
}
List<BillingAccountTerm> billingAccountTerms =((BillingAccountTermFound) Scheduler.execute(query).data()).getBillingAccountTerms();
return ResponseEntity.ok().body(billingAccountTerms);
}
/**
* creates a new BillingAccountTerm entry in the ofbiz database
*
* @param billingAccountTermToBeAdded
* the BillingAccountTerm thats to be added
* @return true on success; false on fail
*/
@RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<BillingAccountTerm> createBillingAccountTerm(@RequestBody BillingAccountTerm billingAccountTermToBeAdded) throws Exception {
AddBillingAccountTerm command = new AddBillingAccountTerm(billingAccountTermToBeAdded);
BillingAccountTerm billingAccountTerm = ((BillingAccountTermAdded) Scheduler.execute(command).data()).getAddedBillingAccountTerm();
if (billingAccountTerm != null)
return successful(billingAccountTerm);
else
return conflict(null);
}
/**
* Updates the BillingAccountTerm with the specific Id
*
* @param billingAccountTermToBeUpdated
* the BillingAccountTerm thats to be updated
* @return true on success, false on fail
* @throws Exception
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{billingAccountTermId}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> updateBillingAccountTerm(@RequestBody BillingAccountTerm billingAccountTermToBeUpdated,
@PathVariable String billingAccountTermId) throws Exception {
billingAccountTermToBeUpdated.setBillingAccountTermId(billingAccountTermId);
UpdateBillingAccountTerm command = new UpdateBillingAccountTerm(billingAccountTermToBeUpdated);
try {
if(((BillingAccountTermUpdated) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
@GetMapping("/{billingAccountTermId}")
public ResponseEntity<BillingAccountTerm> findById(@PathVariable String billingAccountTermId) throws Exception {
HashMap<String, String> requestParams = new HashMap<String, String>();
requestParams.put("billingAccountTermId", billingAccountTermId);
try {
List<BillingAccountTerm> foundBillingAccountTerm = findBillingAccountTermsBy(requestParams).getBody();
if(foundBillingAccountTerm.size()==1){ return successful(foundBillingAccountTerm.get(0));
}else{
return notFound();
}
} catch (RecordNotFoundException e) {
return notFound();
}
}
@DeleteMapping("/{billingAccountTermId}")
public ResponseEntity<String> deleteBillingAccountTermByIdUpdated(@PathVariable String billingAccountTermId) throws Exception {
DeleteBillingAccountTerm command = new DeleteBillingAccountTerm(billingAccountTermId);
try {
if (((BillingAccountTermDeleted) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
}
|
3e037de24c7fa18f8623569b7c6f04f32235b733 | 3,372 | java | Java | hps.java | MrinallU/USACO-Bronze-Collection | 90725c68d1d8dc46baebe5bc294c8025f29472d6 | [
"MIT"
] | 7 | 2020-06-26T21:40:32.000Z | 2021-12-21T04:29:05.000Z | hps.java | MrinallU/USACO-Bronze-Collection | 90725c68d1d8dc46baebe5bc294c8025f29472d6 | [
"MIT"
] | 3 | 2020-07-14T21:34:46.000Z | 2020-08-19T22:09:30.000Z | hps.java | MrinallU/USACO-Bronze-Collection | 90725c68d1d8dc46baebe5bc294c8025f29472d6 | [
"MIT"
] | 4 | 2020-07-14T21:31:29.000Z | 2021-12-12T13:47:23.000Z | 28.336134 | 89 | 0.341934 | 1,435 |
/*
ID: your_id_here
LANG: JAVA
TASK: hps
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class hps
{
public static void main(String[ ] args) throws IOException {
Scanner sc = new Scanner(new File("hps.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("hps.out")));
int N = sc.nextInt(); int [][] arr = new int[N][N];
for(int i = 0; i < N; i++){
for(int j = 0 ; j < 2; j++){
arr[i][j] = sc.nextInt();
}
}
int hoof; int paper; int scissors;
hoof = 1; scissors = 2; paper = 3;
int win = 0;
int ans = 0;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
hoof = 2; scissors = 1; paper = 3;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
hoof = 3; scissors = 1; paper = 2;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
hoof = 1; scissors = 3; paper = 2;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
hoof = 2; scissors = 3; paper = 1;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
hoof = 3; scissors = 1; paper = 2;
for(int i = 0; i < N; i++){
int i1 = arr[i][0]; int i2 = arr[i][1];
if(i1 == scissors && i2 == paper){
win++;
}
if(i1 == hoof && i2 == scissors){
win++;
}
if(i1 == paper && i2 == hoof){
win++;
}
}
ans = Math.max(win, ans);
win = 0 ;
out.println(ans);
out.close();
}
}
|
3e037de418283b1c7391726d1a278a69408d7416 | 188 | java | Java | src/main/java/com/azdanov/pawatask/service/CommentService.java | azdanov/pawa-task | 6e19b137c3d3a5849494d9970c7bb2b74387ff4d | [
"Unlicense"
] | 15 | 2019-05-07T16:50:06.000Z | 2021-08-09T09:07:34.000Z | src/main/java/com/azdanov/pawatask/service/CommentService.java | azdanov/pawa-task | 6e19b137c3d3a5849494d9970c7bb2b74387ff4d | [
"Unlicense"
] | null | null | null | src/main/java/com/azdanov/pawatask/service/CommentService.java | azdanov/pawa-task | 6e19b137c3d3a5849494d9970c7bb2b74387ff4d | [
"Unlicense"
] | 7 | 2019-05-08T01:33:26.000Z | 2021-04-08T18:57:09.000Z | 17.090909 | 43 | 0.765957 | 1,436 | package com.azdanov.pawatask.service;
import com.azdanov.pawatask.domain.Comment;
public interface CommentService {
Comment update(Comment comment);
void deleteById(int id);
}
|
3e037eed68176ce73890f36b206442779526c582 | 1,556 | java | Java | src/com/scm/dao/domain/StockReservationItem.java | theoka81/mycoe-newtest-repo | c12139b9104735d59c81200f9376bb56aef45180 | [
"MIT"
] | null | null | null | src/com/scm/dao/domain/StockReservationItem.java | theoka81/mycoe-newtest-repo | c12139b9104735d59c81200f9376bb56aef45180 | [
"MIT"
] | null | null | null | src/com/scm/dao/domain/StockReservationItem.java | theoka81/mycoe-newtest-repo | c12139b9104735d59c81200f9376bb56aef45180 | [
"MIT"
] | null | null | null | 23.575758 | 95 | 0.746144 | 1,437 | package com.scm.dao.domain;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the StockReservationItems database table.
*
*/
@Entity
@Table(name="StockReservationItems")
@NamedQuery(name="StockReservationItem.findAll", query="SELECT s FROM StockReservationItem s")
public class StockReservationItem implements Serializable {
private static final Long serialVersionUID = 1L;
@EmbeddedId
private StockReservationItemPK id;
@Column(name="Quantity")
private Long quantity;
@Column(name="ReservationQuantity")
private Long reservationQuantity;
//bi-directional many-to-one association to StockReservation
@ManyToOne
@JoinColumn(name="SRId", nullable=false, insertable=false, updatable=false)
private StockReservation stockReservation;
public StockReservationItem() {
}
public StockReservationItemPK getId() {
return this.id;
}
public void setId(StockReservationItemPK id) {
this.id = id;
}
public Long getQuantity() {
return this.quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Long getReservationQuantity() {
return this.reservationQuantity;
}
public void setReservationQuantity(Long reservationQuantity) {
this.reservationQuantity = reservationQuantity;
}
public StockReservation getStockReservation() {
return this.stockReservation;
}
public void setStockReservation(StockReservation stockReservation) {
this.stockReservation = stockReservation;
}
} |
3e038008fe3ec119cae09407ad8162631ebf94f4 | 20,588 | java | Java | cibet-core/src/main/java/com/logitags/cibet/sensor/jdbc/driver/SqlParser.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 7 | 2017-07-05T05:58:24.000Z | 2021-12-20T10:08:37.000Z | cibet-core/src/main/java/com/logitags/cibet/sensor/jdbc/driver/SqlParser.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 11 | 2020-03-04T21:46:49.000Z | 2021-12-17T12:29:21.000Z | cibet-core/src/main/java/com/logitags/cibet/sensor/jdbc/driver/SqlParser.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 2 | 2019-02-01T07:50:03.000Z | 2021-03-18T12:09:43.000Z | 35.37457 | 93 | 0.563969 | 1,438 | /*
*******************************************************************************
* L O G I T A G S
* Software and Programming
* Dr. Wolfgang Winter
* Germany
*
* All rights reserved
*
*******************************************************************************
*/
package com.logitags.cibet.sensor.jdbc.driver;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.StatementVisitor;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.drop.Drop;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.truncate.Truncate;
import net.sf.jsqlparser.statement.update.Update;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.logitags.cibet.core.ControlEvent;
/**
* Parses the sql statement.
*/
public class SqlParser implements StatementVisitor {
private Log log = LogFactory.getLog(SqlParser.class);
private static final String NO_PRIMARYKEY = "-";
private static Map<String, ControlEvent> controlEventMap = Collections
.synchronizedMap(new HashMap<String, ControlEvent>());
private static Map<String, String> targetMap = Collections
.synchronizedMap(new HashMap<String, String>());
/**
* [sql statement|List[SqlParameter]]
*/
private static Map<String, List<SqlParameter>> parameterMap = Collections
.synchronizedMap(new HashMap<String, List<SqlParameter>>());
private static Map<String, List<SqlParameter>> insUpdColumnsMap = Collections
.synchronizedMap(new HashMap<String, List<SqlParameter>>());
private static Map<String, SqlParameter> primaryKeys = Collections
.synchronizedMap(new HashMap<String, SqlParameter>());
private String sql;
private Connection connection;
private Statement statement;
/**
* name of the primary key column
*/
private String primaryKeyColumn;
public SqlParser(Connection conn, String sql) {
if (sql == null) {
throw new IllegalArgumentException(
"Failed to instantiate SqlParser: Constructor parameter sql is null");
}
this.sql = sql;
this.connection = conn;
}
private Statement getStatement() {
if (statement == null) {
try {
statement = new CCJSqlParserManager().parse(new StringReader(sql));
} catch (JSQLParserException e) {
log.error(e.getMessage(), e);
throw new CibetJdbcException(e.getMessage(), e);
}
}
return statement;
}
/**
* parses the ControlEvent from the SQL statement. Other statements than
* INSERT, UPDATE or DELETE are not considered and return null.
*
* @return INSERT, UPDATE, DELETE or null
*/
public ControlEvent getControlEvent() {
if (!controlEventMap.containsKey(sql)) {
if (sql == null || sql.toLowerCase().trim().startsWith("alter")) {
visitAlter();
} else {
getStatement().accept(this);
log();
}
}
return controlEventMap.get(sql);
}
/**
* parses the table name from the SQL statement.
* <p>
* INSERT[.] INTO [schema.]tablename[ \n;][.]
* <p>
* DELETE[.] FROM [schema.]tablename[ \n;][.]
* <p>
* UPDATE[.] [schema.]tablename SET[.]
*
* @return
*/
public String getTarget() {
if (!targetMap.containsKey(sql)) {
getStatement().accept(this);
log();
}
return targetMap.get(sql);
}
public SqlParameter getPrimaryKey() {
if (!primaryKeys.containsKey(sql)) {
getStatement().accept(this);
log();
}
return primaryKeys.get(sql);
}
/**
* Returns a map of column names and values from an insert or update
* statement.
*
* @return
*/
public List<SqlParameter> getInsertUpdateColumns() {
if (!insUpdColumnsMap.containsKey(sql)) {
getStatement().accept(this);
log();
}
return (List<SqlParameter>) ((ArrayList) insUpdColumnsMap.get(sql))
.clone();
}
public List<SqlParameter> getParameters() {
if (!parameterMap.containsKey(sql)) {
getStatement().accept(this);
log();
}
return parameterMap.get(sql);
}
private void refineColumnNames() {
if (connection == null) return;
List<SqlParameter> list = insUpdColumnsMap.get(sql);
if (list.get(0).getColumn().equals("?1")) {
String tableName = getTarget();
log.debug("load column names of table " + tableName
+ " from resultset metadata");
ResultSet rs = null;
java.sql.Statement stmt = null;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("select * from " + tableName
+ " where 1 = 0");
ResultSetMetaData md = rs.getMetaData();
int counter = 1;
for (SqlParameter param : list) {
param.setColumn(md.getColumnName(counter));
counter++;
}
} catch (SQLException e) {
throw new CibetJdbcException(e.getMessage(), e);
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
}
}
}
private void findPrimaryKeyColumn() {
if (primaryKeyColumn == null) {
if (connection == null) {
primaryKeyColumn = NO_PRIMARYKEY;
} else {
ResultSet rs = null;
ResultSet mdRs = null;
java.sql.Statement stmt = null;
try {
String dummy = "select * from " + getTarget()
+ " where 1 = 0";
log.debug(dummy);
stmt = connection.createStatement();
rs = stmt.executeQuery(dummy);
ResultSetMetaData md = rs.getMetaData();
String catalogue = md.getCatalogName(1);
String schema = md.getSchemaName(1);
String tableName = md.getTableName(1);
log.debug("retrieve primary keys for " + catalogue + "."
+ schema + "." + tableName);
mdRs = connection.getMetaData().getPrimaryKeys(catalogue,
schema, tableName);
if (mdRs.next()) {
primaryKeyColumn = mdRs.getString(4);
if (mdRs.next()) {
log.debug("table has more than one primary key column");
primaryKeyColumn = NO_PRIMARYKEY;
} else {
log.debug("found primary key column " + primaryKeyColumn);
}
} else {
findPrimaryKeyColumnOracle();
}
} catch (SQLException e) {
throw new CibetJdbcException(e.getMessage(), e);
} finally {
try {
if (rs != null) rs.close();
if (mdRs != null) mdRs.close();
if (stmt != null) stmt.close();
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
}
}
}
}
private void findPrimaryKeyColumnOracle() {
if (primaryKeyColumn == null) {
if (connection == null) {
primaryKeyColumn = NO_PRIMARYKEY;
} else {
try {
log.debug(connection.getCatalog());
DatabaseMetaData md = connection.getMetaData();
log.debug(md.getUserName());
String tableName = getTarget();
String tableCatalog = null;
String tableSchema = null;
ResultSet resultSet = md.getTables(null, null, "%",
new String[] { "TABLE" });
while (resultSet.next()) {
String table = resultSet.getString(3);
if (table.equalsIgnoreCase(tableName)) {
String scheme = resultSet.getString(2);
if (scheme != null
&& scheme.equalsIgnoreCase(md.getUserName())) {
tableName = table;
tableCatalog = resultSet.getString(1);
tableSchema = scheme;
break;
}
}
}
ResultSet rs = md.getPrimaryKeys(tableCatalog, tableSchema,
tableName);
if (rs.next()) {
primaryKeyColumn = rs.getString(4);
if (rs.next()) {
log.debug("table has more than one primary key column");
primaryKeyColumn = NO_PRIMARYKEY;
} else {
log.debug("found primary key column " + primaryKeyColumn);
}
} else {
log.debug("table has no primary key column");
primaryKeyColumn = NO_PRIMARYKEY;
}
} catch (SQLException e) {
throw new CibetJdbcException(e.getMessage(), e);
}
}
}
}
private void parseWhere(Expression where, int sequence) {
log.debug("parse WHERE expression " + where);
if (where == null) {
log.info("No WHERE clause. Seems not to be a primary key condition");
} else if (where instanceof AndExpression) {
AndExpression and = (AndExpression) where;
parseWhere(and.getLeftExpression(), sequence);
parseWhere(and.getRightExpression(), sequence + 1);
} else if (where instanceof BinaryExpression) {
BinaryExpression exp = (BinaryExpression) where;
if (!(exp.getLeftExpression() instanceof Column)) {
if (log.isDebugEnabled()) {
log.debug(exp.getLeftExpression().toString()
+ exp.getStringExpression() + exp.getRightExpression()
+ " is not a unique condition for the primary key column");
}
return;
}
List<SqlParameter> paramList = parameterMap.get(sql);
if (paramList == null) {
paramList = new ArrayList<SqlParameter>();
parameterMap.put(sql, paramList);
}
findPrimaryKeyColumn();
SqlExpressionParser expParser = new SqlExpressionParser();
exp.getRightExpression().accept(expParser);
Object value = expParser.getValue();
String colName = ((Column) exp.getLeftExpression()).getColumnName();
SqlParameter sqlParam = new SqlParameter(colName, value);
if ("?".equals(value)) {
sequence++;
sqlParam.setSequence(sequence);
}
if (colName.equalsIgnoreCase(primaryKeyColumn)
&& exp instanceof EqualsTo) {
primaryKeys.put(sql, sqlParam);
}
paramList.add(sqlParam);
if (log.isDebugEnabled()) {
log.debug("parse WHERE column " + sqlParam);
}
} else {
log.info("WHERE clause does not contain a unique primary key condition.");
}
}
@Override
public synchronized void visit(Select arg0) {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
@Override
public synchronized void visit(Delete del) {
controlEventMap.put(sql, ControlEvent.DELETE);
targetMap.put(sql, del.getTable().getName());
List<SqlParameter> paramList = new ArrayList<SqlParameter>();
parameterMap.put(sql, paramList);
List<SqlParameter> updList = new ArrayList<SqlParameter>();
insUpdColumnsMap.put(sql, updList);
parseWhere(del.getWhere(), 0);
if (primaryKeys.get(sql) == null) {
// no unique primary key condition. Not controlled
controlEventMap.put(sql, null);
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
}
@Override
public synchronized void visit(Update upd) {
controlEventMap.put(sql, ControlEvent.UPDATE);
targetMap.put(sql, upd.getTable().getName());
findPrimaryKeyColumn();
if (upd.getColumns().size() != upd.getExpressions().size()) {
String err = "Failed to parse UPDATE statement "
+ sql
+ ": number of columns is not equal to number of values in SET clause";
log.error(err);
throw new CibetJdbcException(err);
}
List<SqlParameter> paramList = new ArrayList<SqlParameter>();
parameterMap.put(sql, paramList);
List<SqlParameter> updList = new ArrayList<SqlParameter>();
insUpdColumnsMap.put(sql, updList);
int sequence = 0;
for (int i = 0; i < upd.getExpressions().size(); i++) {
Expression exp = (Expression) upd.getExpressions().get(i);
SqlExpressionParser expParser = new SqlExpressionParser();
exp.accept(expParser);
Object value = expParser.getValue();
SqlParameter sqlParam = new SqlParameter(((Column) upd.getColumns()
.get(i)).getColumnName(), value);
if ("?".equals(value)) {
sequence++;
sqlParam.setSequence(sequence);
}
paramList.add(sqlParam);
updList.add(sqlParam);
}
parseWhere(upd.getWhere(), sequence);
if (primaryKeys.get(sql) == null) {
// no unique primary key condition. Not controlled
controlEventMap.put(sql, null);
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
}
@Override
public synchronized void visit(Insert ins) {
controlEventMap.put(sql, ControlEvent.INSERT);
targetMap.put(sql, ins.getTable().getName());
findPrimaryKeyColumn();
List<SqlParameter> paramList = new ArrayList<SqlParameter>();
parameterMap.put(sql, paramList);
List<SqlParameter> updList = new ArrayList<SqlParameter>();
insUpdColumnsMap.put(sql, updList);
ItemsList il = ins.getItemsList();
if (il instanceof ExpressionList) {
ExpressionList el = (ExpressionList) il;
if (ins.getColumns() != null
&& ins.getColumns().size() != el.getExpressions().size()) {
String err = "Failed to parse INSERT statement "
+ sql
+ ": number of columns is not equal to number of values in VALUES clause";
log.error(err);
throw new CibetJdbcException(err);
}
int sequence = 0;
for (int i = 0; i < el.getExpressions().size(); i++) {
Expression exp = (Expression) el.getExpressions().get(i);
SqlExpressionParser expParser = new SqlExpressionParser();
exp.accept(expParser);
Object value = expParser.getValue();
String columnName = ins.getColumns() == null ? "?" + (i + 1)
: ((Column) ins.getColumns().get(i)).getColumnName();
SqlParameter sqlParam = new SqlParameter(columnName, value);
if ("?".equals(value)) {
sequence++;
sqlParam.setSequence(sequence);
}
if (sqlParam.getColumn().equalsIgnoreCase(primaryKeyColumn)) {
primaryKeys.put(sql, sqlParam);
}
paramList.add(sqlParam);
updList.add(sqlParam);
}
refineColumnNames();
if (primaryKeys.get(sql) == null) {
emptyPrimaryKey(SqlParameterType.INSERT_PARAMETER);
}
} else {
log.warn("Subselects not supported in statement " + sql);
controlEventMap.put(sql, null);
}
}
private synchronized void visitAlter() {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
@Override
public synchronized void visit(Replace arg0) {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
@Override
public synchronized void visit(Drop arg0) {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
@Override
public synchronized void visit(Truncate arg0) {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
@Override
public synchronized void visit(CreateTable arg0) {
controlEventMap.put(sql, null);
targetMap.put(sql, null);
insUpdColumnsMap.put(sql, new ArrayList<SqlParameter>());
parameterMap.put(sql, new LinkedList<SqlParameter>());
emptyPrimaryKey(SqlParameterType.WHERE_PARAMETER);
}
public void log() {
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("\n***************************\n");
buf.append("PARSED SQL STATEMENT: ");
buf.append(sql);
buf.append("\n***************************\n");
buf.append("CONTROL EVENT: ");
buf.append(controlEventMap.get(sql));
buf.append("\nTARGET: ");
buf.append(targetMap.get(sql));
buf.append("\nPRIMARY KEY CONSTRAINT: ");
buf.append(primaryKeys.get(sql).getColumn());
buf.append(" = ");
buf.append(primaryKeys.get(sql).getValue());
buf.append("\nPARAMETERS: ");
List<SqlParameter> l = parameterMap.get(sql);
for (SqlParameter par : l) {
buf.append("\n");
buf.append(par.getSequence() == 0 ? "-" : par.getSequence());
buf.append(": ");
buf.append(par.getColumn());
buf.append(" = ");
buf.append(par.getValue());
}
buf.append("\n***************************\n");
log.debug(buf);
}
}
/**
* @return the sql
*/
public String getSql() {
return sql;
}
private void emptyPrimaryKey(SqlParameterType type) {
SqlParameter sqlParam = new SqlParameter(primaryKeyColumn, null);
primaryKeys.put(sql, sqlParam);
}
}
|
3e03800ab955547fbf86507f3202a084dcf82b82 | 3,795 | java | Java | src/main/java/com/github/chainmailstudios/astromine/mixin/WorldChunkMixin.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | src/main/java/com/github/chainmailstudios/astromine/mixin/WorldChunkMixin.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | src/main/java/com/github/chainmailstudios/astromine/mixin/WorldChunkMixin.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | 26.914894 | 83 | 0.722003 | 1,439 | package com.github.chainmailstudios.astromine.mixin;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.WorldChunk;
import com.github.chainmailstudios.astromine.access.WorldChunkAccess;
@Mixin(WorldChunk.class)
public class WorldChunkMixin implements WorldChunkAccess {
@Shadow
@Final
private World world;
@Shadow
@Final
private ChunkPos pos;
@Shadow
@Final
private ChunkSection[] sections;
private WorldChunk east, west, north, south;
private Runnable unload;
@Override
public void astromine_addUnloadListener(Runnable runnable) {
if (this.unload == null) {
this.unload = runnable;
} else {
Runnable run = this.unload;
this.unload = () -> {
run.run();
runnable.run();
};
}
}
@Override
public void astromine_runUnloadListeners() {
if (this.unload != null) {
this.unload.run();
}
}
@Override
public void astromine_attachEast(WorldChunk chunk) {
this.east = chunk;
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.east = null);
}
@Override
public void astromine_attachWest(WorldChunk chunk) {
this.west = chunk;
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.west = null);
}
@Override
public void astromine_attachNorth(WorldChunk chunk) {
this.north = chunk;
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.north = null);
}
@Override
public void astromine_attachSouth(WorldChunk chunk) {
this.south = chunk;
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.south = null);
}
@Override
public void astromine_removeSubchunk(int subchunk) {
this.sections[subchunk] = WorldChunk.EMPTY_SECTION;
}
@Override
public WorldChunk astromine_east() {
WorldChunk chunk = this.east;
if (chunk == null) {
ChunkPos pos = this.pos;
chunk = this.east = this.world.getChunk(pos.x + 1, pos.z);
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.east = null);
((WorldChunkAccess) chunk).astromine_attachWest((WorldChunk) (Object) this);
}
return chunk;
}
@Override
public WorldChunk astromine_west() {
WorldChunk chunk = this.west;
if (chunk == null) {
ChunkPos pos = this.pos;
chunk = this.west = this.world.getChunk(pos.x - 1, pos.z);
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.west = null);
((WorldChunkAccess) chunk).astromine_attachEast((WorldChunk) (Object) this);
}
return chunk;
}
@Override
public WorldChunk astromine_north() {
WorldChunk chunk = this.north;
if (chunk == null) {
ChunkPos pos = this.pos;
chunk = this.north = this.world.getChunk(pos.x, pos.z - 1);
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.north = null);
((WorldChunkAccess) chunk).astromine_attachSouth((WorldChunk) (Object) this);
}
return chunk;
}
@Override
public WorldChunk astromine_south() {
WorldChunk chunk = this.south;
if (chunk == null) {
ChunkPos pos = this.pos;
chunk = this.south = this.world.getChunk(pos.x, pos.z + 1);
((WorldChunkAccess) chunk).astromine_addUnloadListener(() -> this.south = null);
((WorldChunkAccess) chunk).astromine_attachNorth((WorldChunk) (Object) this);
}
return chunk;
}
@Inject(method = "setLoadedToWorld", at = @At("RETURN"))
private void serialize(boolean loaded, CallbackInfo ci) {
if (!loaded) { // if unloading
this.astromine_runUnloadListeners();
}
}
}
|
3e038072adf90a49edb1a3ecc65d965ccca7d446 | 1,722 | java | Java | java/Naver_Hack/src/KoreanAnalysis/Morph_Main.java | taki0112/Naver-Keyword_analysis | 8be3a481e1be1dd3c6c43b59f0fdc6a9bf9f29a3 | [
"MIT"
] | 3 | 2017-07-03T12:01:56.000Z | 2021-07-25T04:47:04.000Z | java/Naver_Hack/src/KoreanAnalysis/Morph_Main.java | taki0112/Naver-Keyword_analysis | 8be3a481e1be1dd3c6c43b59f0fdc6a9bf9f29a3 | [
"MIT"
] | null | null | null | java/Naver_Hack/src/KoreanAnalysis/Morph_Main.java | taki0112/Naver-Keyword_analysis | 8be3a481e1be1dd3c6c43b59f0fdc6a9bf9f29a3 | [
"MIT"
] | null | null | null | 24.6 | 75 | 0.62892 | 1,440 | package KoreanAnalysis;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Morph_Main {
public static void main(String[] args) {
// 객체 생성
MorphAnalyzer ma = new MorphAnalyzer("lib/models-full");
// 사용자 정의 사전 추가
//ma.setUserDic("dic/userdictionary.txt");
//String text = "우리나라에서 지난 리우올림픽에서 태권도 선수로 몇명이나갔는지,모두다 메달을 땄는지좀 알려주세요";
//System.out.println(ma.analyze(text));
try {
FileWriter fWriter = new FileWriter("KHU_analysis.txt");
BufferedReader br = new BufferedReader(new FileReader("KHU_10000.txt"));
String line = "";
int count = 1;
while( (line = br.readLine()) != null ) {
String morph = ma.analyze(line);
Pattern p = Pattern.compile("([가-힣]+)");
Matcher matcher = p.matcher(morph);
String result = "";
while(matcher.find()) {
result += matcher.group() + " ";
}
// morph = morph.replaceAll("[0-9]", "");
// morph = morph.replaceAll("[a-zA-Z]", "");
fWriter.write(result);
fWriter.write("\n");
System.out.println(count++);
}
fWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String Get_Hangul(String str) {
StringBuffer hangul = new StringBuffer();
for(int i=0; i<str.length(); i++) {
if(checkHan(str.charAt(i)))
hangul.append(str.charAt(i));
else
hangul.append(" ");
}
return hangul.toString();
}
private static boolean checkHan(char cValue) {
if (cValue >= 0xAC00 && cValue <= 0xD743)
return true;
else
return false;
}
}
|
3e0380b12e724e438f59c5fa5ff0d19e6cf00bcf | 250 | java | Java | src/main/java/com/portal/animals/presenters/AllAnimalResponse.java | amitsadafule/animal-information-portal | 153006b0763f346b8474e2eda4379911984ac487 | [
"MIT"
] | null | null | null | src/main/java/com/portal/animals/presenters/AllAnimalResponse.java | amitsadafule/animal-information-portal | 153006b0763f346b8474e2eda4379911984ac487 | [
"MIT"
] | null | null | null | src/main/java/com/portal/animals/presenters/AllAnimalResponse.java | amitsadafule/animal-information-portal | 153006b0763f346b8474e2eda4379911984ac487 | [
"MIT"
] | null | null | null | 15.625 | 56 | 0.808 | 1,441 | package com.portal.animals.presenters;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@Builder
public class AllAnimalResponse {
private List<BasicAnimalInformationPresenter> animals;
}
|
3e03810c42999b19e485472921a1dcba859cab7a | 125 | java | Java | src/main/java/net/blay09/mods/chattweaks/image/renderable/IAnimatedChatRenderable.java | RoCoKo/ChatTweaks | e774cb914b1f2298c21f814991ded23a03264d5d | [
"MIT"
] | 17 | 2018-01-14T10:16:58.000Z | 2021-01-26T12:42:25.000Z | src/main/java/net/blay09/mods/chattweaks/image/renderable/IAnimatedChatRenderable.java | RoCoKo/ChatTweaks | e774cb914b1f2298c21f814991ded23a03264d5d | [
"MIT"
] | 55 | 2017-03-25T03:59:46.000Z | 2021-01-10T14:12:01.000Z | src/main/java/net/blay09/mods/chattweaks/image/renderable/IAnimatedChatRenderable.java | RoCoKo/ChatTweaks | e774cb914b1f2298c21f814991ded23a03264d5d | [
"MIT"
] | 19 | 2017-12-26T15:07:39.000Z | 2021-06-14T10:36:40.000Z | 17.857143 | 52 | 0.816 | 1,442 | package net.blay09.mods.chattweaks.image.renderable;
public interface IAnimatedChatRenderable {
void updateAnimation();
}
|
3e0382a31afe22d77dd9a68ce324cc035949b773 | 495 | java | Java | compiler/testData/loadJava/compiledJava/kotlinSignature/propagation/parameter/InheritReadOnliness.java | chashnikov/kotlin | 88a261234860ff0014e3c2dd8e64072c685d442d | [
"Apache-2.0"
] | 5 | 2015-08-01T10:35:57.000Z | 2021-02-11T16:25:41.000Z | compiler/testData/loadJava/compiledJava/kotlinSignature/propagation/parameter/InheritReadOnliness.java | chashnikov/kotlin | 88a261234860ff0014e3c2dd8e64072c685d442d | [
"Apache-2.0"
] | null | null | null | compiler/testData/loadJava/compiledJava/kotlinSignature/propagation/parameter/InheritReadOnliness.java | chashnikov/kotlin | 88a261234860ff0014e3c2dd8e64072c685d442d | [
"Apache-2.0"
] | 1 | 2017-04-21T06:19:05.000Z | 2017-04-21T06:19:05.000Z | 23.571429 | 65 | 0.69899 | 1,443 | package test;
import org.jetbrains.annotations.NotNull;
import jet.runtime.typeinfo.KotlinSignature;
import org.jetbrains.jet.jvm.compiler.annotation.ExpectLoadError;
import java.util.*;
public interface InheritReadOnliness {
public interface Super {
@KotlinSignature("fun foo(p: List<String>)")
void foo(List<String> p);
void dummy(); // to avoid loading as SAM interface
}
public interface Sub extends Super {
void foo(List<String> p);
}
}
|
3e0382fcaa51b9cf5f11da114dd4fa34bae04be3 | 1,633 | java | Java | jetty-websocket/javax-websocket-client-impl/src/test/java/org/eclipse/jetty/websocket/jsr356/encoders/BadDualEncoder.java | jovenwang/jettyprojec | a89d0b15780e9043e910cc6f9cd6f40bbc6c8827 | [
"Apache-2.0"
] | 3 | 2018-01-26T12:28:09.000Z | 2018-02-01T02:19:38.000Z | jetty-websocket/javax-websocket-client-impl/src/test/java/org/eclipse/jetty/websocket/jsr356/encoders/BadDualEncoder.java | jovenwang/jettyprojec | a89d0b15780e9043e910cc6f9cd6f40bbc6c8827 | [
"Apache-2.0"
] | 5 | 2021-01-31T21:11:55.000Z | 2021-01-31T21:12:10.000Z | jetty-websocket/javax-websocket-client-impl/src/test/java/org/eclipse/jetty/websocket/jsr356/encoders/BadDualEncoder.java | cuba-platform/jetty.project | fdca6109cea36decc16f9e2d6366638fb1701256 | [
"Apache-2.0"
] | 1 | 2020-10-27T07:24:10.000Z | 2020-10-27T07:24:10.000Z | 29.690909 | 97 | 0.617269 | 1,444 | //
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.jsr356.encoders;
import java.io.IOException;
import java.io.Writer;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
/**
* Intentionally bad example of attempting to encode the same object for different message types.
*/
public class BadDualEncoder implements Encoder.Text<Integer>, Encoder.TextStream<Integer>
{
@Override
public void destroy()
{
}
@Override
public String encode(Integer object) throws EncodeException
{
return Integer.toString(object);
}
@Override
public void encode(Integer object, Writer writer) throws EncodeException, IOException
{
writer.write(Integer.toString(object));
}
@Override
public void init(EndpointConfig config)
{
}
}
|
3e03831c2545864246ddb257070db4b594ebe051 | 8,254 | java | Java | mvcCarro/src/DAO/ClientesDAO.java | vinicrespi/JAVA | 43a236a8e85e8ad2324f486fe7b9ab79ab4283fe | [
"MIT"
] | null | null | null | mvcCarro/src/DAO/ClientesDAO.java | vinicrespi/JAVA | 43a236a8e85e8ad2324f486fe7b9ab79ab4283fe | [
"MIT"
] | null | null | null | mvcCarro/src/DAO/ClientesDAO.java | vinicrespi/JAVA | 43a236a8e85e8ad2324f486fe7b9ab79ab4283fe | [
"MIT"
] | null | null | null | 35.273504 | 222 | 0.564332 | 1,445 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import DTO.ClientesDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import mvccarro.Conexao;
import util.DataUtil;
/**
*
* @author 110000636
*/
public class ClientesDAO {
final String NOMEDOBANCO = "carros";
final String NOMEDATABELA = "clientes";
public boolean inserir(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "INSERT INTO " + NOMEDATABELA + " (cli_nome,cli_end,cli_bairro,cli_cidade,cli_cep,cli_uf,cli_fone,cli_email,cli_datanasc,cli_sexo) VALUES (?,?,?,?,?,?,?,?,?,?);";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, clientesDTO.getCli_nome());
ps.setString(2, clientesDTO.getCli_end());
ps.setString(3, clientesDTO.getCli_bairro());
ps.setString(4, clientesDTO.getCli_cidade());
ps.setString(5, clientesDTO.getCli_cep());
ps.setString(6, clientesDTO.getCli_uf());
ps.setString(7, clientesDTO.getCli_fone());
ps.setString(8, clientesDTO.getCli_email());
ps.setString(9, DataUtil.DataForStringMySQL(clientesDTO.getCli_datanasc()));
ps.setString(10, clientesDTO.getCli_sexo()+"");
ps.executeUpdate();
ps.close();
conn.close();
return true;
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return false;
}
}
public boolean alterar(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "UPDATE " + NOMEDATABELA + " SET cli_nome = ?, cli_end = ?, cli_bairro = ?, cli_cidade = ?, cli_cep = ?, cli_uf = ?, cli_fone = ?, cli_email = ?, cli_datanasc = ?, cli_sexo = ? WHERE cli_cod = ?;";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, clientesDTO.getCli_nome());
ps.setString(2, clientesDTO.getCli_end());
ps.setString(3, clientesDTO.getCli_bairro());
ps.setString(4, clientesDTO.getCli_cidade());
ps.setString(5, clientesDTO.getCli_cep());
ps.setString(6, clientesDTO.getCli_uf());
ps.setString(7, clientesDTO.getCli_fone());
ps.setString(8, clientesDTO.getCli_email());
ps.setString(9, DataUtil.DataForStringMySQL(clientesDTO.getCli_datanasc()));
ps.setString(10, clientesDTO.getCli_sexo());
ps.setInt(11, clientesDTO.getCli_cod());
ps.executeUpdate();
ps.close();
conn.close();
return true;
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return false;
}
}
public boolean excluir(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "DELETE FROM " + NOMEDATABELA + " WHERE cli_cod = ?;";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, clientesDTO.getCli_cod());
ps.executeUpdate();
ps.close();
conn.close();
return true;
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return false;
}
}
public ClientesDTO procurarPorCodigo(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "SELECT * FROM " + NOMEDATABELA + " WHERE cli_cod = ?;";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, clientesDTO.getCli_cod());
ResultSet rs = ps.executeQuery();
if(rs.next()){
ClientesDTO obj = new ClientesDTO();
obj.setCli_cod(rs.getInt(1));
obj.setCli_nome(rs.getString(2));
obj.setCli_end(rs.getString(3));
obj.setCli_bairro(rs.getString(4));
obj.setCli_cidade(rs.getString(5));
obj.setCli_cep(rs.getString(6));
obj.setCli_uf(rs.getString(7));
obj.setCli_fone(rs.getString(8));
obj.setCli_email(rs.getString(9));
obj.setCli_datanasc(rs.getTimestamp(10));
obj.setCli_sexo(rs.getString(11));
rs.close();
ps.close();
conn.close();
return obj;
}else{
ps.close();
rs.close();
conn.close();
return null;
}
}catch(Exception e){
return null;
}
}
public ClientesDTO procurarPorDescricao(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "SELECT * FROM " + NOMEDATABELA + " WHERE cli_nome = ?;";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, clientesDTO.getCli_nome());
ResultSet rs = ps.executeQuery();
if(rs.next()){
ClientesDTO obj = new ClientesDTO();
obj.setCli_cod(rs.getInt(1));
obj.setCli_nome(rs.getString(2));
obj.setCli_end(rs.getString(3));
obj.setCli_bairro(rs.getString(4));
obj.setCli_cidade(rs.getString(5));
obj.setCli_cep(rs.getString(6));
obj.setCli_uf(rs.getString(7));
obj.setCli_fone(rs.getString(8));
obj.setCli_email(rs.getString(9));
obj.setCli_datanasc(rs.getTimestamp(10));
obj.setCli_sexo(rs.getString(11));
ps.close();
rs.close();
conn.close();
return obj;
}else{
ps.close();
rs.close();
conn.close();
return null;
}
}catch(Exception e){
return null;
}
}
public boolean existe(ClientesDTO clientesDTO){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "SELECT * FROM " + NOMEDATABELA + " WHERE cli_nome = ?;";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, clientesDTO.getCli_nome());
ResultSet rs = ps.executeQuery();
if(rs.next()){
ps.close();
rs.close();
conn.close();
return true;
}
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return false;
}
return false;
}
public List<ClientesDTO> pesquisarTodos(){
try{
Connection conn = Conexao.conectar(NOMEDOBANCO);
String sql = "SELECT * FROM " + NOMEDATABELA + ";";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
List<ClientesDTO> listObj = montarLista(rs);
return listObj;
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return null;
}
}
public List<ClientesDTO> montarLista(ResultSet rs){
List<ClientesDTO> listObj = new ArrayList<ClientesDTO>();
try{
while(rs.next()){
ClientesDTO obj = new ClientesDTO();
obj.setCli_cod(rs.getInt(1));
obj.setCli_nome(rs.getString(2));
obj.setCli_end(rs.getString(3));
obj.setCli_bairro(rs.getString(4));
obj.setCli_cidade(rs.getString(5));
obj.setCli_cep(rs.getString(6));
obj.setCli_uf(rs.getString(7));
obj.setCli_fone(rs.getString(8));
obj.setCli_email(rs.getString(9));
obj.setCli_datanasc(rs.getTimestamp(10));
obj.setCli_sexo(rs.getString(11));
listObj.add(obj);
}
return listObj;
}catch(Exception e){
System.err.println("Erro: " + e.toString());
e.printStackTrace();
return null;
}
}
}
|
3e038459ca69c62abba4235f9339baf4763412d9 | 2,432 | java | Java | src/main/java/at/o2xfs/memory/databind/introspect/CollectorBase.java | AndreasFagschlunger/o2xfs-memory-databind | b42a4b2effdf02642ae87d05d8960f6939064284 | [
"Apache-2.0"
] | null | null | null | src/main/java/at/o2xfs/memory/databind/introspect/CollectorBase.java | AndreasFagschlunger/o2xfs-memory-databind | b42a4b2effdf02642ae87d05d8960f6939064284 | [
"Apache-2.0"
] | null | null | null | src/main/java/at/o2xfs/memory/databind/introspect/CollectorBase.java | AndreasFagschlunger/o2xfs-memory-databind | b42a4b2effdf02642ae87d05d8960f6939064284 | [
"Apache-2.0"
] | null | null | null | 29 | 106 | 0.710591 | 1,446 | /* Jackson JSON-processor.
*
* Copyright (c) 2007- Tatu Saloranta, [email protected]
* Modifications Copyright (c) 2019 Andreas Fagschlunger
*/
package at.o2xfs.memory.databind.introspect;
import java.lang.annotation.Annotation;
import at.o2xfs.memory.databind.AnnotationIntrospector;
import at.o2xfs.memory.databind.cfg.MapperConfig;
import at.o2xfs.memory.databind.util.ClassUtil;
class CollectorBase {
protected final MapperConfig<?> config;
protected final AnnotationIntrospector intr;
public CollectorBase(MapperConfig<?> config) {
this.config = config;
intr = config == null ? null : config.getAnnotationIntrospector();
}
protected final AnnotationCollector collectAnnotations(Annotation[] annotations) {
AnnotationCollector result = AnnotationCollector.emptyCollector();
for (Annotation each : annotations) {
result = result.addOrOverride(each);
if (intr.isAnnotationBundle(each)) {
collectFromBundle(result, each);
}
}
return result;
}
protected final AnnotationCollector collectAnnotations(AnnotationCollector c, Annotation[] anns) {
for (int i = 0, end = anns.length; i < end; ++i) {
Annotation ann = anns[i];
c = c.addOrOverride(ann);
if (intr.isAnnotationBundle(ann)) {
c = collectFromBundle(c, ann);
}
}
return c;
}
protected final AnnotationCollector collectDefaultAnnotations(AnnotationCollector c, Annotation[] anns) {
for (int i = 0, end = anns.length; i < end; ++i) {
Annotation ann = anns[i];
if (!c.isPresent(ann)) {
c = c.addOrOverride(ann);
if (intr.isAnnotationBundle(ann)) {
c = collectDefaultFromBundle(c, ann);
}
}
}
return c;
}
protected final AnnotationCollector collectDefaultFromBundle(AnnotationCollector c, Annotation bundle) {
Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType());
for (int i = 0, end = anns.length; i < end; ++i) {
Annotation ann = anns[i];
if (!c.isPresent(ann)) {
c = c.addOrOverride(ann);
if (intr.isAnnotationBundle(ann)) {
c = collectFromBundle(c, ann);
}
}
}
return c;
}
protected final AnnotationCollector collectFromBundle(AnnotationCollector c, Annotation bundle) {
Annotation[] anns = ClassUtil.findClassAnnotations(bundle.annotationType());
for (Annotation each : anns) {
c = c.addOrOverride(each);
if (intr.isAnnotationBundle(each)) {
c = collectFromBundle(c, each);
}
}
return c;
}
}
|
3e0384daa2816af30fbce0e834d072e66889cce2 | 2,560 | java | Java | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/collections/NodeInterfacePair.java | netarch/batfish | 61b76041e1b144863be58cc4bb8e4441f8de7a06 | [
"Apache-2.0"
] | 10 | 2020-10-27T02:27:56.000Z | 2021-12-20T06:04:03.000Z | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/collections/NodeInterfacePair.java | dvandra/batfish | 18eba913c6e3d4269a41a3d1cb479cb4ef47be3d | [
"Apache-2.0"
] | null | null | null | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/collections/NodeInterfacePair.java | dvandra/batfish | 18eba913c6e3d4269a41a3d1cb479cb4ef47be3d | [
"Apache-2.0"
] | 2 | 2021-04-09T07:51:35.000Z | 2021-05-25T08:02:22.000Z | 29.090909 | 88 | 0.74375 | 1,447 | package org.batfish.datamodel.collections;
import static com.google.common.base.Preconditions.checkArgument;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.Interface;
/** Combination of node name and interface name */
@ParametersAreNonnullByDefault
public class NodeInterfacePair implements Serializable, Comparable<NodeInterfacePair> {
private static final String PROP_HOSTNAME = "hostname";
private static final String PROP_INTERFACE = "interface";
private static final long serialVersionUID = 1L;
@Nonnull private final String _hostname;
@Nonnull private final String _interfaceName;
@JsonCreator
private static NodeInterfacePair create(
@Nullable @JsonProperty(PROP_HOSTNAME) String node,
@Nullable @JsonProperty(PROP_INTERFACE) String iface) {
checkArgument(node != null, "Cannot create NodeInterfacePair with null node");
checkArgument(iface != null, "Cannot create NodeInterfacePair with null interface");
return new NodeInterfacePair(node, iface);
}
public NodeInterfacePair(String hostname, String interfaceName) {
_hostname = hostname;
_interfaceName = interfaceName;
}
public NodeInterfacePair(Interface iface) {
this(iface.getOwner().getHostname(), iface.getName());
}
/** Return node name */
@JsonProperty(PROP_HOSTNAME)
@Nonnull
public String getHostname() {
return _hostname;
}
/** Return node interface name */
@JsonProperty(PROP_INTERFACE)
@Nonnull
public String getInterface() {
return _interfaceName;
}
@Override
public String toString() {
return _hostname + ":" + _interfaceName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof NodeInterfacePair)) {
return false;
}
NodeInterfacePair that = (NodeInterfacePair) o;
return Objects.equals(_hostname, that._hostname)
&& Objects.equals(_interfaceName, that._interfaceName);
}
@Override
public int hashCode() {
return Objects.hash(_hostname, _interfaceName);
}
@Override
public int compareTo(NodeInterfacePair other) {
return Comparator.comparing(NodeInterfacePair::getHostname)
.thenComparing(NodeInterfacePair::getInterface)
.compare(this, other);
}
}
|
3e0385badeb9a33a891683cd081cb32e56958b3b | 1,358 | java | Java | skener/Skener.java | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | skener/Skener.java | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | skener/Skener.java | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | 33.121951 | 81 | 0.426362 | 1,448 | import java.util.*;
import java.io.*;
public class Skener {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
int zr = Integer.parseInt(st.nextToken());
int zc = Integer.parseInt(st.nextToken());
char[][] input = new char[r][c];
char[][] ans = new char[r*zr][c*zc];
for(int i = 0; i < r; i++) {
String line = br.readLine();
for(int j = 0; j < line.length(); j++) {
input[i][j] = line.charAt(j);
}
}
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
char current = input[i][j];
for(int x = zr*i; x < zr*i + zr; x++) {
for(int y = zc*j; y < zc*j + zc; y++) {
ans[x][y] = current;
}
}
}
}
for(int i = 0; i < r*zr; i++) {
for(int j = 0; j < c*zc; j++) {
System.out.print(ans[i][j]);
}
if(i != r*zr - 1) {
System.out.println();
}
}
}
}
|
3e03869ae2942bfd944005e386801e906ca1e24c | 2,496 | java | Java | Mage/src/main/java/mage/abilities/dynamicvalue/common/GreatestSharedCreatureTypeCount.java | mdschatz/mage | 56df62a743491e75f39ad2c92c8cf60392595e41 | [
"MIT"
] | null | null | null | Mage/src/main/java/mage/abilities/dynamicvalue/common/GreatestSharedCreatureTypeCount.java | mdschatz/mage | 56df62a743491e75f39ad2c92c8cf60392595e41 | [
"MIT"
] | null | null | null | Mage/src/main/java/mage/abilities/dynamicvalue/common/GreatestSharedCreatureTypeCount.java | mdschatz/mage | 56df62a743491e75f39ad2c92c8cf60392595e41 | [
"MIT"
] | null | null | null | 31.594937 | 94 | 0.639423 | 1,449 | package mage.abilities.dynamicvalue.common;
import mage.abilities.Ability;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.effects.Effect;
import mage.abilities.hint.Hint;
import mage.abilities.hint.ValueHint;
import mage.constants.SubType;
import mage.constants.SubTypeSet;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.util.CardUtil;
import java.util.*;
/**
* @author TheElk801
*/
public enum GreatestSharedCreatureTypeCount implements DynamicValue {
instance;
private static final Hint hint = new ValueHint(
"Greatest number of creatures you control that share a creature type", instance
);
@Override
public int calculate(Game game, Ability sourceAbility, Effect effect) {
return getValue(sourceAbility.getControllerId(), sourceAbility.getSourceId(), game);
}
public static int getValue(UUID playerId, UUID sourceId, Game game) {
List<Permanent> permanentList = game.getBattlefield().getActivePermanents(
StaticFilters.FILTER_CONTROLLED_CREATURE, playerId, sourceId, game
);
permanentList.removeIf(Objects::isNull);
int changelings = permanentList
.stream()
.filter(Objects::nonNull)
.filter(permanent1 -> permanent1.isAllCreatureTypes(game))
.mapToInt(x -> 1)
.sum();
permanentList.removeIf(permanent1 -> permanent1.isAllCreatureTypes(game));
Map<SubType, Integer> typeMap = new HashMap<>();
permanentList
.stream()
.map(permanent -> permanent.getSubtype(game))
.flatMap(Collection::stream)
.filter(subType -> subType.getSubTypeSet() == SubTypeSet.CreatureType)
.forEach(subType -> typeMap.compute(subType, CardUtil::setOrIncrementValue));
return changelings
+ typeMap
.values()
.stream()
.mapToInt(x -> x)
.max()
.orElse(0);
}
@Override
public GreatestSharedCreatureTypeCount copy() {
return instance;
}
@Override
public String toString() {
return "X";
}
@Override
public String getMessage() {
return "greatest number of creatures you control that have a creature type in common";
}
public static Hint getHint() {
return hint;
}
}
|
3e03878b5a719b5c761444f0306824c164ae893d | 876 | java | Java | src/main/java/moe/sigure/fabricmod/freecam/FakeClientPlayer.java | AmemiyaSigure/FreecamFabric | 5cee13ae40f2b161bc6099a74b84b8b6b3c01488 | [
"Apache-2.0"
] | null | null | null | src/main/java/moe/sigure/fabricmod/freecam/FakeClientPlayer.java | AmemiyaSigure/FreecamFabric | 5cee13ae40f2b161bc6099a74b84b8b6b3c01488 | [
"Apache-2.0"
] | 1 | 2020-12-06T03:12:50.000Z | 2020-12-06T04:39:59.000Z | src/main/java/moe/sigure/fabricmod/freecam/FakeClientPlayer.java | AmemiyaSigure/FreecamFabric | 5cee13ae40f2b161bc6099a74b84b8b6b3c01488 | [
"Apache-2.0"
] | null | null | null | 24.333333 | 93 | 0.726027 | 1,450 | package moe.sigure.fabricmod.freecam;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.Arm;
import net.minecraft.world.World;
public class FakeClientPlayer extends LivingEntity {
public FakeClientPlayer(EntityType<? extends LivingEntity> entityType_1, World world_1) {
super(entityType_1, world_1);
}
@Override
public Iterable<ItemStack> getArmorItems() {
return null;
}
@Override
public ItemStack getEquippedStack(EquipmentSlot var1) {
return new ItemStack(Items.AIR);
}
@Override
public void setEquippedStack(EquipmentSlot var1, ItemStack var2) {
}
@Override
public Arm getMainArm() {
return Arm.RIGHT;
}
}
|
3e038790520b757e760b1c4d4f9e3e483c000700 | 2,518 | java | Java | sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/WorkNote.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/WorkNote.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/WorkNote.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | 23.53271 | 90 | 0.586974 | 1,451 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* 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.slc.sli.ingestion;
import java.io.Serializable;
/**
* Unit of work, a structure that holds information about the work.
*
* @author okrook
*/
public class WorkNote implements Serializable {
private static final long serialVersionUID = 5462350263804401592L;
private final String batchJobId;
private final boolean hasErrors;
/**
* Constructor for the class.
*
* @param batchJobId
* @param tenantId
*/
public WorkNote(String batchJobId, boolean hasErrors) {
this.batchJobId = batchJobId;
this.hasErrors = hasErrors;
}
/**
* Gets the batch job id.
*
* @return String representing batch job id.
*/
public String getBatchJobId() {
return batchJobId;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((batchJobId == null) ? 0 : batchJobId.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WorkNote other = (WorkNote) obj;
if (batchJobId == null) {
if (other.batchJobId != null) {
return false;
}
} else if (!batchJobId.equals(other.batchJobId)) {
return false;
}
return true;
}
/**
* @return the hasErrors
*/
public boolean hasErrors() {
return hasErrors;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "SLIWorkNote [batchJobId=" + batchJobId + ", hasErrors=" + hasErrors + "]";
}
}
|
3e0388ab4e3abf86f73817df25c90f209a43da75 | 2,257 | java | Java | src/ForagingModel/space/ScentSexHistory.java | cbracis/ForagingModel | d7738dd113650b6e41adea469970e118dd736a10 | [
"MIT"
] | null | null | null | src/ForagingModel/space/ScentSexHistory.java | cbracis/ForagingModel | d7738dd113650b6e41adea469970e118dd736a10 | [
"MIT"
] | null | null | null | src/ForagingModel/space/ScentSexHistory.java | cbracis/ForagingModel | d7738dd113650b6e41adea469970e118dd736a10 | [
"MIT"
] | null | null | null | 25.647727 | 91 | 0.775809 | 1,452 | package ForagingModel.space;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import ForagingModel.core.MatrixUtils;
import ForagingModel.core.NdPoint;
public class ScentSexHistory extends AbstractMemory implements MemoryAssemblage
{
private ScentHistory scentHistory;
private ScentHistory femaleHistory;
protected ScentSexHistory(ScentHistory scentHistory, ScentHistory femaleHistory)
{
super(scentHistory.angProbInfo);
this.scentHistory = scentHistory;
this.femaleHistory = femaleHistory;
// set scent to use this probability cache
this.scentHistory.probabilityCache = this.probabilityCache;
}
@Override
public void execute(int currentInterval, int priority)
{
scentHistory.decay();
// female ScentHistory is shared and thus decayed on its own
}
@Override
public void learn(NdPoint consumerLocation)
{
// scent updating handled by ScentManager
}
@Override
public double[][] reportCurrentState(State state)
{
double[][] data;
switch (state)
{
case Scent:
data = scentHistory.reportCurrentState(state);
break;
case Resource:
case Predators:
default:
data = null;
break;
}
return data;
}
@Override
protected RealMatrix getProbabilities(NdPoint currentLocation)
{
// this is only for unused MemoryDestinationMovement
return null;
}
@Override
protected RealVector getAngularProbabilities(NdPoint currentLocation)
{
RealVector conspecificSafety = scentHistory.getConspecificSafety(currentLocation);
RealVector femalesProbs = femaleHistory.getScentAttractionProbabilities(currentLocation);
// resource and scent already use same probCache, but need to save femaleProbs
probabilityCache.updateAttractiveScent(femalesProbs);
// multiply female prob by conspecific safety which ranges [0,1] but doesn't sum to 1
RealVector aggregateProbs = MatrixUtils.multiply(femalesProbs, conspecificSafety);
if (!normalizeVector(aggregateProbs))
{
// all uniform, so base direction off conspecific safety, need to normalize first
aggregateProbs = conspecificSafety.copy();
normalizeVector(aggregateProbs);
}
probabilityCache.updateAggregate(aggregateProbs);
return aggregateProbs;
}
}
|
3e0389a53ecf8ba40624acb9846eefd91f207a3c | 2,120 | java | Java | src/breakout/PowerUp.java | danamulligan/game_dmm107 | 1d9980208b6a0c25888a51d5f2e585e1a7b9953a | [
"MIT"
] | null | null | null | src/breakout/PowerUp.java | danamulligan/game_dmm107 | 1d9980208b6a0c25888a51d5f2e585e1a7b9953a | [
"MIT"
] | null | null | null | src/breakout/PowerUp.java | danamulligan/game_dmm107 | 1d9980208b6a0c25888a51d5f2e585e1a7b9953a | [
"MIT"
] | null | null | null | 26.835443 | 111 | 0.654245 | 1,453 | package breakout;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
/**
* PowerUp create a positive side effect, a Circle that drops towards the paddle and can be activated if caught
* Dependencies:
* package breakout
* Classes Circle, Paint, and Color
* Main Class
* PowerUp is created as a PowerUpBrick is broken, but PowerUp doesn't depend on PowerUpBrick
*/
public class PowerUp {
public static final int POWER_UP_RADIUS = 10;
public static final Paint POWER_UP_COLOR = Color.ORANGE;
private String powerUpType;
private int powerUpSpeed=80;
private Circle powerUp;
/**
* Constructor
* set powerUp as a new Circle in the position of xPosition and yPosition (where the brick holding it was)
* et powerUpType to type, xPosition to xPos, and yPosition to yPos
* @param type
* @param xPos
* @param yPos
*/
public PowerUp(String type, int xPos, int yPos){
powerUp = new Circle(xPos+POWER_UP_RADIUS, yPos+POWER_UP_RADIUS,POWER_UP_RADIUS);
powerUp.setFill(POWER_UP_COLOR);
powerUpType = type;
}
/**
* default constructor
*/
public PowerUp(){
this(null, Main.SIZE+POWER_UP_RADIUS, Main.SIZE+POWER_UP_RADIUS);
}
/**
* allow other objects to see what type it is
* @return powerUpType
*/
public String getType(){
return powerUpType;
}
/**
* allow the Circle to be added to a collection
* @return powerUp
*/
public Circle getNode(){
return powerUp;
}
/**
* move the powerUp off the screen so it doesn't interfere with game play
*/
public void caught(){
powerUp.setCenterX(Main.SIZE*2);
powerUp.setCenterY(Main.SIZE*2);
powerUp.setFill(Main.BACKGROUND);
}
/**
* allow power up to fall at powerUpSpeed to the bottom of the screen
* @param elapsedTime
*/
public void updateCenter(double elapsedTime){
powerUp.setCenterY(powerUp.getCenterY() + powerUpSpeed * elapsedTime);
}
}
|
3e038a185d1c4289ec38f8387f7ffaedd102e13b | 1,628 | java | Java | src/main/java/ecommercejava/cms/icommyjava/paymentmethods/check/CheckModule.java | worldthem/jcomcms | 802832a498d91fc2a9401aaa39c9b8630351a9d1 | [
"MIT"
] | null | null | null | src/main/java/ecommercejava/cms/icommyjava/paymentmethods/check/CheckModule.java | worldthem/jcomcms | 802832a498d91fc2a9401aaa39c9b8630351a9d1 | [
"MIT"
] | null | null | null | src/main/java/ecommercejava/cms/icommyjava/paymentmethods/check/CheckModule.java | worldthem/jcomcms | 802832a498d91fc2a9401aaa39c9b8630351a9d1 | [
"MIT"
] | 1 | 2021-11-09T11:25:21.000Z | 2021-11-09T11:25:21.000Z | 25.84127 | 172 | 0.668305 | 1,454 | package ecommercejava.cms.icommyjava.paymentmethods.check;
import ecommercejava.cms.icommyjava.entity.Lang;
import ecommercejava.cms.icommyjava.helper.Language;
public class CheckModule {
public String getTitle() {
return title== null? "Check payments": Language.getLangData(title);
}
public void setTitle(String title) {
this.title = Language.saveSimple(title, this.title, lang );
}
public String getDescription() {
return description== null? "Please send a check to Store Name, Store Street, Store Town, Store State / County, Store Postcode." : Language.getLangData(description);
}
public void setDescription(String description) {
this.description= Language.saveSimple(description, this.description, lang );
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getInstruction() {
return Language.getLangData(instruction);
}
public void setInstruction(String instruction) {
this.instruction= Language.saveSimple(instruction, this.instruction, lang);
}
public Boolean getNoimage() {
return noimage == null ? false : true;
}
public void setNoimage(String noimage) {
this.noimage = noimage;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
private String noimage;
private String image;
private Lang instruction;
private Lang title;
private Lang description;
private String lang;
}
|
3e038b0a277c8c1c548003a8d19f24b8f4bc7354 | 5,313 | java | Java | model_zoo/official/lite/MindSpore_inhand/app/src/main/java/com/mindspore/himindspore/ui/guide/SplashActivity.java | chncwang/mindspore | 6dac92aedf0aa1541d181e6aedab29aaadc2dafb | [
"Apache-2.0"
] | 1 | 2021-03-10T09:05:13.000Z | 2021-03-10T09:05:13.000Z | model_zoo/official/lite/MindSpore_inhand/app/src/main/java/com/mindspore/himindspore/ui/guide/SplashActivity.java | king4arabs/mindspore | bc38590e5300588aa551355836043af0ea092a72 | [
"Apache-2.0"
] | null | null | null | model_zoo/official/lite/MindSpore_inhand/app/src/main/java/com/mindspore/himindspore/ui/guide/SplashActivity.java | king4arabs/mindspore | bc38590e5300588aa551355836043af0ea092a72 | [
"Apache-2.0"
] | null | null | null | 33.20625 | 135 | 0.691135 | 1,455 | /**
* Copyright 2020 Huawei Technologies Co., Ltd
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.mindspore.himindspore.ui.guide;
import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import com.mindspore.customview.countdown.CountDownView;
import com.mindspore.himindspore.R;
import com.mindspore.himindspore.base.BaseActivity;
import com.mindspore.himindspore.ui.main.MainActivity;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
public class SplashActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
private static final String TAG = "SplashActivity";
private static final String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA};
private static final int REQUEST_PERMISSION = 1;
private CountDownView cdvTime;
@Override
protected void init() {
cdvTime = findViewById(R.id.cdv_time);
initCountDownView();
}
private void initCountDownView() {
cdvTime.setTime(3);
cdvTime.start();
cdvTime.setOnLoadingFinishListener(() -> startPermissionsTask());
cdvTime.setOnClickListener(view -> {
cdvTime.stop();
startPermissionsTask();
});
}
@Override
public int getLayout() {
return R.layout.activity_splash;
}
@AfterPermissionGranted(REQUEST_PERMISSION)
private void startPermissionsTask() {
if (hasPermissions()) {
setHandler();
} else {
EasyPermissions.requestPermissions(this,
this.getResources().getString(R.string.app_need_permission),
REQUEST_PERMISSION, PERMISSIONS);
}
}
private boolean hasPermissions() {
return EasyPermissions.hasPermissions(this, PERMISSIONS);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode,
permissions, grantResults, SplashActivity.this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
if (EasyPermissions.somePermissionPermanentlyDenied(SplashActivity.this, perms)) {
openAppDetails();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
setHandler();
}
}
private void openAppDetails() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getResources().getString(R.string.app_need_permission));
builder.setPositiveButton(getResources().getString(R.string.app_permission_by_hand), (dialog, which) -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
});
builder.setNegativeButton(getResources().getString(R.string.cancel), null);
builder.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
private void setHandler() {
enterMainView();
}
private void enterMainView() {
Intent intent = new Intent();
intent.setClass(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (cdvTime != null && cdvTime.isShown()) {
cdvTime.stop();
}
}
} |
3e038b9b0c0abee8aa9958a9e0a473f7630d8e7d | 2,896 | java | Java | shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java | jslohner/java-deployshoppingcart | 12a093048be067a5966eb54c7608f9eded41c825 | [
"MIT"
] | null | null | null | shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java | jslohner/java-deployshoppingcart | 12a093048be067a5966eb54c7608f9eded41c825 | [
"MIT"
] | null | null | null | shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java | jslohner/java-deployshoppingcart | 12a093048be067a5966eb54c7608f9eded41c825 | [
"MIT"
] | null | null | null | 21.294118 | 106 | 0.728591 | 1,456 | package com.lambdaschool.shoppingcart.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "users")
public class User
extends Auditable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long userid;
@NotNull
@Column(nullable = false,
unique = true)
private String username;
@NotNull
@Column(nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
private String comments;
@OneToMany(mappedBy = "user",
cascade = CascadeType.ALL)
@JsonIgnoreProperties(value = "user",
allowSetters = true)
private List<Cart> carts = new ArrayList<>();
@OneToMany(mappedBy = "user",
cascade = CascadeType.ALL)
@JsonIgnoreProperties(value = "user",
allowSetters = true)
private List<UserRoles> roles = new ArrayList<>();
public User() {
}
public User(String username, String password, String comments, List<Cart> carts, List<UserRoles> roles) {
this.username = username;
this.password = password;
this.comments = comments;
this.carts = carts;
this.roles = roles;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getUsername() {
if (username == null) {
return null;
} else {
return username.toLowerCase();
}
}
public void setUsername(String username) {
this.username = username.toLowerCase() ;
}
public String getPassword() {
return password;
}
public void setPasswordNoEncrypt(String password) {
this.password = password;
}
public void setPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
this.password = passwordEncoder.encode(password);
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public List<Cart> getCarts() {
return carts;
}
public void setCarts(List<Cart> carts) {
this.carts = carts;
}
public List<UserRoles> getRoles() {
return roles;
}
public void setRoles(List<UserRoles> roles) {
this.roles = roles;
}
public void addRole(Role role) {
roles.add(new UserRoles(this, role));
}
@JsonIgnore
public List<SimpleGrantedAuthority> getAuthority()
{
List<SimpleGrantedAuthority> rtnList = new ArrayList<>();
for (UserRoles r : this.roles)
{
String myRole = "ROLE_" + r
.getRole()
.getName()
.toUpperCase();
rtnList.add(new SimpleGrantedAuthority(myRole));
}
return rtnList;
}
}
|
3e038bab0c105233b017e85662ad40b388ad4702 | 302 | java | Java | src/main/java/com/ninetailsoftware/model/facts/RequestContainer.java | Tierran/home-automation-model | 100152696f2ff0fdfcf0ce863d0e60bad8774e70 | [
"MIT"
] | null | null | null | src/main/java/com/ninetailsoftware/model/facts/RequestContainer.java | Tierran/home-automation-model | 100152696f2ff0fdfcf0ce863d0e60bad8774e70 | [
"MIT"
] | null | null | null | src/main/java/com/ninetailsoftware/model/facts/RequestContainer.java | Tierran/home-automation-model | 100152696f2ff0fdfcf0ce863d0e60bad8774e70 | [
"MIT"
] | null | null | null | 18.875 | 57 | 0.784768 | 1,457 | package com.ninetailsoftware.model.facts;
public class RequestContainer {
private SimpleSwitch simpleSwitch = new SimpleSwitch();
public SimpleSwitch getSimpleSwitch() {
return simpleSwitch;
}
public void setSimpleSwitch(SimpleSwitch simpleSwitch) {
this.simpleSwitch = simpleSwitch;
}
}
|
3e038bc27b6da5f43814e473d769415430fc7cee | 3,390 | java | Java | ide/db.dataview/src/org/netbeans/modules/db/dataview/output/DataViewDBTable.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | ide/db.dataview/src/org/netbeans/modules/db/dataview/output/DataViewDBTable.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | ide/db.dataview/src/org/netbeans/modules/db/dataview/output/DataViewDBTable.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 30 | 93 | 0.684956 | 1,458 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.netbeans.modules.db.dataview.output;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.netbeans.modules.db.dataview.meta.DBColumn;
import org.netbeans.modules.db.dataview.meta.DBTable;
/**
* Wrapper class provides ordered columns and tooltips
*
* @author Ahimanikya Satapathy
*/
public class DataViewDBTable {
private final DBTable[] dbTables;
private final List<DBColumn> columns;
public DataViewDBTable(Collection<DBTable> tables) {
assert tables != null;
dbTables = new DBTable[tables.size()];
List<DBColumn> cols = new ArrayList<>();
for (DBTable tbl : tables.toArray(dbTables)) {
cols.addAll(tbl.getColumnList());
}
Collections.sort(cols, new ColumnOrderComparator());
columns = Collections.unmodifiableList(cols);
}
public DBTable getTable(int index) {
return dbTables[index];
}
public int getTableCount() {
return dbTables.length;
}
public boolean hasOneTable() {
return dbTables != null && dbTables.length == 1 && !dbTables[0].getName().equals("");
}
public String getFullyQualifiedName(int index, boolean quoteAlways) {
return dbTables[index].getFullyQualifiedName(quoteAlways);
}
public DBColumn getColumn(int index) {
return columns.get(index);
}
public int getColumnType(int index) {
return columns.get(index).getJdbcType();
}
public String getColumnName(int index) {
return columns.get(index).getName();
}
public String getQualifiedName(int index, boolean quoteAlways) {
return columns.get(index).getQualifiedName(quoteAlways);
}
public int getColumnCount() {
return columns.size();
}
public List<DBColumn> getColumns() {
return Collections.unmodifiableList(columns);
}
public synchronized Map<String,DBColumn> getColumnMap() {
Map<String, DBColumn> colMap = new HashMap<>();
for (DBTable tbl : dbTables) {
colMap.putAll(tbl.getColumns());
}
return Collections.unmodifiableMap(colMap);
}
private final class ColumnOrderComparator implements Comparator<DBColumn> {
private ColumnOrderComparator() {
}
@Override
public int compare(DBColumn col1, DBColumn col2) {
return col1.getOrdinalPosition() - col2.getOrdinalPosition();
}
}
}
|
3e038bccf5b89f5ef06b8bbf9d80023d11933e45 | 1,381 | java | Java | src/java/com/canoo/grails/ulc/server/CreateGrailsULCSessionCommand.java | canoo/grails-ulc | a2a4007393fa4235ff0e36975a70edb643b23409 | [
"Apache-2.0"
] | null | null | null | src/java/com/canoo/grails/ulc/server/CreateGrailsULCSessionCommand.java | canoo/grails-ulc | a2a4007393fa4235ff0e36975a70edb643b23409 | [
"Apache-2.0"
] | null | null | null | src/java/com/canoo/grails/ulc/server/CreateGrailsULCSessionCommand.java | canoo/grails-ulc | a2a4007393fa4235ff0e36975a70edb643b23409 | [
"Apache-2.0"
] | null | null | null | 46.033333 | 105 | 0.812455 | 1,459 | package com.canoo.grails.ulc.server;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.codehaus.groovy.grails.support.PersistenceContextInterceptor;
import org.springframework.context.ApplicationContext;
import com.ulcjava.base.application.event.IRoundTripListener;
import com.ulcjava.base.application.event.RoundTripEvent;
import com.ulcjava.base.server.ApplicationConfiguration;
import com.ulcjava.base.server.IContainerServices;
import com.ulcjava.base.server.ISession;
import com.ulcjava.base.server.ULCSession;
import com.ulcjava.container.servlet.server.CreateSessionCommand;
import com.ulcjava.container.servlet.server.ICommandInfo;
public class CreateGrailsULCSessionCommand extends CreateSessionCommand {
public CreateGrailsULCSessionCommand(ICommandInfo commandInfo) {
super(commandInfo);
}
protected ISession createSession(String applicationClassName, IContainerServices containerServices) {
String alias = GrailsULCApplicationConfiguration.getApplicationAlias(applicationClassName);
ApplicationConfiguration config = GrailsULCApplicationConfiguration.getInstance(alias);
if (config != null) {
return config.getSessionProvider(containerServices).createSession();
}
return GrailsULCSessionInitializer.createSession(applicationClassName, containerServices);
}
} |
3e038c81a44a3e555687b3e760a8c25b6065eecb | 626 | java | Java | server/server-oauth2-service/src/test/java/com/cnec5/it/selfservice/server/Oauth2PasswordTests.java | John-zzy/it-selfservice | 91bb7891e6bc2f6eedca0ff9709fff6cbef7ddb6 | [
"Apache-2.0"
] | 1 | 2020-01-14T08:53:32.000Z | 2020-01-14T08:53:32.000Z | server/server-oauth2-service/src/test/java/com/cnec5/it/selfservice/server/Oauth2PasswordTests.java | John-zzy/it-selfservice | 91bb7891e6bc2f6eedca0ff9709fff6cbef7ddb6 | [
"Apache-2.0"
] | null | null | null | server/server-oauth2-service/src/test/java/com/cnec5/it/selfservice/server/Oauth2PasswordTests.java | John-zzy/it-selfservice | 91bb7891e6bc2f6eedca0ff9709fff6cbef7ddb6 | [
"Apache-2.0"
] | null | null | null | 26.083333 | 73 | 0.766773 | 1,460 | package com.cnec5.it.selfservice.server;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
public class Oauth2PasswordTests {
@Resource
private BCryptPasswordEncoder passwordEncoder;
@Test
public void test_bean_oauth2_password() {
System.out.println(passwordEncoder.encode("123456"));
}
}
|
3e038cd0a44f922b8a1de68299ff499c23756cf0 | 6,473 | java | Java | jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/lodcalc/DistanceLodCalculator.java | Markil3/jmonkeyengine | 49383a5c0c80557b99275bbe0d9af42e7527bd03 | [
"BSD-3-Clause"
] | 3,139 | 2015-01-01T10:18:09.000Z | 2022-03-31T12:51:24.000Z | jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/lodcalc/DistanceLodCalculator.java | Markil3/jmonkeyengine | 49383a5c0c80557b99275bbe0d9af42e7527bd03 | [
"BSD-3-Clause"
] | 1,385 | 2015-01-01T00:21:56.000Z | 2022-03-31T18:36:04.000Z | jme3-terrain/src/main/java/com/jme3/terrain/geomipmap/lodcalc/DistanceLodCalculator.java | Markil3/jmonkeyengine | 49383a5c0c80557b99275bbe0d9af42e7527bd03 | [
"BSD-3-Clause"
] | 1,306 | 2015-01-01T10:18:11.000Z | 2022-03-27T06:38:48.000Z | 33.890052 | 135 | 0.648695 | 1,461 | /*
* Copyright (c) 2009-2020 jMonkeyEngine
* 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 'jMonkeyEngine' 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 com.jme3.terrain.geomipmap.lodcalc;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.math.Vector3f;
import com.jme3.terrain.geomipmap.TerrainPatch;
import com.jme3.terrain.geomipmap.UpdatedTerrainPatch;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
/**
* Calculates the LOD of the terrain based on its distance from the
* cameras. Taking the minimum distance from all cameras.
*
* @author bowens
*/
public class DistanceLodCalculator implements LodCalculator {
private int size; // size of a terrain patch
private float lodMultiplier = 2;
private boolean turnOffLod = false;
public DistanceLodCalculator() {
}
public DistanceLodCalculator(int patchSize, float multiplier) {
this.size = patchSize;
this.lodMultiplier = multiplier;
}
@Override
public boolean calculateLod(TerrainPatch terrainPatch, List<Vector3f> locations, HashMap<String, UpdatedTerrainPatch> updates) {
if (locations == null || locations.isEmpty())
return false;// no camera yet
float distance = getCenterLocation(terrainPatch).distance(locations.get(0));
if (turnOffLod) {
// set to full detail
int prevLOD = terrainPatch.getLod();
UpdatedTerrainPatch utp = updates.get(terrainPatch.getName());
if (utp == null) {
utp = new UpdatedTerrainPatch(terrainPatch);
updates.put(utp.getName(), utp);
}
utp.setNewLod(0);
utp.setPreviousLod(prevLOD);
//utp.setReIndexNeeded(true);
return true;
}
// go through each lod level to find the one we are in
for (int i = 0; i <= terrainPatch.getMaxLod(); i++) {
if (distance < getLodDistanceThreshold() * (i + 1)*terrainPatch.getWorldScaleCached().x || i == terrainPatch.getMaxLod()) {
boolean reIndexNeeded = false;
if (i != terrainPatch.getLod()) {
reIndexNeeded = true;
//System.out.println("lod change: "+lod+" > "+i+" dist: "+distance);
}
int prevLOD = terrainPatch.getLod();
UpdatedTerrainPatch utp = updates.get(terrainPatch.getName());
if (utp == null) {
utp = new UpdatedTerrainPatch(terrainPatch);//save in here, do not update actual variables
updates.put(utp.getName(), utp);
}
utp.setNewLod(i);
utp.setPreviousLod(prevLOD);
//utp.setReIndexNeeded(reIndexNeeded);
return reIndexNeeded;
}
}
return false;
}
protected Vector3f getCenterLocation(TerrainPatch terrainPatch) {
Vector3f loc = terrainPatch.getWorldTranslationCached();
loc.x += terrainPatch.getSize()*terrainPatch.getWorldScaleCached().x / 2;
loc.z += terrainPatch.getSize()*terrainPatch.getWorldScaleCached().z / 2;
return loc;
}
@Override
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(size, "patchSize", 32);
oc.write(lodMultiplier, "lodMultiplier", 32);
}
@Override
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
size = ic.readInt("patchSize", 32);
lodMultiplier = ic.readFloat("lodMultiplier", 32f);
}
@Override
public LodCalculator clone() {
DistanceLodCalculator clone = new DistanceLodCalculator(size, lodMultiplier);
return clone;
}
@Override
public String toString() {
return "DistanceLodCalculator "+size+"*"+lodMultiplier;
}
/**
* Gets the camera distance where the LOD level will change
*/
protected float getLodDistanceThreshold() {
return size*lodMultiplier;
}
/**
* Does this calculator require the terrain to have the difference of
* LOD levels of neighbours to be more than 1.
*/
@Override
public boolean usesVariableLod() {
return false;
}
public float getLodMultiplier() {
return lodMultiplier;
}
public void setLodMultiplier(float lodMultiplier) {
this.lodMultiplier = lodMultiplier;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public void turnOffLod() {
turnOffLod = true;
}
@Override
public boolean isLodOff() {
return turnOffLod;
}
@Override
public void turnOnLod() {
turnOffLod = false;
}
}
|
3e038cd507b5a0e3d2e2b3c75d86de29799049c6 | 1,180 | java | Java | src/main/java/pt/ipp/isep/dei/esoft/pot/controller/DefinirCategoriaController.java | atuhrr/ESOFT-ISEP | d989da51f49475c21c6a02ced68a2b9d8e34efe5 | [
"MIT"
] | null | null | null | src/main/java/pt/ipp/isep/dei/esoft/pot/controller/DefinirCategoriaController.java | atuhrr/ESOFT-ISEP | d989da51f49475c21c6a02ced68a2b9d8e34efe5 | [
"MIT"
] | null | null | null | src/main/java/pt/ipp/isep/dei/esoft/pot/controller/DefinirCategoriaController.java | atuhrr/ESOFT-ISEP | d989da51f49475c21c6a02ced68a2b9d8e34efe5 | [
"MIT"
] | null | null | null | 28.780488 | 86 | 0.742373 | 1,462 | /*
* 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 pt.ipp.isep.dei.esoft.pot.controller;
import pt.ipp.isep.dei.esoft.pot.model.*;
import java.util.List;
public class DefinirCategoriaController {
private Plataforma m_oPlataforma;
private CategoriaTarefa categoriaTarefa;
public List<AreaAtividade> getListaAreaAtividade() {
return this.m_oPlataforma.getListaAreaAtividade();
}
public CategoriaTarefa novaCategoriaTarefa(String desc, String IDArea) {
return new CategoriaTarefa(desc, m_oPlataforma.getAreaAtividadeById(IDArea));
}
public List<CompetenciaTecnica> getListaCompetenciaTecnica() {
return this.m_oPlataforma.getListaCompetenciaTecnica();
}
public CompetenciaTecnica novaCompetenciaTecnica(String idComp,boolean obrgComp) {
return m_oPlataforma.getCompetenciaById(idComp);
}
public boolean registaCategoria(CategoriaTarefa categoriaTarefa) {
return this.m_oPlataforma.registaCategoria(categoriaTarefa);
}
}
|
3e038cef61cd63c06b7c372d271773f43ff01542 | 390 | java | Java | src/main/java/com/n11/loanapplication/gen/utilities/MessageConstants.java | n11-TalentHub-Java-Bootcamp/n11-talenthub-bootcamp-graduation-project-arikanogluulku | 1adbb52cbf08254c315b08dad7ad925abe0a0574 | [
"MIT"
] | null | null | null | src/main/java/com/n11/loanapplication/gen/utilities/MessageConstants.java | n11-TalentHub-Java-Bootcamp/n11-talenthub-bootcamp-graduation-project-arikanogluulku | 1adbb52cbf08254c315b08dad7ad925abe0a0574 | [
"MIT"
] | null | null | null | src/main/java/com/n11/loanapplication/gen/utilities/MessageConstants.java | n11-TalentHub-Java-Bootcamp/n11-talenthub-bootcamp-graduation-project-arikanogluulku | 1adbb52cbf08254c315b08dad7ad925abe0a0574 | [
"MIT"
] | 1 | 2022-02-08T14:19:22.000Z | 2022-02-08T14:19:22.000Z | 30 | 122 | 0.751282 | 1,463 | package com.n11.loanapplication.gen.utilities;
import java.math.BigDecimal;
import java.text.NumberFormat;
public class MessageConstants {
public static final String CREDIT_APPLICATION_RESULT_SMS = "Dear %s , credit application result is %s . Limit : %s ";
public static String currencyFormat(BigDecimal n) {
return NumberFormat.getCurrencyInstance().format(n);
}
}
|
3e038d8c4ec6b752396a5cfeda40fc50d8077210 | 817 | java | Java | src/main/java/io/tarantool/driver/exceptions/TarantoolTimeoutException.java | akudiyar/tarantool-cartridge-java-driver | 42999fe5c4b85c96009c2294bd484df061b6c9d4 | [
"BSD-2-Clause"
] | 18 | 2020-10-13T12:27:59.000Z | 2022-02-18T20:36:56.000Z | src/main/java/io/tarantool/driver/exceptions/TarantoolTimeoutException.java | akudiyar/tarantool-cartridge-java-driver | 42999fe5c4b85c96009c2294bd484df061b6c9d4 | [
"BSD-2-Clause"
] | 113 | 2020-10-18T11:35:17.000Z | 2022-03-30T11:04:08.000Z | src/main/java/io/tarantool/driver/exceptions/TarantoolTimeoutException.java | akudiyar/tarantool-cartridge-java-driver | 42999fe5c4b85c96009c2294bd484df061b6c9d4 | [
"BSD-2-Clause"
] | 3 | 2020-11-09T16:05:36.000Z | 2021-04-15T04:01:03.000Z | 28.172414 | 89 | 0.724602 | 1,464 | package io.tarantool.driver.exceptions;
import io.tarantool.driver.api.retry.TarantoolRequestRetryPolicies;
/**
* The exception that was thrown from {@link TarantoolRequestRetryPolicies}
*
* @author Artyom Dubinin
*/
public class TarantoolTimeoutException extends TarantoolException {
private static final String message = "Operation timeout value exceeded after %s ms";
public TarantoolTimeoutException(Throwable cause) {
super(cause);
}
public TarantoolTimeoutException(Long time) {
super(String.format(message, time));
}
public TarantoolTimeoutException(Long time, Throwable cause) {
super(String.format(message, time), cause);
}
public TarantoolTimeoutException(String format, Object... args) {
super(String.format(format, args));
}
}
|
3e038dee7f6bee75a1464cac44c2f5deca2c8d03 | 1,816 | java | Java | ts4udev/UmarWorkProject-main/src/main/java/com/perficient/util/ReadJsonObject.java | laziestcoder/learnig_or_poc | 3e0fa4f11226929377ceb7e7c64683182553cb6e | [
"MIT"
] | null | null | null | ts4udev/UmarWorkProject-main/src/main/java/com/perficient/util/ReadJsonObject.java | laziestcoder/learnig_or_poc | 3e0fa4f11226929377ceb7e7c64683182553cb6e | [
"MIT"
] | null | null | null | ts4udev/UmarWorkProject-main/src/main/java/com/perficient/util/ReadJsonObject.java | laziestcoder/learnig_or_poc | 3e0fa4f11226929377ceb7e7c64683182553cb6e | [
"MIT"
] | null | null | null | 23.282051 | 69 | 0.673458 | 1,465 | package com.perficient.util;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
/**
* This is utility to read the JSON object of Webservices.
* @author pooja.manna
*
*/
public class ReadJsonObject{
/**
* This method is used to read the Json Object response
* @param apiLink
*/
public void apiTesting(String apiLink ){
try {
URL url = new URL(apiLink);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException(" HTTP error code : "
+ conn.getResponseCode());
}
Scanner scan = new Scanner(url.openStream());
String entireResponse = new String();
while (scan.hasNext())
entireResponse =entireResponse+ scan.nextLine();
System.out.println("Response : "+entireResponse);
scan.close();
JSONObject obj =new JSONObject(entireResponse);
String responseCode = obj.getString("status");
System.out.println("status : " + responseCode);
org.json.JSONArray arr = obj.getJSONArray("results");
for (int i = 0; i < arr.length(); i++) {
String placeid = arr.getJSONObject(i).getString("place_id");
System.out.println("Place id : " + placeid);
String formatAddress = arr.getJSONObject(i).getString(
"formatted_address");
System.out.println("Address : " + formatAddress);
//validating Address as per the requirement
if(formatAddress.equalsIgnoreCase("Chicago, IL, USA"))
{
System.out.println("Address is as Expected");
}
else
{
System.out.println("Address is not as Expected");
}
}
conn.disconnect();
}catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e038e2e6fe8c00f95eb536675b4925f8c2dcb5f | 831 | java | Java | src/main/java/duelistmod/metrics/builders/MiniModBundleBuilder.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 3 | 2019-06-20T08:52:04.000Z | 2020-06-17T19:32:05.000Z | src/main/java/duelistmod/metrics/builders/MiniModBundleBuilder.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 7 | 2019-04-22T12:26:08.000Z | 2021-01-18T02:45:58.000Z | src/main/java/duelistmod/metrics/builders/MiniModBundleBuilder.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 2 | 2019-12-06T14:30:34.000Z | 2020-03-29T15:43:02.000Z | 22.459459 | 66 | 0.666667 | 1,466 | package duelistmod.metrics.builders;
import duelistmod.metrics.*;
import java.util.*;
public class MiniModBundleBuilder {
private String id;
private String modVersion;
private String name;
private List<String> authors;
public MiniModBundleBuilder setID(String id) {
this.id = id;
return this;
}
public MiniModBundleBuilder setName(String name) {
this.name = name;
return this;
}
public MiniModBundleBuilder setModVersion(String modVersion) {
this.modVersion = modVersion;
return this;
}
public MiniModBundleBuilder setAuthors(List<String> authors) {
this.authors = authors;
return this;
}
public MiniModBundle createMiniModBundle() {
return new MiniModBundle(id, modVersion, name, authors);
}
}
|
3e038e413231acb7498f7473e5203908ae331546 | 1,772 | java | Java | mixbookBackend/Mixbook-java/src/main/java/com/mixbook/springmvc/Controllers/StyleController.java | alexcoll/mixbook | 27f74b59cd05572a0fb3bd0d584b6fe5ef35e882 | [
"Apache-2.0"
] | 1 | 2017-08-30T15:52:31.000Z | 2017-08-30T15:52:31.000Z | mixbookBackend/Mixbook-java/src/main/java/com/mixbook/springmvc/Controllers/StyleController.java | alexcoll/mixbook | 27f74b59cd05572a0fb3bd0d584b6fe5ef35e882 | [
"Apache-2.0"
] | null | null | null | mixbookBackend/Mixbook-java/src/main/java/com/mixbook/springmvc/Controllers/StyleController.java | alexcoll/mixbook | 27f74b59cd05572a0fb3bd0d584b6fe5ef35e882 | [
"Apache-2.0"
] | null | null | null | 33.433962 | 145 | 0.775959 | 1,467 | package com.mixbook.springmvc.Controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mixbook.springmvc.Exceptions.UnknownServerErrorException;
import com.mixbook.springmvc.Models.Style;
import com.mixbook.springmvc.Services.StyleService;
/**
* Provides API endpoints for style functions.
* @author John Tyler Preston
* @version 1.0
*/
@Controller
@RequestMapping("/style")
public class StyleController {
/**
* Provides ability to access style service layer functions.
*/
@Autowired
StyleService styleService;
/**
* Loads a complete list of styles.
* @return a <code>ResponseEntity</code> of type <code>List</code> of type <code>Style</code> of all styles. It contains each style's
* information, information regarding the success or failure of request, along with an HTTP status code, 200 for success and 500 for an internal
* server error.
*/
@RequestMapping(value = "/getStyles", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Style>> getStyles() {
List<Style> tempList = new ArrayList<Style>();
try {
tempList = styleService.getStyles();
} catch (UnknownServerErrorException e) {
List<Style> emptyList = new ArrayList<Style>();
return new ResponseEntity<List<Style>>(emptyList, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<List<Style>>(tempList, HttpStatus.OK);
}
}
|
3e038eaf4cdd145579398d27957c76e3ed359429 | 1,322 | java | Java | gen/com/dexscript/psi/GoImportSpec.java | dexscript/intellij-plugin | dafa5416e1d59b0598603978b1b179f75bd13d72 | [
"Apache-2.0"
] | 1 | 2018-10-08T05:43:15.000Z | 2018-10-08T05:43:15.000Z | gen/com/dexscript/psi/GoImportSpec.java | dexscript/intellij-plugin | dafa5416e1d59b0598603978b1b179f75bd13d72 | [
"Apache-2.0"
] | null | null | null | gen/com/dexscript/psi/GoImportSpec.java | dexscript/intellij-plugin | dafa5416e1d59b0598603978b1b179f75bd13d72 | [
"Apache-2.0"
] | null | null | null | 24.481481 | 93 | 0.75416 | 1,468 | /*
* Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan
*
* 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.
*/
// This is a generated file. Not intended for manual editing.
package com.dexscript.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.StubBasedPsiElement;
import com.dexscript.stubs.GoImportSpecStub;
public interface GoImportSpec extends GoNamedElement, StubBasedPsiElement<GoImportSpecStub> {
@NotNull
GoImportString getImportString();
@Nullable
PsiElement getDot();
@Nullable
PsiElement getIdentifier();
String getAlias();
String getLocalPackageName();
boolean shouldGoDeeper();
boolean isForSideEffects();
boolean isDot();
@NotNull
String getPath();
String getName();
boolean isCImport();
}
|
3e038eee949ab53bee561734cb644d1813a9effd | 163 | java | Java | funBall/src/com/game/util/ID.java | leplopp/funball | f4bbf99531eca89f978aef303fe86dffef0b1724 | [
"MIT"
] | null | null | null | funBall/src/com/game/util/ID.java | leplopp/funball | f4bbf99531eca89f978aef303fe86dffef0b1724 | [
"MIT"
] | null | null | null | funBall/src/com/game/util/ID.java | leplopp/funball | f4bbf99531eca89f978aef303fe86dffef0b1724 | [
"MIT"
] | null | null | null | 9.588235 | 23 | 0.496933 | 1,469 | package com.game.util;
public enum ID {
player(),
Block(),
Crate(),
Bullet(),
Ball(),
Spikes(),
Ballon(),
Game(),
Menu(),
Enemy();
}
|
3e03900ea74456f5dafe31f3468d89c04d7a0f5a | 5,185 | java | Java | src/main/java/es/tid/vntm/LigthPathCreateIP.java | Telefonica/netphony-gmpls-emulator | 843036b279e4550aa7f030e5d0a49638057f3441 | [
"Apache-2.0"
] | 9 | 2015-10-28T11:11:34.000Z | 2021-11-21T11:40:07.000Z | src/main/java/es/tid/vntm/LigthPathCreateIP.java | Telefonica/netphony-gmpls-emulator | 843036b279e4550aa7f030e5d0a49638057f3441 | [
"Apache-2.0"
] | 3 | 2015-11-12T18:45:33.000Z | 2017-01-04T15:04:24.000Z | src/main/java/es/tid/vntm/LigthPathCreateIP.java | Telefonica/netphony-gmpls-emulator | 843036b279e4550aa7f030e5d0a49638057f3441 | [
"Apache-2.0"
] | 2 | 2016-12-28T17:10:32.000Z | 2018-03-14T09:30:23.000Z | 33.237179 | 123 | 0.746384 | 1,470 | package es.tid.vntm;
import java.net.Inet4Address;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MaximumBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MaximumReservableBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.UnreservedBandwidth;
import es.tid.rsvp.objects.subobjects.EROSubobject;
import es.tid.rsvp.objects.subobjects.IPv4prefixEROSubobject;
import es.tid.tedb.DomainTEDB;
import es.tid.tedb.IntraDomainEdge;
import es.tid.tedb.MultiLayerTEDB;
import es.tid.tedb.TE_Information;
public class LigthPathCreateIP {
private DomainTEDB ted;
/**
* Variable usada para bloquear la lectura y escritura en la TEDB
*/
private ReentrantLock graphlock;
private int NumLigthPaths = 0;
private Logger log;
public LigthPathCreateIP(DomainTEDB tedb){
log = LoggerFactory.getLogger("PCCClient.log");
this.ted=(DomainTEDB)tedb;
graphlock = new ReentrantLock();
}
public boolean createLigthPath (LinkedList<EROSubobject> ERO){
SimpleDirectedWeightedGraph<Object, IntraDomainEdge> graph_IP = null;
try {
graph_IP = ((MultiLayerTEDB)ted).getUpperLayerGraph();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
Inet4Address src = null;
Inet4Address dst = null;
src=((IPv4prefixEROSubobject)ERO.getFirst()).getIpv4address();
dst=((IPv4prefixEROSubobject)ERO.getLast()).getIpv4address();
if (graph_IP == null){
log.warn("Graph IP is Null!");
return false;
}
graphlock.lock();
try{
float bw = 10;
float[] bw_un = new float[8];
bw_un[0] = bw;
IntraDomainEdge new_edge;
TE_Information TE_INFO = new TE_Information();
MaximumBandwidth maximumBandwidth = new MaximumBandwidth();
MaximumReservableBandwidth maximumReservableBandwidth = new MaximumReservableBandwidth();
UnreservedBandwidth unreservedBandwidth = new UnreservedBandwidth();
try{
if (graph_IP.getEdge(src, dst) == null){
new_edge=new IntraDomainEdge();
maximumBandwidth.setMaximumBandwidth(bw);
maximumReservableBandwidth.setMaximumReservableBandwidth(bw);
unreservedBandwidth.setUnreservedBandwidth(bw_un);
TE_INFO.setMaximumBandwidth(maximumBandwidth);
TE_INFO.setMaximumReservableBandwidth(maximumReservableBandwidth);
TE_INFO.setUnreservedBandwidth(unreservedBandwidth);
new_edge.setTE_info(TE_INFO);
graph_IP.addEdge(src, dst, new_edge);
//System.out.print(graph_IP.getEdge(src, dst).getTE_info().getMaximumBandwidth().maximumBandwidth);
}
else {
//System.out.println("El edge ya existe --> "+graph_IP.getEdge(src, dst).toString());
//new_edge = graph_IP.getEdge(src, dst);
float bw_max = bw;
float bw_new = bw;
log.info("Unreserved :"+graph_IP.getEdge(src, dst).getTE_info().getUnreservedBandwidth().getUnreservedBandwidth()[0]);
bw_un[0] = bw_un[0] + graph_IP.getEdge(src, dst).getTE_info().getUnreservedBandwidth().getUnreservedBandwidth()[0];
bw_new = bw_new + graph_IP.getEdge(src, dst).getTE_info().getMaximumBandwidth().maximumBandwidth;
bw_max = bw_max + graph_IP.getEdge(src, dst).getTE_info().getMaximumReservableBandwidth().maximumReservableBandwidth;
maximumBandwidth.setMaximumBandwidth(bw_new);
maximumReservableBandwidth.setMaximumReservableBandwidth(bw_max);
unreservedBandwidth.setUnreservedBandwidth(bw_un);
graph_IP.getEdge(src, dst).getTE_info().setMaximumBandwidth(maximumBandwidth);
graph_IP.getEdge(src, dst).getTE_info().setMaximumReservableBandwidth(maximumReservableBandwidth);
graph_IP.getEdge(src, dst).getTE_info().setUnreservedBandwidth(unreservedBandwidth);
}
((MultiLayerTEDB)ted).setUpperLayerGraph(graph_IP);
}catch (Exception e){
e.printStackTrace();
System.exit(0);
}
}finally{
graphlock.unlock();
}
return true;
}
public boolean deleteLigthPath (Inet4Address source, Inet4Address destination){
//borrar el ligthPath creado pasando el origen y el destino
SimpleDirectedWeightedGraph<Object,IntraDomainEdge> graph_IP;
IntraDomainEdge edge=new IntraDomainEdge();
graph_IP = ((MultiLayerTEDB)ted).getDuplicatedUpperLayerkGraph();
graph_IP.removeEdge(source, destination);
((MultiLayerTEDB)ted).setUpperLayerGraph(graph_IP);
return true;
}
public boolean reserveLigthPath (Inet4Address source, Inet4Address destination, float bw){
//Reservar Bandwidth en el Ligth Path
SimpleDirectedWeightedGraph<Object,IntraDomainEdge> graph_IP;
graph_IP = ((MultiLayerTEDB)ted).getDuplicatedUpperLayerkGraph();
IntraDomainEdge edge = new IntraDomainEdge();
edge = graph_IP.getEdge(source, destination);
float bandwidth = edge.getTE_info().getUnreservedBandwidth().getUnreservedBandwidth()[0];
TE_Information tE_info = null;
UnreservedBandwidth unreservedBandwidth = null;
tE_info.setUnreservedBandwidth(unreservedBandwidth);
if (bw <= bandwidth){
edge.setTE_info(tE_info);
}
return true;
}
}
|
3e039027855a0bc56e8e010522d6b1a7fd9caf81 | 1,198 | java | Java | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/VoidResponse.java | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/VoidResponse.java | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/VoidResponse.java | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | 31.526316 | 75 | 0.741235 | 1,471 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.hadoop.nfs.nfs3.response;
import org.apache.hadoop.oncrpc.RpcAcceptedReply;
import org.apache.hadoop.oncrpc.XDR;
/**
* A void NFSv3 response
*/
public class VoidResponse extends NFS3Response {
public VoidResponse(int status) {
super(status);
}
@Override
public XDR send(XDR out, int xid) {
RpcAcceptedReply.voidReply(out, xid);
return out;
}
}
|
3e0390c38b4126e678c01601069c9021cf626f74 | 681 | java | Java | p6e-germ-oauth2-2/src/main/java/com/p6e/germ/oauth2/model/base/P6eResultDto2.java | lidashuang1996/p6e_germ_java | 16f3c00dff62b3750559ba9d81de68f12b289ca3 | [
"MIT"
] | 2 | 2020-04-21T14:58:07.000Z | 2020-05-15T02:56:36.000Z | p6e-germ-oauth2-2/src/main/java/com/p6e/germ/oauth2/model/base/P6eResultDto2.java | lidashuang1996/p6e_germ_java | 16f3c00dff62b3750559ba9d81de68f12b289ca3 | [
"MIT"
] | null | null | null | p6e-germ-oauth2-2/src/main/java/com/p6e/germ/oauth2/model/base/P6eResultDto2.java | lidashuang1996/p6e_germ_java | 16f3c00dff62b3750559ba9d81de68f12b289ca3 | [
"MIT"
] | null | null | null | 18.916667 | 55 | 0.615272 | 1,472 | package com.p6e.germ.oauth2.model.base;
import com.p6e.germ.oauth2.model.P6eResultModel;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author lidashuang
* @version 1.0
*/
@Data
public class P6eResultDto2<T> implements Serializable {
/** 错误的描述 */
private P6eResultModel.Error error;
/** 多条查询的数据内容 */
private List<T> list;
/** 总数 */
private Long total;
/** 页码 */
private Integer page;
/** 长度 */
private Integer size;
/**
* 初始化 页码/ 长度 数据
* @param db DB 数据对象
*/
public void initPaging(P6eBaseDb db) {
this.setPage(db.getPage());
this.setSize(db.getSize());
}
}
|
3e0391a20594a691b50bf23db515215d842bbe9c | 2,746 | java | Java | mica-mqtt-codec/src/main/java/net/dreamlu/iot/mqtt/codec/MqttConnectReasonCode.java | lets-mica/mica-mq | 0070cc38ced9e4ef2ab95c7e015bafc1e49c748e | [
"Apache-2.0"
] | 81 | 2020-09-14T02:42:11.000Z | 2022-03-30T14:51:47.000Z | mica-mqtt-codec/src/main/java/net/dreamlu/iot/mqtt/codec/MqttConnectReasonCode.java | lets-mica/mica-mq | 0070cc38ced9e4ef2ab95c7e015bafc1e49c748e | [
"Apache-2.0"
] | null | null | null | mica-mqtt-codec/src/main/java/net/dreamlu/iot/mqtt/codec/MqttConnectReasonCode.java | lets-mica/mica-mq | 0070cc38ced9e4ef2ab95c7e015bafc1e49c748e | [
"Apache-2.0"
] | 14 | 2020-09-17T02:35:24.000Z | 2022-03-28T08:56:18.000Z | 34.325 | 86 | 0.795339 | 1,473 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package net.dreamlu.iot.mqtt.codec;
/**
* Return Code of {@link MqttConnAckMessage}
*
* @author netty
*/
public enum MqttConnectReasonCode implements MqttReasonCode {
/**
* ReturnCode
*/
CONNECTION_ACCEPTED((byte) 0x00),
//MQTT 3 codes
CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION((byte) 0X01),
CONNECTION_REFUSED_IDENTIFIER_REJECTED((byte) 0x02),
CONNECTION_REFUSED_SERVER_UNAVAILABLE((byte) 0x03),
CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD((byte) 0x04),
CONNECTION_REFUSED_NOT_AUTHORIZED((byte) 0x05),
//MQTT 5 codes
CONNECTION_REFUSED_UNSPECIFIED_ERROR((byte) 0x80),
CONNECTION_REFUSED_MALFORMED_PACKET((byte) 0x81),
CONNECTION_REFUSED_PROTOCOL_ERROR((byte) 0x82),
CONNECTION_REFUSED_IMPLEMENTATION_SPECIFIC((byte) 0x83),
CONNECTION_REFUSED_UNSUPPORTED_PROTOCOL_VERSION((byte) 0x84),
CONNECTION_REFUSED_CLIENT_IDENTIFIER_NOT_VALID((byte) 0x85),
CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD((byte) 0x86),
CONNECTION_REFUSED_NOT_AUTHORIZED_5((byte) 0x87),
CONNECTION_REFUSED_SERVER_UNAVAILABLE_5((byte) 0x88),
CONNECTION_REFUSED_SERVER_BUSY((byte) 0x89),
CONNECTION_REFUSED_BANNED((byte) 0x8A),
CONNECTION_REFUSED_BAD_AUTHENTICATION_METHOD((byte) 0x8C),
CONNECTION_REFUSED_TOPIC_NAME_INVALID((byte) 0x90),
CONNECTION_REFUSED_PACKET_TOO_LARGE((byte) 0x95),
CONNECTION_REFUSED_QUOTA_EXCEEDED((byte) 0x97),
CONNECTION_REFUSED_PAYLOAD_FORMAT_INVALID((byte) 0x99),
CONNECTION_REFUSED_RETAIN_NOT_SUPPORTED((byte) 0x9A),
CONNECTION_REFUSED_QOS_NOT_SUPPORTED((byte) 0x9B),
CONNECTION_REFUSED_USE_ANOTHER_SERVER((byte) 0x9C),
CONNECTION_REFUSED_SERVER_MOVED((byte) 0x9D),
CONNECTION_REFUSED_CONNECTION_RATE_EXCEEDED((byte) 0x9F);
private static final MqttConnectReasonCode[] VALUES = new MqttConnectReasonCode[160];
static {
ReasonCodeUtils.fillValuesByCode(VALUES, values());
}
private final byte byteValue;
MqttConnectReasonCode(byte byteValue) {
this.byteValue = byteValue;
}
public static MqttConnectReasonCode valueOf(byte b) {
return ReasonCodeUtils.codeLoopUp(VALUES, b, "Connect");
}
@Override
public byte value() {
return byteValue;
}
}
|
3e0391c7ae0e86c51892f62266d6f330591da498 | 4,267 | java | Java | algorithms/src/main/java/com/github/kuangcp/strcuture/stackapp/OutOfTheMaze.java | Kuangcp/JavaBase | 398b05ce0269b20d8ed3854e737ee8e54d74ead2 | [
"MIT"
] | 16 | 2017-07-11T14:11:48.000Z | 2021-03-31T08:50:55.000Z | algorithms/src/main/java/com/github/kuangcp/strcuture/stackapp/OutOfTheMaze.java | Kuangcp/JavaBase | 398b05ce0269b20d8ed3854e737ee8e54d74ead2 | [
"MIT"
] | 1 | 2017-07-03T06:50:53.000Z | 2019-03-06T18:05:18.000Z | algorithms/src/main/java/com/github/kuangcp/strcuture/stackapp/OutOfTheMaze.java | Kuangcp/JavaBase | 398b05ce0269b20d8ed3854e737ee8e54d74ead2 | [
"MIT"
] | 13 | 2018-01-10T05:03:50.000Z | 2020-11-24T09:58:27.000Z | 26.503106 | 74 | 0.461917 | 1,474 | package com.github.kuangcp.strcuture.stackapp;
import lombok.extern.slf4j.Slf4j;
/**
* Created by https://github.com/kuangcp on 17-8-22 下午3:11
* 迷宫,找出路径和最短路路径
* 想要实现和c一样用define定义常量(不是用final定义方法内部常量)的功能就要用接口
* 在接口中定义一个常量,再继承这个接口,就能在类中到处用这个常量了
* path的路径没有变过,哪了出错了?、、、
*/
@Slf4j
public class OutOfTheMaze {
private static int top = -1, count = 0, minSize = 100;
//定义一个普通整型的地图,两个栈
//int [][] map = new int [M+2][N+2]; 不需要指明大小
private static int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 1},
{1, 0, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 1, 0, 1, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
//只是说放的是point类型的引用,而不是放对象
private static Point[] stack = new Point[100];
private static Point[] path = new Point[100];
static class Point {
int row = 1;//行
int col = 1;//列
int choose = -1;//记录岔路口选择状态
}
public static void main(String[] args) {
for (int k = 0; k < minSize; k++) {
stack[k] = new Point();
path[k] = new Point();
}
int found, choose, i, j;
boolean success = false;
int maxRow = 6;
int maxCol = 6;
char[][] print = new char[maxRow + 2][maxCol + 2];
for (int z = 0; z < maxRow + 2; z++) {
for (int x = 0; x < maxCol + 2; x++) {
print[z][x] = (char) map[z][x];
}
}
// log.info("{}", stack[6].row);
top++;
stack[top].row = 1;
stack[top].col = 1; //起始位置是(1,1)
stack[top].choose = 0;
map[1][1] = -1;
while (top > -1) { //栈不为空就循环
i = stack[top].row;
j = stack[top].col;
choose = stack[top].choose;
if (i == maxRow && j == maxCol) { //走到了终点
success = true;
log.info("the {} way:", ++count);
for (int k = 0; k <= top; k++) {
System.out.printf("(%d,%d) ", stack[k].row, stack[k].col);
}
System.out.println("\n");
if (top + 1 < minSize) { //比较 找到最短路径放入path中
System.arraycopy(stack, 0, path, 0, top + 1);
minSize = top + 1;
}
map[stack[top].row][stack[top].col] = 0; // 把破坏的那个终点恢复
top--;
i = stack[top].row;
j = stack[top].col;
choose = stack[top].choose;
}
found = 0;
while (choose < 4 && found == 0) { //开始选择路径
switch (choose++) {
case 0:
i = stack[top].row - 1;
j = stack[top].col;
break; // 上
case 1:
i = stack[top].row;
j = stack[top].col + 1;
break; // 右
case 2:
i = stack[top].row + 1;
j = stack[top].col;
break; // 下
case 3:
i = stack[top].row;
j = stack[top].col - 1;
break; // 左
}
if (map[i][j] == 0) {
found = 1;
}
}
//System.out.println("top="+top);
if (found == 1) {
stack[top].choose = choose;
top++;
stack[top].row = i;
stack[top].col = j;
stack[top].choose = 0;
map[i][j] = -1; //破坏该位置
} else { //没找到
map[stack[top].row][stack[top].col] = 0;
//恢复当前位置,在while和方向choose变量的作用下就能一步步按原路返回
top--;
}
}
if (success) {
showResult(maxRow, maxCol, print);
} else {
log.warn("这个迷宫无解");
}
}
private static void showResult(int maxRow, int maxCol, char[][] print) {
System.out.printf("最短路径的长度 %d\n\n", minSize);
System.out.print("最短的路径:");
for (int k = 0; k < minSize; k++) {
System.out.printf("(%d,%d) ", path[k].row, path[k].col);
print[path[k].row][path[k].col] = '.';
if ((k + 1) % 8 == 0) {
System.out.println();
}
}
System.out.print("\n迷宫地图:\n");
for (int z = 0; z < maxRow + 2; z++) {
for (int x = 0; x < maxCol + 2; x++) {
System.out.printf(" %c", map[z][x]);
}
System.out.println();
}
System.out.println();
System.out.print("\n最短路径如图:\n");
for (int z = 0; z < maxRow + 2; z++) {
for (int x = 0; x < maxCol + 2; x++) {
System.out.printf(" %c", print[z][x]);
}
System.out.println();
}
}
}
|
3e0391e75d556419e852038f7d442b5114434177 | 1,249 | java | Java | src/main/java/br/com/swconsultoria/efd/contribuicoes/bo/blocoC/GerarRegistroC181.java | Samuel-Oliveira/Java-Efd-Contribuicoes | 67c5b7b41c1dbd7d31f83ac7d9f90d18ae299dad | [
"MIT"
] | 7 | 2017-06-28T11:59:22.000Z | 2022-01-07T14:02:31.000Z | src/main/java/br/com/swconsultoria/efd/contribuicoes/bo/blocoC/GerarRegistroC181.java | Samuel-Oliveira/Java-Efd-Contribuicoes | 67c5b7b41c1dbd7d31f83ac7d9f90d18ae299dad | [
"MIT"
] | 1 | 2021-01-05T21:12:37.000Z | 2021-01-05T21:12:37.000Z | src/main/java/br/com/swconsultoria/efd/contribuicoes/bo/blocoC/GerarRegistroC181.java | Samuel-Oliveira/Java-Efd-Contribuicoes | 67c5b7b41c1dbd7d31f83ac7d9f90d18ae299dad | [
"MIT"
] | 5 | 2018-04-18T23:45:16.000Z | 2022-03-02T16:51:52.000Z | 37.848485 | 86 | 0.746998 | 1,475 | /**
*
*/
package br.com.swconsultoria.efd.contribuicoes.bo.blocoC;
import br.com.swconsultoria.efd.contribuicoes.registros.blocoC.RegistroC181;
import br.com.swconsultoria.efd.contribuicoes.util.Util;
/**
* @author Yuri Lemes
*
*/
public class GerarRegistroC181 {
public static StringBuilder gerar(RegistroC181 registroC181, StringBuilder sb) {
sb.append("|").append(Util.preencheRegistro(registroC181.getReg()));
sb.append("|").append(Util.preencheRegistro(registroC181.getCst_pis()));
sb.append("|").append(Util.preencheRegistro(registroC181.getCfop()));
sb.append("|").append(Util.preencheRegistro(registroC181.getVl_item()));
sb.append("|").append(Util.preencheRegistro(registroC181.getVl_desc()));
sb.append("|").append(Util.preencheRegistro(registroC181.getVl_bc_pis()));
sb.append("|").append(Util.preencheRegistro(registroC181.getAliq_pis_percentual()));
sb.append("|").append(Util.preencheRegistro(registroC181.getQuant_bc_pis()));
sb.append("|").append(Util.preencheRegistro(registroC181.getAliq_pis_reais()));
sb.append("|").append(Util.preencheRegistro(registroC181.getVl_pis()));
sb.append("|").append(Util.preencheRegistro(registroC181.getCod_cta()));
sb.append("|").append('\n');
return sb;
}
}
|
3e03926e2ecbb12383ce017e51da14df9511c617 | 2,608 | java | Java | src/main/java/umm3601/user/TodoDatabase.java | UMM-CSci-3601-S19/lab-2-joe-and-leah | af088fb1464d22ccf34ca4cdef28a24d1e0bcbe3 | [
"MIT"
] | null | null | null | src/main/java/umm3601/user/TodoDatabase.java | UMM-CSci-3601-S19/lab-2-joe-and-leah | af088fb1464d22ccf34ca4cdef28a24d1e0bcbe3 | [
"MIT"
] | 21 | 2019-02-14T19:29:57.000Z | 2019-02-14T20:17:35.000Z | src/main/java/umm3601/user/TodoDatabase.java | UMM-CSci-3601-S19/lab-2-joe-and-leah | af088fb1464d22ccf34ca4cdef28a24d1e0bcbe3 | [
"MIT"
] | null | null | null | 32.6 | 92 | 0.663344 | 1,476 | package umm3601.user;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.lang.String;
import java.util.Map;
import java.util.Objects;
public class TodoDatabase {
private Todo[] allTodos;
public TodoDatabase(String todoDataFile) throws IOException {
Gson gson = new Gson();
FileReader reader = new FileReader(todoDataFile);
allTodos = gson.fromJson(reader, Todo[].class);
}
public Todo[] listTodos(){
return allTodos;
}
public Todo[] listTodos(Map<String, String[]> queryParams) {
Todo[] filteredTodos = allTodos;
// Filter age if defined
if (queryParams.containsKey("status")) {
boolean compstat = (Objects.equals(queryParams.get("status")[0], "complete"));
filteredTodos = filterStatusTodo(filteredTodos, compstat);
}
// Process other query parameters here...
if (queryParams.containsKey("body")) {
String word = (queryParams.get("body")[0]);
filteredTodos = filterBodyTodo(filteredTodos, word);
}
if (queryParams.containsKey("_id")) {
String word = (queryParams.get("_id")[0]);
filteredTodos = filterIDTodo(filteredTodos, word);
}
if (queryParams.containsKey("owner")) {
String word = (queryParams.get("owner")[0]);
filteredTodos = filterOwnerTodo(filteredTodos, word);
}
if (queryParams.containsKey("category")) {
String word = (queryParams.get("category")[0]);
filteredTodos = filterCategoryTodo(filteredTodos, word);
}
if (queryParams.containsKey("limit")) {
int limit = Integer.parseInt(queryParams.get("limit")[0]);
filteredTodos = Arrays.copyOfRange(filteredTodos,0,limit);
}
return filteredTodos;
}
public Todo[] filterStatusTodo(Todo[] todos, boolean compstatus) {
return Arrays.stream(todos).filter(x -> x.status == compstatus).toArray(Todo[]::new);
}
public Todo[] filterBodyTodo(Todo[] todos, String word) {
return Arrays.stream(todos).filter(x -> x.body.contains(word)).toArray(Todo[]::new);
}
public Todo[] filterIDTodo(Todo[] todos, String word) {
return Arrays.stream(todos).filter(x -> x._id.contains(word)).toArray(Todo[]::new);
}
public Todo[] filterOwnerTodo(Todo[] todos, String word) {
return Arrays.stream(todos).filter(x -> x.owner.contains(word)).toArray(Todo[]::new);
}
public Todo[] filterCategoryTodo(Todo[] todos, String word) {
return Arrays.stream(todos).filter(x -> x.category.contains(word)).toArray(Todo[]::new);
}
}
|
3e03929902cb6c81d8d0dab7cfe7add6774b6edf | 395 | java | Java | eshow-api/src/main/java/cn/org/eshow/webapp/action/PhotoCommentAction.java | bangqu/EShow | d7780ac747a0da1916e5c75d8abd1e38217a7b50 | [
"Apache-2.0"
] | 14 | 2016-04-20T05:47:47.000Z | 2018-10-08T00:31:59.000Z | eshow-api/src/main/java/cn/org/eshow/webapp/action/PhotoCommentAction.java | bangqu/EShow | d7780ac747a0da1916e5c75d8abd1e38217a7b50 | [
"Apache-2.0"
] | null | null | null | eshow-api/src/main/java/cn/org/eshow/webapp/action/PhotoCommentAction.java | bangqu/EShow | d7780ac747a0da1916e5c75d8abd1e38217a7b50 | [
"Apache-2.0"
] | 19 | 2016-03-18T02:16:02.000Z | 2019-09-04T10:31:23.000Z | 26.333333 | 104 | 0.741772 | 1,477 | package cn.org.eshow.webapp.action;
import cn.org.eshow.model.PhotoComment;
import org.apache.struts2.convention.annotation.AllowedMethods;
/**
* 照片评论API接口
*/
@AllowedMethods({"check", "login", "singup", "third", "mobile", "password", "update", "cancel", "view"})
public class PhotoCommentAction extends ApiBaseAction<PhotoComment> {
private static final long serialVersionUID = 1L;
} |
3e039464445767d690c491bc3a2f704ea7c6bf21 | 385 | java | Java | Exercicio/app/src/main/java/com/example/exercicio/view/CadastroPessoa.java | dequim1000/Agenda_Android_Native | f47f65556a672ba0b419c0270e0fc2e1f75750b7 | [
"MIT"
] | null | null | null | Exercicio/app/src/main/java/com/example/exercicio/view/CadastroPessoa.java | dequim1000/Agenda_Android_Native | f47f65556a672ba0b419c0270e0fc2e1f75750b7 | [
"MIT"
] | null | null | null | Exercicio/app/src/main/java/com/example/exercicio/view/CadastroPessoa.java | dequim1000/Agenda_Android_Native | f47f65556a672ba0b419c0270e0fc2e1f75750b7 | [
"MIT"
] | null | null | null | 24.0625 | 58 | 0.774026 | 1,478 | package com.example.exercicio.view;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.exercicio.R;
public class CadastroPessoa extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_pessoa);
}
} |
3e039539bcfb0de8971b49b3a2b1196c36805dff | 648 | java | Java | src/test/java/examples/nft/DepositHistory.java | andrea-amadei/binance-connector-java | f6c1752e9776b34296af4ad95ddac1dfa41c1772 | [
"MIT"
] | 45 | 2021-12-10T01:42:27.000Z | 2022-03-29T08:49:51.000Z | src/test/java/examples/nft/DepositHistory.java | tochki/binance-connector-java | 9e923b10ad9bcbf8a2435cd2eaad6575ef0a8972 | [
"MIT"
] | 15 | 2021-12-28T19:06:47.000Z | 2022-03-30T12:59:49.000Z | src/test/java/examples/nft/DepositHistory.java | tochki/binance-connector-java | 9e923b10ad9bcbf8a2435cd2eaad6575ef0a8972 | [
"MIT"
] | 24 | 2021-12-10T16:55:41.000Z | 2022-03-29T08:49:55.000Z | 32.4 | 100 | 0.759259 | 1,479 | package examples.nft;
import com.binance.connector.client.impl.SpotClientImpl;
import examples.PrivateConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
public class DepositHistory {
private static final Logger logger = LoggerFactory.getLogger(DepositHistory.class);
public static void main(String[] args) {
LinkedHashMap<String,Object> parameters = new LinkedHashMap<>();
SpotClientImpl client = new SpotClientImpl(PrivateConfig.API_KEY, PrivateConfig.SECRET_KEY);
String result = client.createNFT().depositHistory(parameters);
logger.info(result);
}
}
|
3e0395c85ab56be06d6636a9566ad66510bd9ccb | 8,014 | java | Java | src/main/java/com/assignment/service/impl/UserServiceImpl.java | ZihaoTao/assignment | 446d831a0909e3e6d5aed5f25cf7704563d10a9c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/assignment/service/impl/UserServiceImpl.java | ZihaoTao/assignment | 446d831a0909e3e6d5aed5f25cf7704563d10a9c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/assignment/service/impl/UserServiceImpl.java | ZihaoTao/assignment | 446d831a0909e3e6d5aed5f25cf7704563d10a9c | [
"Apache-2.0"
] | null | null | null | 40.271357 | 109 | 0.677065 | 1,480 | package com.assignment.service.impl;
import com.assignment.common.Const;
import com.assignment.common.ServerResponse;
import com.assignment.common.TokenCache;
import com.assignment.dao.UserMapper;
import com.assignment.pojo.User;
import com.assignment.service.IUserService;
import com.assignment.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
/**
* Created by geely
*/
@Service("iUserService")
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public ServerResponse<User> login(String username, String password) {
int resultCount = userMapper.checkUsername(username);
if(resultCount == 0 ){
return ServerResponse.createByErrorMessage("Username does not exist");
}
String md5Password = MD5Util.MD5EncodeUtf8(password);
User user = userMapper.selectLogin(username,md5Password);
if(user == null){
return ServerResponse.createByErrorMessage("Incorrect password");
}
user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
return ServerResponse.createBySuccess("Login successful",user);
}
@Override
public ServerResponse<String> register(User user){
ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
if(!validResponse.isSuccess()){
return validResponse;
}
validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
if(!validResponse.isSuccess()){
return validResponse;
}
user.setRole(Const.Role.ROLE_CUSTOMER);
//MD5
user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
int resultCount = userMapper.insert(user);
if(resultCount == 0){
return ServerResponse.createByErrorMessage("Registration failed");
}
return ServerResponse.createBySuccessMessage("Registration successful");
}
@Override
public ServerResponse<String> checkValid(String str,String type){
if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){
if(Const.USERNAME.equals(type)){
int resultCount = userMapper.checkUsername(str);
if(resultCount > 0 ){
return ServerResponse.createByErrorMessage("Username exists");
}
}
if(Const.EMAIL.equals(type)){
int resultCount = userMapper.checkEmail(str);
if(resultCount > 0 ){
return ServerResponse.createByErrorMessage("Email exists");
}
}
}else{
return ServerResponse.createByErrorMessage("Incorrect index");
}
return ServerResponse.createBySuccessMessage("Successfully verified");
}
@Override
public ServerResponse selectQuestion(String username){
ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
if(validResponse.isSuccess()){
//User does not exist
return ServerResponse.createByErrorMessage("User does not exist");
}
String question = userMapper.selectQuestionByUsername(username);
if(org.apache.commons.lang3.StringUtils.isNotBlank(question)){
return ServerResponse.createBySuccess(question);
}
return ServerResponse.createByErrorMessage("Question is blank");
}
@Override
public ServerResponse<String> checkAnswer(String username,String question,String answer){
int resultCount = userMapper.checkAnswer(username,question,answer);
if(resultCount>0){
//说明问题及问题答案是这个用户的,并且是正确的
String forgetToken = UUID.randomUUID().toString();
TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
return ServerResponse.createBySuccess(forgetToken);
}
return ServerResponse.createByErrorMessage("Answer is incorrect");
}
@Override
public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
if(org.apache.commons.lang3.StringUtils.isBlank(forgetToken)){
return ServerResponse.createByErrorMessage("Wrong index,need token");
}
ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
if(validResponse.isSuccess()){
//用户不存在
return ServerResponse.createByErrorMessage("User does not exists");
}
String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
if(org.apache.commons.lang3.StringUtils.isBlank(token)){
return ServerResponse.createByErrorMessage("Invalid or expired token");
}
if(org.apache.commons.lang3.StringUtils.equals(forgetToken,token)){
String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
if(rowCount > 0){
return ServerResponse.createBySuccessMessage("Password has been changed successfully");
}
}else{
return ServerResponse.createByErrorMessage("Wrong token, please get a new token");
}
return ServerResponse.createByErrorMessage("Password reset failed");
}
@Override
public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
//防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
if(resultCount == 0){
return ServerResponse.createByErrorMessage("Incorrect old password");
}
if(org.apache.commons.lang3.StringUtils.equals(passwordNew, passwordOld)) {
return ServerResponse.createByErrorMessage("New password cannot be your old password");
}
user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if(updateCount > 0){
return ServerResponse.createBySuccessMessage("Password has been changed successfully");
}
return ServerResponse.createByErrorMessage("Password reset failed");
}
@Override
public ServerResponse<User> updateInformation(User user){
//username cannot be updated
//need to validate email to make sure it is not used
int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
if(resultCount > 0){
return ServerResponse.createByErrorMessage("email exists, please change the email");
}
User updateUser = new User();
updateUser.setId(user.getId());
updateUser.setEmail(user.getEmail());
updateUser.setPhone(user.getPhone());
updateUser.setQuestion(user.getQuestion());
updateUser.setAnswer(user.getAnswer());
int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
if(updateCount > 0){
return ServerResponse.createBySuccess("Information has been updated successfully",updateUser);
}
return ServerResponse.createByErrorMessage("Information reset failed");
}
@Override
public ServerResponse<User> getInformation(Integer userId){
User user = userMapper.selectByPrimaryKey(userId);
if(user == null){
return ServerResponse.createByErrorMessage("Cannot find the user");
}
user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
return ServerResponse.createBySuccess(user);
}
@Override
public ServerResponse checkAdminRole(User user){
if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
return ServerResponse.createBySuccess();
}
return ServerResponse.createByError();
}
}
|
3e039781dedf03906d8be7dfbfce71ce34f5e5ec | 1,444 | java | Java | src/main/java/org/graylog/plugins/cef/CEFInputMetaData.java | Gandalf098/graylog-plugin-cef | 011559a94a1c3d6714ec5ee48ac6e3dbdf070fa5 | [
"Apache-2.0"
] | 9 | 2016-09-29T17:54:47.000Z | 2020-07-13T14:46:48.000Z | src/main/java/org/graylog/plugins/cef/CEFInputMetaData.java | Gandalf098/graylog-plugin-cef | 011559a94a1c3d6714ec5ee48ac6e3dbdf070fa5 | [
"Apache-2.0"
] | 26 | 2016-08-21T09:16:01.000Z | 2021-12-02T09:45:00.000Z | src/main/java/org/graylog/plugins/cef/CEFInputMetaData.java | isabella232/graylog-plugin-cef | 011559a94a1c3d6714ec5ee48ac6e3dbdf070fa5 | [
"Apache-2.0"
] | 8 | 2016-09-27T11:01:25.000Z | 2021-08-15T13:54:54.000Z | 26.740741 | 126 | 0.694598 | 1,481 | package org.graylog.plugins.cef;
import org.graylog2.plugin.PluginMetaData;
import org.graylog2.plugin.ServerStatus;
import org.graylog2.plugin.Version;
import java.net.URI;
import java.util.Collections;
import java.util.Set;
public class CEFInputMetaData implements PluginMetaData {
private static final String PLUGIN_PROPERTIES = "org.graylog.plugins.graylog-plugin-cef/graylog-plugin.properties";
@Override
public String getUniqueId() {
return "org.graylog.plugins.cef.CEFInputPlugin";
}
@Override
public String getName() {
return "CEF Input";
}
@Override
public String getAuthor() {
return "Graylog, Inc.";
}
@Override
public URI getURL() {
return URI.create("https://github.com/Graylog2/graylog-plugin-cef");
}
@Override
public Version getVersion() {
return Version.fromPluginProperties(this.getClass(), PLUGIN_PROPERTIES, "version", Version.from(0, 0, 0, "unknown"));
}
@Override
public String getDescription() {
return "Input plugin to receive CEF (Common Event Format) messages.";
}
@Override
public Version getRequiredVersion() {
return Version.fromPluginProperties(this.getClass(), PLUGIN_PROPERTIES, "graylog.version", Version.CURRENT_CLASSPATH);
}
@Override
public Set<ServerStatus.Capability> getRequiredCapabilities() {
return Collections.emptySet();
}
}
|
3e039878e322ba9d229590f3de834b57e3b5cdab | 363 | java | Java | src/main/java/dev/tensor/backend/events/KeyPressedEvent.java | IUDevman/Tensor | 714cb9ef855b05310ce1d4eeb9e7c2c294bfaa9e | [
"MIT"
] | 13 | 2021-11-21T08:55:36.000Z | 2022-03-29T11:19:07.000Z | src/main/java/dev/tensor/backend/events/KeyPressedEvent.java | IUDevman/Tensor | 714cb9ef855b05310ce1d4eeb9e7c2c294bfaa9e | [
"MIT"
] | 4 | 2021-12-08T03:13:26.000Z | 2022-03-09T18:14:48.000Z | src/main/java/dev/tensor/backend/events/KeyPressedEvent.java | IUDevman/Tensor | 714cb9ef855b05310ce1d4eeb9e7c2c294bfaa9e | [
"MIT"
] | 5 | 2021-11-09T23:41:55.000Z | 2022-03-31T04:36:52.000Z | 16.5 | 61 | 0.666667 | 1,482 | package dev.tensor.backend.events;
import dev.tensor.misc.event.imp.EventCancellable;
/**
* @author IUDevman
* @since 04-13-2021
*/
public final class KeyPressedEvent extends EventCancellable {
private final int bind;
public KeyPressedEvent(int bind) {
this.bind = bind;
}
public int getBind() {
return this.bind;
}
}
|
3e0398b677f203e1e9a46b83fb24bdfec8303583 | 4,903 | java | Java | cdap-master/src/main/java/io/cdap/cdap/master/startup/FileSystemCheck.java | neelesh-nirmal/cdap | ac80b367554eed063690844a86d2bb427e13663c | [
"Apache-2.0"
] | 369 | 2018-12-11T08:30:05.000Z | 2022-03-30T09:32:53.000Z | cdap-master/src/main/java/io/cdap/cdap/master/startup/FileSystemCheck.java | neelesh-nirmal/cdap | ac80b367554eed063690844a86d2bb427e13663c | [
"Apache-2.0"
] | 8,921 | 2015-01-01T16:40:44.000Z | 2018-11-29T21:58:11.000Z | cdap-master/src/main/java/io/cdap/cdap/master/startup/FileSystemCheck.java | neelesh-nirmal/cdap | ac80b367554eed063690844a86d2bb427e13663c | [
"Apache-2.0"
] | 189 | 2018-11-30T20:11:08.000Z | 2022-03-25T02:55:39.000Z | 40.858333 | 110 | 0.683255 | 1,483 | /*
* Copyright © 2016 Cask Data, 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 io.cdap.cdap.master.startup;
import com.google.inject.Inject;
import io.cdap.cdap.common.conf.CConfiguration;
import io.cdap.cdap.common.conf.Constants;
import io.cdap.cdap.common.io.Locations;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.twill.filesystem.Location;
import org.apache.twill.filesystem.LocationFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Checks that the configured FileSystem is available and the root path has the correct permissions.
*/
// class is picked up through classpath examination
@SuppressWarnings("unused")
public class FileSystemCheck extends AbstractMasterCheck {
private static final Logger LOG = LoggerFactory.getLogger(FileSystemCheck.class);
private final LocationFactory locationFactory;
private final Configuration hConf;
@Inject
private FileSystemCheck(CConfiguration cConf, Configuration hConf, LocationFactory locationFactory) {
super(cConf);
this.hConf = hConf;
this.locationFactory = locationFactory;
}
@Override
public void run() throws IOException {
String user = cConf.get(Constants.CFG_HDFS_USER);
String rootPath = cConf.get(Constants.CFG_HDFS_NAMESPACE);
LOG.info("Checking FileSystem availability.");
Location rootLocation = Locations.getLocationFromAbsolutePath(locationFactory, rootPath);
boolean rootExists;
try {
rootExists = rootLocation.exists();
LOG.info(" FileSystem availability successfully verified.");
if (rootExists) {
if (!rootLocation.isDirectory()) {
throw new RuntimeException(String.format(
"%s is not a directory. Change it to a directory, or update %s to point to a different location.",
rootPath, Constants.CFG_HDFS_NAMESPACE));
}
}
} catch (IOException e) {
throw new RuntimeException(String.format(
"Unable to connect to the FileSystem with %s set to %s. " +
"Please check that the FileSystem is running and that the correct " +
"Hadoop configuration (e.g. core-site.xml, hdfs-site.xml) " +
"and Hadoop libraries are included in the CDAP Master classpath.",
CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY,
hConf.get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY)), e);
}
LOG.info("Checking that user {} has permission to write to {} on the FileSystem.", user, rootPath);
if (rootExists) {
// try creating a tmp file to check permissions
try {
Location tmpFile = rootLocation.append("newTempFile").getTempFile("tmp");
if (!tmpFile.createNew()) {
throw new RuntimeException(String.format(
"Could not make a temp file %s in directory %s on the FileSystem. " +
"Please check that user %s has permission to write to %s, " +
"or create the directory manually with write permissions.",
tmpFile, rootPath, user, rootPath));
} else {
tmpFile.delete();
}
} catch (IOException e) {
throw new RuntimeException(String.format(
"Could not make/delete a temp file in directory %s on the FileSystem. " +
"Please check that user %s has permission to write to %s, " +
"or create the directory manually with write permissions.",
rootPath, user, rootPath), e);
}
} else {
// try creating the directory to check permissions
try {
if (!rootLocation.mkdirs()) {
throw new RuntimeException(String.format(
"Could not make directory %s on the FileSystem. " +
"Please check that user %s has permission to write to %s, " +
"or create the directory manually with write permissions.",
rootPath, user, rootPath));
}
} catch (IOException e) {
throw new RuntimeException(String.format(
"Could not make directory %s on the FileSystem. " +
"Please check that user %s has permission to write to %s, " +
"or create the directory manually with write permissions.",
rootPath, user, rootPath), e);
}
}
LOG.info(" FileSystem permissions successfully verified.");
}
}
|
3e0399bfe3b024faa06f80575be228c9bea32392 | 752 | java | Java | jardemotest/src/main/java/com/snbc/jardemotest/Logs.java | zzggxx/jardemo | ea286f9848eb3e0f952ce844af6b6fd130ce1825 | [
"Apache-2.0"
] | null | null | null | jardemotest/src/main/java/com/snbc/jardemotest/Logs.java | zzggxx/jardemo | ea286f9848eb3e0f952ce844af6b6fd130ce1825 | [
"Apache-2.0"
] | null | null | null | jardemotest/src/main/java/com/snbc/jardemotest/Logs.java | zzggxx/jardemo | ea286f9848eb3e0f952ce844af6b6fd130ce1825 | [
"Apache-2.0"
] | null | null | null | 25.066667 | 120 | 0.658245 | 1,484 | package com.snbc.jardemotest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.InputStream;
/**
* author: zhougaoxiong
* date: 2019/12/11,9:31
* projectName:jardemo
* packageName:com.snbc.jardemotest
*/
public class Logs {
public static void error() {
LogUtli.e();
}
public static Bitmap getAssets(Context context) {
Bitmap bitmap = null;
try {
InputStream resourceAsStream = context.getClass().getClassLoader().getResourceAsStream("assets/" + "d.jpg");
bitmap = BitmapFactory.decodeStream(resourceAsStream);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
} |
3e039ad385a8254bc3749e950b5441b3b5743815 | 745 | java | Java | agent-bridge/src/main/java/com/newrelic/agent/bridge/DistributedTracePayload.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 119 | 2020-08-15T21:38:07.000Z | 2022-03-25T12:07:11.000Z | agent-bridge/src/main/java/com/newrelic/agent/bridge/DistributedTracePayload.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 468 | 2020-08-07T17:56:39.000Z | 2022-03-31T17:33:45.000Z | agent-bridge/src/main/java/com/newrelic/agent/bridge/DistributedTracePayload.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 91 | 2020-08-11T14:23:08.000Z | 2022-03-31T17:28:18.000Z | 26.607143 | 129 | 0.765101 | 1,485 | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.bridge;
import com.newrelic.api.agent.Headers;
import com.newrelic.api.agent.TransportType;
/**
* Payload used to connect two services in a distributed system.
*
* @deprecated Instead, use the Distributed Tracing API {@link Transaction#insertDistributedTraceHeaders(Headers)} to create a
* distributed tracing payload and {@link Transaction#acceptDistributedTraceHeaders(TransportType, Headers)} to link the services
* together.
*/
@Deprecated
public interface DistributedTracePayload extends com.newrelic.api.agent.DistributedTracePayload {
String text();
String httpSafe();
}
|
3e039b30b5da58cb629938edf8af22499fa9273b | 1,048 | java | Java | chapter_002/src/main/java/ru/job4j/tracker/StartUI.java | Antierror/job4j | 0c20a1ed1ff2451b8d1a44511109468be0d9df54 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/job4j/tracker/StartUI.java | Antierror/job4j | 0c20a1ed1ff2451b8d1a44511109468be0d9df54 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/job4j/tracker/StartUI.java | Antierror/job4j | 0c20a1ed1ff2451b8d1a44511109468be0d9df54 | [
"Apache-2.0"
] | null | null | null | 25.02381 | 77 | 0.542341 | 1,486 | package ru.job4j.tracker;
import java.util.ArrayList;
import java.util.List;
/**
* @author Konstantin Kazakov ([email protected]).
* @version $Id$
* @since 0.1
*/
public class StartUI {
private final Input input;
private final Tracker tracker;
public StartUI(Input input, Tracker tracker) {
this.input = input;
this.tracker = tracker;
}
public void init() {
MenuTracker menu = new MenuTracker(this.input, this.tracker);
List<Integer> range = new ArrayList<>();
menu.fillActions();
for (int i = 0; i < menu.getActionsLentgh(); i++) {
range.add(i);
}
do {
menu.show();
menu.select(input.ask("Введите число:", range));
} while (!"y".equals(this.input.ask("Выйти с программы?(y - Yes)")));
}
public static void main(String[] args) {
new StartUI(
new ValidateInput(
new ConsoleInput()
),
new Tracker()
).init();
}
}
|
3e039b356a9b756edd56159d2f7a2aa6902cec57 | 2,842 | java | Java | src/main/java/it/polimi/ingsw/shared/rmi/ServerAPI.java | fabiocody/ProgettoIngSwFLK | 86b5bf95a0326ccfe49ee15b78b5a7f7f3363edf | [
"MIT"
] | null | null | null | src/main/java/it/polimi/ingsw/shared/rmi/ServerAPI.java | fabiocody/ProgettoIngSwFLK | 86b5bf95a0326ccfe49ee15b78b5a7f7f3363edf | [
"MIT"
] | null | null | null | src/main/java/it/polimi/ingsw/shared/rmi/ServerAPI.java | fabiocody/ProgettoIngSwFLK | 86b5bf95a0326ccfe49ee15b78b5a7f7f3363edf | [
"MIT"
] | 1 | 2020-07-03T14:43:26.000Z | 2020-07-03T14:43:26.000Z | 35.525 | 90 | 0.705137 | 1,487 | package it.polimi.ingsw.shared.rmi;
import java.rmi.*;
import java.util.*;
/**
* This is the server interface used for RMI
*/
public interface ServerAPI extends Remote {
/**
* This method is used to connect to the server
*
* @param client the client that wants to connect
* @return the server endpoint used later
* @throws RemoteException thrown when there are connection problems
*/
ServerAPI connect(ClientAPI client) throws RemoteException;
/**
* This method is used to check if the server is still connected
*
* @throws RemoteException thrown when there are connection problems
*/
void probe() throws RemoteException;
/**
* @param nickname the nickname of the player logging in
* @return a random UUID if the user has been added, null if login has failed
* @throws RemoteException thrown when there are connection problems
*/
UUID addPlayer(String nickname) throws RemoteException;
/**
* @param patternIndex the index of the pattern chosen by the player
* @return true if the index is valid and the pattern has been chosen, false otherwise
* @throws RemoteException thrown when there are connection problems
*/
boolean choosePattern(int patternIndex) throws RemoteException;
/**
* @param draftPoolIndex the index of die the in the Draft Pool to be placed
* @param x the column in which to place the die
* @param y the row in which to place the die
* @return the serialized JSON describing the result of the placement
* @throws RemoteException thrown when there are connection problems
*/
String placeDie (int draftPoolIndex, int x, int y) throws RemoteException;
/**
* This method toggles turn ending
*
* @throws RemoteException thrown when there are connection problems
*/
void nextTurn() throws RemoteException;
/**
* @param cardIndex the index of the Tool Card you need data for
* @return the data required by the specified Tool Card, JSON-serialized
* @throws RemoteException thrown when there are connection problems
*/
String requiredData(int cardIndex) throws RemoteException;
/**
* @param cardIndex the index of the Tool Card you want to use
* @param requiredDataString the JSON-serialized data required to use the Tool Card
* @return the serialized JSON describing the result of the Tool Card usage
* @throws RemoteException thrown when there are connection problems
*/
String useToolCard(int cardIndex, String requiredDataString) throws RemoteException;
/**
* @param cardIndex the index of the Tool Card
* @throws RemoteException thrown when there are connection problems
*/
void cancelToolCardUsage(int cardIndex) throws RemoteException;
}
|
3e039beaf5a8cc887e4fc3008573d62e2fbf8a10 | 1,188 | java | Java | carisa-administration/src/main/java/org/elipcero/carisa/administration/convert/web/WebValueConverter.java | davsuapas/incubator-carisa | d22022c4219f1943e248fcc990adf4891f317f48 | [
"Apache-2.0"
] | null | null | null | carisa-administration/src/main/java/org/elipcero/carisa/administration/convert/web/WebValueConverter.java | davsuapas/incubator-carisa | d22022c4219f1943e248fcc990adf4891f317f48 | [
"Apache-2.0"
] | null | null | null | carisa-administration/src/main/java/org/elipcero/carisa/administration/convert/web/WebValueConverter.java | davsuapas/incubator-carisa | d22022c4219f1943e248fcc990adf4891f317f48 | [
"Apache-2.0"
] | null | null | null | 32.108108 | 79 | 0.739899 | 1,488 | /*
* Copyright 2019-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.elipcero.carisa.administration.convert.web;
import com.fasterxml.jackson.databind.JsonNode;
import org.elipcero.carisa.administration.domain.DynamicObjectInstanceProperty;
/**
* Convert json message to dynamic object instance property
*
* @author David Suárez
*/
public interface WebValueConverter {
/**
* Create dynamic instance object property from value
* @param value the value of the property
* @return the dynamic instance object property
*/
DynamicObjectInstanceProperty<?> create(JsonNode value);
}
|
3e039beb02ceeeb023325be1de93be9a44ebea5e | 1,993 | java | Java | src/main/java/br/com/rprvidros/daos/UsuarioDao.java | gab2691/rprvidros | e713c8d08935ac04ff9edaa07c209133acedb378 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/rprvidros/daos/UsuarioDao.java | gab2691/rprvidros | e713c8d08935ac04ff9edaa07c209133acedb378 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/rprvidros/daos/UsuarioDao.java | gab2691/rprvidros | e713c8d08935ac04ff9edaa07c209133acedb378 | [
"Apache-2.0"
] | null | null | null | 30.661538 | 141 | 0.734571 | 1,489 | package br.com.rprvidros.daos;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import br.com.rprvidros.models.Usuario;
@Repository
public class UsuarioDao implements UserDetailsService {
@PersistenceContext
private EntityManager manager;
@Override
public UserDetails loadUserByUsername(String email) {
List<Usuario> usuarios = manager.createQuery("select u from Usuario u where u.email = :email", Usuario.class)
.setParameter("email", email).getResultList();
if (usuarios.isEmpty()) {
throw new UsernameNotFoundException("O usuário " + email + " não foi encontrado");
}
return usuarios.get(0);
}
public Usuario addUsuario(Usuario usuario) {
manager.persist(usuario);
return usuario;
}
public Usuario alteraUsuario(Integer id,Usuario usuario){
Usuario usuarios = manager.createQuery("select u from Usuario u where u.id = :id", Usuario.class).setParameter("id", id).getSingleResult();
usuarios.setNome(usuario.getNome());
usuarios.setEmail(usuario.getEmail());
String telefone = usuario.getTelefone().replaceAll("[()-]" , "");
usuarios.setTelefone(telefone);
Usuario merge = manager.merge(usuarios);
return merge;
}
public Usuario buscaUsuario(Integer id){
return (Usuario) manager.createQuery("select u from Usuario u where u.id = :id").setParameter("id", id).getSingleResult();
}
public Usuario atualizaSenha(Integer id, String senha){
Usuario usuario = (Usuario) manager.createQuery("select u from Usuario u where u.id = :id").setParameter("id", id).getSingleResult();
usuario.setSenha(senha);
return usuario;
}
} |
3e039e4f4f84c6427183480eeb4fdfa19737493e | 1,491 | java | Java | jraft-rheakv/rheakv-core/src/test/java/com/alipay/sofa/jraft/rhea/storage/zip/ZipStrategyManagerTest.java | endlessc/sofa-jraft | b9ce89859cf78beaaab6928d8eaf29daa99c3a06 | [
"Apache-2.0"
] | 1,127 | 2019-03-04T11:27:04.000Z | 2019-05-12T02:50:26.000Z | jraft-rheakv/rheakv-core/src/test/java/com/alipay/sofa/jraft/rhea/storage/zip/ZipStrategyManagerTest.java | endlessc/sofa-jraft | b9ce89859cf78beaaab6928d8eaf29daa99c3a06 | [
"Apache-2.0"
] | 104 | 2019-03-05T04:48:21.000Z | 2019-05-10T09:15:52.000Z | jraft-rheakv/rheakv-core/src/test/java/com/alipay/sofa/jraft/rhea/storage/zip/ZipStrategyManagerTest.java | endlessc/sofa-jraft | b9ce89859cf78beaaab6928d8eaf29daa99c3a06 | [
"Apache-2.0"
] | 261 | 2019-03-04T11:22:54.000Z | 2019-05-11T08:20:35.000Z | 37.275 | 106 | 0.753186 | 1,490 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.alipay.sofa.jraft.rhea.storage.zip;
import com.alipay.sofa.jraft.rhea.options.RheaKVStoreOptions;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author blake.qiu
*/
public class ZipStrategyManagerTest {
@Test
public void testInit() {
RheaKVStoreOptions opts = new RheaKVStoreOptions();
opts.setUseParallelCompress(true);
ZipStrategyManager.init(opts);
ZipStrategy zipStrategy = ZipStrategyManager.getZipStrategy(ZipStrategyManager.PARALLEL_STRATEGY);
assertNotNull(zipStrategy);
assertTrue(zipStrategy instanceof ParallelZipStrategy);
}
} |
3e039e7373d492c8a0633d3c3cc6bd4d5cc4fa80 | 1,091 | java | Java | src/main/java/com/stevemosley/chance/base/StringChance.java | smozely/Chance | 8f67641c1596e736683ecbf100bfc68712550b47 | [
"MIT"
] | null | null | null | src/main/java/com/stevemosley/chance/base/StringChance.java | smozely/Chance | 8f67641c1596e736683ecbf100bfc68712550b47 | [
"MIT"
] | 1 | 2016-08-29T15:23:17.000Z | 2016-08-29T15:23:17.000Z | src/main/java/com/stevemosley/chance/base/StringChance.java | smozely/Chance | 8f67641c1596e736683ecbf100bfc68712550b47 | [
"MIT"
] | null | null | null | 22.265306 | 69 | 0.638863 | 1,491 | package com.stevemosley.chance.base;
import static com.stevemosley.chance.ChancePools.*;
import com.google.common.primitives.Chars;
import com.stevemosley.chance.ChanceSettings;
/**
* TODO ... this class ...
*/
public class StringChance extends ChanceSupport {
public StringChance(ChanceSettings settings) {
super(settings);
}
public char aChar() {
return aChar(ALPHA_NUMERIC_CHARS);
}
public char aChar(char[] pool) {
return pool[random().nextInt(pool.length)];
}
public String aString(int length, char[] pool) {
char[] resultChars = new char[length];
for (int i = 0; i < resultChars.length; i++) {
resultChars[i] = aChar(pool);
}
return new String(resultChars);
}
public String aString(int length) {
return aString(length, ALPHA_NUMERIC_CHARS);
}
public String aString(char[] pool) {
return aString(randomIntBetween(5, 20), pool);
}
public String aString() {
return aString(randomIntBetween(5, 20), ALPHA_NUMERIC_CHARS);
}
}
|
3e039f3791ca0acaeac8262e68aab31e899f9b4e | 608 | java | Java | src/javase/data/object/clazz/throwable/exception/IllegalArgumentException.java | liuyangspace/java-test | 67a3d18fae1854aff4f38dff40dca75fda204933 | [
"MIT"
] | null | null | null | src/javase/data/object/clazz/throwable/exception/IllegalArgumentException.java | liuyangspace/java-test | 67a3d18fae1854aff4f38dff40dca75fda204933 | [
"MIT"
] | null | null | null | src/javase/data/object/clazz/throwable/exception/IllegalArgumentException.java | liuyangspace/java-test | 67a3d18fae1854aff4f38dff40dca75fda204933 | [
"MIT"
] | null | null | null | 24.32 | 71 | 0.712171 | 1,492 | package javase.data.object.clazz.throwable.exception;
import java.lang.RuntimeException;
/**
* @see java.lang.IllegalArgumentException
*/
public class IllegalArgumentException extends RuntimeException
{
private static final long serialVersionUID = -5365630128856068164L;
public IllegalArgumentException() {
super();
}
public IllegalArgumentException(String s) {
super(s);
}
public IllegalArgumentException(String message, Throwable cause) {
super(message, cause);
}
public IllegalArgumentException(Throwable cause) {
super(cause);
}
}
|
3e03a0ccbc295bab64f5f850f88d78dc0407ef9f | 666 | java | Java | Algoritmalar/src/com/Interview/easy/ChuckNorris.java | ahmetyavuzoruc/SomeAlgorithms | ffb7b0c95739adc9aa4eddeeb13a24ba0c5cdccb | [
"MIT"
] | 1 | 2021-09-17T19:17:02.000Z | 2021-09-17T19:17:02.000Z | Algoritmalar/src/com/Interview/easy/ChuckNorris.java | ahmetyavuzoruc/SomeAlgorithms | ffb7b0c95739adc9aa4eddeeb13a24ba0c5cdccb | [
"MIT"
] | null | null | null | Algoritmalar/src/com/Interview/easy/ChuckNorris.java | ahmetyavuzoruc/SomeAlgorithms | ffb7b0c95739adc9aa4eddeeb13a24ba0c5cdccb | [
"MIT"
] | null | null | null | 24.666667 | 53 | 0.427928 | 1,493 | package com.Interview.easy;
import java.util.Scanner;
public class ChuckNorris {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
char[] MESSAGE = in.nextLine().toCharArray();
boolean pbit = (MESSAGE[0] & 0x40) != 0;
System.out.print(pbit ? "0 " : "00 ");
for (char B : MESSAGE)
{
for (char bm = 0x40; bm != 0; bm >>= 1)
{
boolean bit = (B & bm) != 0;
System.out.print((bit == pbit) ? "0"
: bit ? " 0 0"
: " 00 0");
pbit = bit;
}
}
}
}
|
3e03a0cfc4aa36e6974dc2696345d1d9b0f9ab33 | 3,348 | java | Java | src/main/java/fr/Axeldu18/PterodactylAPI/Methods/DELETEMethods.java | matt11matthew/Pterodactyl-JAVA-API | 474628f8c2f8844c94860adf6ca689775ea875b9 | [
"MIT"
] | 6 | 2020-05-30T23:25:34.000Z | 2021-07-24T02:31:29.000Z | src/main/java/fr/Axeldu18/PterodactylAPI/Methods/DELETEMethods.java | AxelVatan/Pterodactyl-JAVA-API | 474628f8c2f8844c94860adf6ca689775ea875b9 | [
"MIT"
] | 5 | 2017-08-02T20:19:20.000Z | 2017-10-09T22:19:01.000Z | src/main/java/fr/Axeldu18/PterodactylAPI/Methods/DELETEMethods.java | AxelVatan/Pterodactyl-JAVA-API | 474628f8c2f8844c94860adf6ca689775ea875b9 | [
"MIT"
] | 6 | 2017-07-04T17:44:25.000Z | 2019-02-04T04:48:21.000Z | 34.515464 | 140 | 0.736858 | 1,494 | /**
MIT License
Copyright (c) 2017 Axel Vatan, Marc Sollie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package fr.Axeldu18.PterodactylAPI.Methods;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import fr.Axeldu18.PterodactylAPI.PterodactylAPI;
import lombok.AllArgsConstructor;
import lombok.Getter;
public class DELETEMethods {
private PterodactylAPI main;
@Getter
private String lastError = "";
public DELETEMethods(PterodactylAPI main){
this.main = main;
}
public boolean delete(Methods method){
if(method.getURL().contains("{params}")){
main.log(Level.SEVERE, "The method '" + method.toString() + "'contains field {params}, please use 'get' withs params function for this");
return false;
}
return call(main.getMainURL() + method.getURL());
}
public boolean delete(Methods method, String params){
if(!method.getURL().contains("{params}")){
main.log(Level.SEVERE, "The method '" + method.toString() + "' doesn't contains field {params}, please use 'get' function for this");
return false;
}
return call(main.getMainURL() + method.getURL().replace("{params}", params));
}
public boolean delete(Methods method, int id){
return this.delete(method, id + "");
}
private boolean call(String methodURL){
try {
URL url = new URL(methodURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String hmac = main.getPublicKey() + "." + main.hmac(methodURL);
connection.setRequestMethod("DELETE");
connection.setRequestProperty("User-Agent", "Pterodactyl Java-API");
connection.setRequestProperty("Authorization", "Bearer " + hmac.replaceAll("\n", ""));
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
return true;
} else {
this.lastError = main.readResponse(connection.getErrorStream()).toString();
return false;
}
} catch (Exception e) {
main.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
return false;
}
}
@AllArgsConstructor
public enum Methods{
USER("api/admin/users/{params}"), //Returns information about a single user.
SERVER("api/admin/servers/{params}"), //Lists information about a single server.
NODE("api/admin/nodes/{params}"); //View data for a single node.
private @Getter String URL;
}
}
|
3e03a0f651e22e3c607eb6e4bf02c458a1671854 | 15,624 | java | Java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeInstanceCreditSpecificationsRequest.java | stepio/aws-sdk-java | 0370178d6c0c0f40f6d0b8894e77ef8b133fd366 | [
"Apache-2.0"
] | 1 | 2020-04-16T10:06:15.000Z | 2020-04-16T10:06:15.000Z | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeInstanceCreditSpecificationsRequest.java | stepio/aws-sdk-java | 0370178d6c0c0f40f6d0b8894e77ef8b133fd366 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeInstanceCreditSpecificationsRequest.java | stepio/aws-sdk-java | 0370178d6c0c0f40f6d0b8894e77ef8b133fd366 | [
"Apache-2.0"
] | 1 | 2019-07-22T16:24:05.000Z | 2019-07-22T16:24:05.000Z | 32.280992 | 146 | 0.587558 | 1,495 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.DescribeInstanceCreditSpecificationsRequestMarshaller;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeInstanceCreditSpecificationsRequest extends AmazonWebServiceRequest implements Serializable, Cloneable,
DryRunSupportedRequest<DescribeInstanceCreditSpecificationsRequest> {
/**
* <p>
* One or more filters.
* </p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* </ul>
*/
private com.amazonaws.internal.SdkInternalList<Filter> filters;
/**
* <p>
* One or more instance IDs.
* </p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> instanceIds;
/**
* <p>
* The maximum number of results to return in a single call. To retrieve the remaining results, make another call
* with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot specify this
* parameter and the instance IDs parameter in the same call.
* </p>
*/
private Integer maxResults;
/**
* <p>
* The token to retrieve the next page of results.
* </p>
*/
private String nextToken;
/**
* <p>
* One or more filters.
* </p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* </ul>
*
* @return One or more filters.</p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
*/
public java.util.List<Filter> getFilters() {
if (filters == null) {
filters = new com.amazonaws.internal.SdkInternalList<Filter>();
}
return filters;
}
/**
* <p>
* One or more filters.
* </p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* </ul>
*
* @param filters
* One or more filters.</p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
*/
public void setFilters(java.util.Collection<Filter> filters) {
if (filters == null) {
this.filters = null;
return;
}
this.filters = new com.amazonaws.internal.SdkInternalList<Filter>(filters);
}
/**
* <p>
* One or more filters.
* </p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* </ul>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setFilters(java.util.Collection)} or {@link #withFilters(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param filters
* One or more filters.</p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withFilters(Filter... filters) {
if (this.filters == null) {
setFilters(new com.amazonaws.internal.SdkInternalList<Filter>(filters.length));
}
for (Filter ele : filters) {
this.filters.add(ele);
}
return this;
}
/**
* <p>
* One or more filters.
* </p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* </ul>
*
* @param filters
* One or more filters.</p>
* <ul>
* <li>
* <p>
* <code>instance-id</code> - The ID of the instance.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withFilters(java.util.Collection<Filter> filters) {
setFilters(filters);
return this;
}
/**
* <p>
* One or more instance IDs.
* </p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* </p>
*
* @return One or more instance IDs.</p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
*/
public java.util.List<String> getInstanceIds() {
if (instanceIds == null) {
instanceIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return instanceIds;
}
/**
* <p>
* One or more instance IDs.
* </p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* </p>
*
* @param instanceIds
* One or more instance IDs.</p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
*/
public void setInstanceIds(java.util.Collection<String> instanceIds) {
if (instanceIds == null) {
this.instanceIds = null;
return;
}
this.instanceIds = new com.amazonaws.internal.SdkInternalList<String>(instanceIds);
}
/**
* <p>
* One or more instance IDs.
* </p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setInstanceIds(java.util.Collection)} or {@link #withInstanceIds(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param instanceIds
* One or more instance IDs.</p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withInstanceIds(String... instanceIds) {
if (this.instanceIds == null) {
setInstanceIds(new com.amazonaws.internal.SdkInternalList<String>(instanceIds.length));
}
for (String ele : instanceIds) {
this.instanceIds.add(ele);
}
return this;
}
/**
* <p>
* One or more instance IDs.
* </p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* </p>
*
* @param instanceIds
* One or more instance IDs.</p>
* <p>
* Default: Describes all your instances.
* </p>
* <p>
* Constraints: Maximum 1000 explicitly specified instance IDs.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withInstanceIds(java.util.Collection<String> instanceIds) {
setInstanceIds(instanceIds);
return this;
}
/**
* <p>
* The maximum number of results to return in a single call. To retrieve the remaining results, make another call
* with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot specify this
* parameter and the instance IDs parameter in the same call.
* </p>
*
* @param maxResults
* The maximum number of results to return in a single call. To retrieve the remaining results, make another
* call with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot
* specify this parameter and the instance IDs parameter in the same call.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* The maximum number of results to return in a single call. To retrieve the remaining results, make another call
* with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot specify this
* parameter and the instance IDs parameter in the same call.
* </p>
*
* @return The maximum number of results to return in a single call. To retrieve the remaining results, make another
* call with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot
* specify this parameter and the instance IDs parameter in the same call.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* The maximum number of results to return in a single call. To retrieve the remaining results, make another call
* with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot specify this
* parameter and the instance IDs parameter in the same call.
* </p>
*
* @param maxResults
* The maximum number of results to return in a single call. To retrieve the remaining results, make another
* call with the returned <code>NextToken</code> value. This value can be between 5 and 1000. You cannot
* specify this parameter and the instance IDs parameter in the same call.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* <p>
* The token to retrieve the next page of results.
* </p>
*
* @param nextToken
* The token to retrieve the next page of results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token to retrieve the next page of results.
* </p>
*
* @return The token to retrieve the next page of results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token to retrieve the next page of results.
* </p>
*
* @param nextToken
* The token to retrieve the next page of results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeInstanceCreditSpecificationsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* This method is intended for internal use only. Returns the marshaled request configured with additional
* parameters to enable operation dry-run.
*/
@Override
public Request<DescribeInstanceCreditSpecificationsRequest> getDryRunRequest() {
Request<DescribeInstanceCreditSpecificationsRequest> request = new DescribeInstanceCreditSpecificationsRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFilters() != null)
sb.append("Filters: ").append(getFilters()).append(",");
if (getInstanceIds() != null)
sb.append("InstanceIds: ").append(getInstanceIds()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeInstanceCreditSpecificationsRequest == false)
return false;
DescribeInstanceCreditSpecificationsRequest other = (DescribeInstanceCreditSpecificationsRequest) obj;
if (other.getFilters() == null ^ this.getFilters() == null)
return false;
if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false)
return false;
if (other.getInstanceIds() == null ^ this.getInstanceIds() == null)
return false;
if (other.getInstanceIds() != null && other.getInstanceIds().equals(this.getInstanceIds()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode());
hashCode = prime * hashCode + ((getInstanceIds() == null) ? 0 : getInstanceIds().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public DescribeInstanceCreditSpecificationsRequest clone() {
return (DescribeInstanceCreditSpecificationsRequest) super.clone();
}
}
|
3e03a149676477423157c98355a89cd195ef7176 | 774 | java | Java | tools/src/main/java/io/toolisticon/aptk/tools/command/impl/GetAttributesCommandWithInheritance.java | AlexRogalskiy/aptk | 58a538b6ba56c80c3a087ea5df3d19a58827017f | [
"MIT"
] | 16 | 2018-03-26T11:41:02.000Z | 2021-07-07T10:45:56.000Z | tools/src/main/java/io/toolisticon/aptk/tools/command/impl/GetAttributesCommandWithInheritance.java | toolisticon/annotation-processor-toolk | 58a538b6ba56c80c3a087ea5df3d19a58827017f | [
"MIT"
] | 66 | 2018-01-10T13:48:02.000Z | 2021-06-25T15:36:08.000Z | tools/src/main/java/io/toolisticon/aptk/tools/command/impl/GetAttributesCommandWithInheritance.java | AlexRogalskiy/aptk | 58a538b6ba56c80c3a087ea5df3d19a58827017f | [
"MIT"
] | 2 | 2018-10-01T11:09:22.000Z | 2019-05-10T10:56:03.000Z | 33.652174 | 115 | 0.80491 | 1,496 | package io.toolisticon.aptk.tools.command.impl;
import io.toolisticon.aptk.tools.BeanUtils;
import io.toolisticon.aptk.tools.BeanUtils.AttributeResult;
import io.toolisticon.aptk.tools.command.CommandWithReturnType;
import javax.lang.model.element.TypeElement;
/**
* Get all attributes of passed TypeElement and it's parents.
* attribute = field with adequate getter and setter method
*/
public class GetAttributesCommandWithInheritance implements CommandWithReturnType<TypeElement, AttributeResult[]> {
public final static GetAttributesCommandWithInheritance INSTANCE = new GetAttributesCommandWithInheritance();
@Override
public AttributeResult[] execute(TypeElement element) {
return BeanUtils.getAttributesWithInheritance(element);
}
}
|
3e03a1e86d0c851f98d61bceb96c8aaf4cd2ee6a | 4,806 | java | Java | parcial/codigo/RestserverClient/src/main/java/sv/edu/uesocc/ingenieria/prn335_2017/datos/definiciones/PostPaso.java | Carlos222Cuellar/java_rest | 81c6456a0d196d012e0da95bdcc14ba9079f5e04 | [
"MIT"
] | null | null | null | parcial/codigo/RestserverClient/src/main/java/sv/edu/uesocc/ingenieria/prn335_2017/datos/definiciones/PostPaso.java | Carlos222Cuellar/java_rest | 81c6456a0d196d012e0da95bdcc14ba9079f5e04 | [
"MIT"
] | null | null | null | parcial/codigo/RestserverClient/src/main/java/sv/edu/uesocc/ingenieria/prn335_2017/datos/definiciones/PostPaso.java | Carlos222Cuellar/java_rest | 81c6456a0d196d012e0da95bdcc14ba9079f5e04 | [
"MIT"
] | null | null | null | 30.0375 | 142 | 0.664794 | 1,497 | /*
* 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 sv.edu.uesocc.ingenieria.prn335_2017.datos.definiciones;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author carlos
*/
@Entity
@Table(name = "post_paso", catalog = "posts", schema = "public")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PostPaso.findAll", query = "SELECT p FROM PostPaso p")
, @NamedQuery(name = "PostPaso.findByIdPost", query = "SELECT p FROM PostPaso p WHERE p.postPasoPK.idPost = :idPost")
, @NamedQuery(name = "PostPaso.findByIdPaso", query = "SELECT p FROM PostPaso p WHERE p.postPasoPK.idPaso = :idPaso")
, @NamedQuery(name = "PostPaso.findByIdUsuario", query = "SELECT p FROM PostPaso p WHERE p.idUsuario = :idUsuario")
, @NamedQuery(name = "PostPaso.findByIdCategoria", query = "SELECT p FROM PostPaso p WHERE p.idCategoria = :idCategoria")
, @NamedQuery(name = "PostPaso.findByIdRol", query = "SELECT p FROM PostPaso p WHERE p.idRol = :idRol")
, @NamedQuery(name = "PostPaso.findByAprobado", query = "SELECT p FROM PostPaso p WHERE p.aprobado = :aprobado")
, @NamedQuery(name = "PostPaso.findByComentarios", query = "SELECT p FROM PostPaso p WHERE p.comentarios = :comentarios")})
public class PostPaso implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PostPasoPK postPasoPK;
@Column(name = "id_usuario")
private Integer idUsuario;
@Column(name = "id_categoria")
private Integer idCategoria;
@Column(name = "id_rol")
private Integer idRol;
@Column(name = "aprobado")
private Boolean aprobado;
@Size(max = 2147483647)
@Column(name = "comentarios")
private String comentarios;
@JoinColumn(name = "id_paso", referencedColumnName = "id_paso", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Paso paso;
@JoinColumn(name = "id_post", referencedColumnName = "id_post", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Post post;
public PostPaso() {
}
public PostPaso(PostPasoPK postPasoPK) {
this.postPasoPK = postPasoPK;
}
public PostPaso(int idPost, int idPaso) {
this.postPasoPK = new PostPasoPK(idPost, idPaso);
}
public PostPasoPK getPostPasoPK() {
return postPasoPK;
}
public void setPostPasoPK(PostPasoPK postPasoPK) {
this.postPasoPK = postPasoPK;
}
public Integer getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public Integer getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(Integer idCategoria) {
this.idCategoria = idCategoria;
}
public Integer getIdRol() {
return idRol;
}
public void setIdRol(Integer idRol) {
this.idRol = idRol;
}
public Boolean getAprobado() {
return aprobado;
}
public void setAprobado(Boolean aprobado) {
this.aprobado = aprobado;
}
public String getComentarios() {
return comentarios;
}
public void setComentarios(String comentarios) {
this.comentarios = comentarios;
}
public Paso getPaso() {
return paso;
}
public void setPaso(Paso paso) {
this.paso = paso;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
@Override
public int hashCode() {
int hash = 0;
hash += (postPasoPK != null ? postPasoPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PostPaso)) {
return false;
}
PostPaso other = (PostPaso) object;
if ((this.postPasoPK == null && other.postPasoPK != null) || (this.postPasoPK != null && !this.postPasoPK.equals(other.postPasoPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "sv.edu.uesocc.ingenieria.prn335_2017.datos.definiciones.PostPaso[ postPasoPK=" + postPasoPK + " ]";
}
}
|
3e03a2ba00618c5d132d27c83eb8012d2b9de138 | 884 | java | Java | harbor-core/src/main/java/com/icfolson/aem/harbor/core/components/content/list/dynamic/v1/AllowedDynamicListItemsDataSource.java | Citytechinc/harbor | f11bdd17ee52bc419c3ace5ab3b2c8d1c21fd2b1 | [
"Apache-2.0"
] | 8 | 2017-06-07T11:31:13.000Z | 2018-09-20T18:42:40.000Z | harbor-core/src/main/java/com/icfolson/aem/harbor/core/components/content/list/dynamic/v1/AllowedDynamicListItemsDataSource.java | Citytechinc/harbor | f11bdd17ee52bc419c3ace5ab3b2c8d1c21fd2b1 | [
"Apache-2.0"
] | 3 | 2017-08-01T20:44:43.000Z | 2018-04-17T19:18:47.000Z | harbor-core/src/main/java/com/icfolson/aem/harbor/core/components/content/list/dynamic/v1/AllowedDynamicListItemsDataSource.java | Citytechinc/harbor | f11bdd17ee52bc419c3ace5ab3b2c8d1c21fd2b1 | [
"Apache-2.0"
] | 3 | 2017-05-01T15:48:17.000Z | 2018-01-03T15:50:05.000Z | 38.434783 | 113 | 0.820136 | 1,498 | package com.icfolson.aem.harbor.core.components.content.list.dynamic.v1;
import com.icfolson.aem.harbor.api.components.content.list.dynamic.DynamicListItem;
import com.icfolson.aem.harbor.core.components.dynamics.v1.AbstractAllowedDynamicTypesDataSource;
import org.apache.sling.api.servlets.ServletResolverConstants;
import org.osgi.service.component.annotations.Component;
import javax.servlet.Servlet;
@Component(service = Servlet.class, property = {
ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "=" + AllowedDynamicListItemsDataSource.RESOURCE_TYPE
})
public class AllowedDynamicListItemsDataSource extends AbstractAllowedDynamicTypesDataSource {
public static final String RESOURCE_TYPE = NewDynamicListItem.RESOURCE_TYPE + "/allowedoptions";
@Override
public String getItemResourceType() {
return DynamicListItem.RESOURCE_TYPE;
}
}
|
3e03a36211f819db190c98f67d0ed2edd203761e | 648 | java | Java | src/main/java/fr/tse/fise2/heapoverflow/gui/GradesPanelView.java | DariosDjimado/Marvel-Search-Engine | 77c07e1cf2b9dd31501b94843ca7a6fc2f69d2cc | [
"Apache-2.0"
] | null | null | null | src/main/java/fr/tse/fise2/heapoverflow/gui/GradesPanelView.java | DariosDjimado/Marvel-Search-Engine | 77c07e1cf2b9dd31501b94843ca7a6fc2f69d2cc | [
"Apache-2.0"
] | null | null | null | src/main/java/fr/tse/fise2/heapoverflow/gui/GradesPanelView.java | DariosDjimado/Marvel-Search-Engine | 77c07e1cf2b9dd31501b94843ca7a6fc2f69d2cc | [
"Apache-2.0"
] | null | null | null | 28.173913 | 72 | 0.686728 | 1,499 | package fr.tse.fise2.heapoverflow.gui;
import java.util.Observable;
import java.util.Observer;
public class GradesPanelView extends GradesPanel implements Observer {
GradesPanelView() {
}
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
*/
@Override
public void update(Observable o, Object arg) {
}
}
|
3e03a385cda0f468599539f835619208427da220 | 5,014 | java | Java | src/procurementBehaviours/CheckMaterialStorage.java | gseteamproject/GrizzlyAgentCompany | d16ffc5ee0bc35ade6f8c894ce57a3d13fe25f70 | [
"MIT"
] | null | null | null | src/procurementBehaviours/CheckMaterialStorage.java | gseteamproject/GrizzlyAgentCompany | d16ffc5ee0bc35ade6f8c894ce57a3d13fe25f70 | [
"MIT"
] | null | null | null | src/procurementBehaviours/CheckMaterialStorage.java | gseteamproject/GrizzlyAgentCompany | d16ffc5ee0bc35ade6f8c894ce57a3d13fe25f70 | [
"MIT"
] | null | null | null | 41.098361 | 116 | 0.630634 | 1,500 | package procurementBehaviours;
import basicAgents.Procurement;
import basicClasses.Order;
import basicClasses.OrderPart;
import basicClasses.Product;
import communication.Communication;
import communication.MessageObject;
import interactors.OrderDataStore;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
public class CheckMaterialStorage extends OneShotBehaviour {
/**
*
*/
private static final long serialVersionUID = -4869963544017982955L;
private String requestedMaterial;
private OrderDataStore dataStore;
private ProcurementResponder interactionBehaviour;
private MessageObject msgObj;
private ACLMessage request;
public CheckMaterialStorage(ProcurementResponder interactionBehaviour, OrderDataStore dataStore) {
super(interactionBehaviour.getAgent());
requestedMaterial = interactionBehaviour.getRequest().getContent();
request = interactionBehaviour.getRequest();
this.interactionBehaviour = interactionBehaviour;
this.dataStore = dataStore;
}
@Override
public void action() {
Order order = Order.gson.fromJson(requestedMaterial, Order.class);
Procurement.isInMaterialStorage = true;
boolean isInQueue = false;
// check if this order is not in queue yet
isInQueue = Procurement.procurementQueue.contains(order);
// part of order, that needs to be produced
Order orderToBuy = new Order();
orderToBuy.id = order.id;
orderToBuy.deadline = order.deadline;
orderToBuy.price = order.price;
orderToBuy.agent = order.agent;
for (OrderPart orderPart : order.orderList) {
Product productToCheck = orderPart.getProduct();
String color = productToCheck.getColor();
Double size = productToCheck.getSize();
int amount = orderPart.getAmount();
msgObj = new MessageObject("AgentProcurement", "Asking about " + orderPart.getTextOfOrderPart());
Communication.server.sendMessageToClient(msgObj);
/*
System.out.println("ProcurementAgent: Asking materialStorage about " + orderPart.getTextOfOrderPart());
*/
int paintAmountInMS = Procurement.materialStorage.getAmountOfPaint(color);
int stoneAmountInMS = Procurement.materialStorage.getAmountOfStones(size);
if (paintAmountInMS >= amount && stoneAmountInMS >= amount) {
if (Procurement.isInMaterialStorage) {
Procurement.isInMaterialStorage = true;
}
msgObj = new MessageObject("AgentProcurement", "I say that materials for "
+ orderPart.getTextOfOrderPart() + " are in materialStorage. ");
Communication.server.sendMessageToClient(msgObj);
/*
System.out.println("ProcurementAgent: I say that materials for " + orderPart.getTextOfOrderPart()
+ " are in materialStorage");*/
} else {
// need to describe multiple statements to check every material
Procurement.isInMaterialStorage = false;
// creating new instance of OrderPart to change its amount
OrderPart paintOrderPart = new OrderPart(orderPart.getProduct().getPaint());
OrderPart stoneOrderPart = new OrderPart(orderPart.getProduct().getStone());
paintOrderPart.setAmount(amount - paintAmountInMS);
stoneOrderPart.setAmount(amount - stoneAmountInMS);
/*
System.out.println("paintOrderPart.getAmount() " + paintOrderPart.getAmount());
*/
if (paintOrderPart.getAmount() > 0) {
orderToBuy.orderList.add(paintOrderPart);
}
if (stoneOrderPart.getAmount() > 0) {
orderToBuy.orderList.add(stoneOrderPart);
}
}
}
if (!isInQueue && orderToBuy.orderList.size() > 0) {
String testGson = Order.gson.toJson(orderToBuy);
ACLMessage agree = (ACLMessage) request.clone();
agree.setContent(testGson);
// add order to queue
Procurement.procurementQueue.add(order);
msgObj = new MessageObject("AgentProcurement" , "senr info to ProcurementMarket to buy materials for "
+ orderToBuy.getTextOfOrder());
Communication.server.sendMessageToClient(msgObj);
/*
System.out.println("ProcurementAgent: send info to ProcurementMarket to buy materials for "
+ orderToBuy.getTextOfOrder());*/
// TODO: create another Set method
dataStore.setRequestMessage(agree);
myAgent.addBehaviour(new AskForAuction(interactionBehaviour, dataStore));
}
}
} |
3e03a3c081b42bc5e451fa8a9d608655db9964bf | 6,044 | java | Java | OriginalJuiceColoredGameTillaman/src/Main/Game.java | VSU-BS-Computer-Science/JuiceColored | abe6afcb0ab998968fb288b4d1f21dd5dd8de12c | [
"MIT"
] | null | null | null | OriginalJuiceColoredGameTillaman/src/Main/Game.java | VSU-BS-Computer-Science/JuiceColored | abe6afcb0ab998968fb288b4d1f21dd5dd8de12c | [
"MIT"
] | null | null | null | OriginalJuiceColoredGameTillaman/src/Main/Game.java | VSU-BS-Computer-Science/JuiceColored | abe6afcb0ab998968fb288b4d1f21dd5dd8de12c | [
"MIT"
] | null | null | null | 17.318052 | 76 | 0.699371 | 1,501 | package Main;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.JFileChooser;
import Main.Display.Display;
import Main.GFX.Assets;
import Main.GFX.SpriteSheet;
import Main.Input.MouseManager;
import Main.States.HomeState;
import Main.States.LoadingState;
import Main.States.MenuState;
import Main.States.States;
import Main.States.TimesUpState;
public class Game implements Runnable{
//CLASSES
private Thread thread;
private BufferStrategy bs;
private Graphics g;
private Display display;
private BufferedImage test;
private SpriteSheet sheet;
//ATTRIBUTES
public boolean running;
private String title;
private int width,height;
//INPUT
private MouseManager mouseManager;
//STATES
private States homeState, menuState,timesUpState,loadingState,loadingHome;
private static States currentState = null,previousState = null;
//MOUSE COORDINATES
private Point mousePoint;
private long timer;
private int ticks;
public Game(String title, int width, int height)
{
this.title = title;
this.width = width;
this.height = height;
this.running = false;
mouseManager = new MouseManager();
mousePoint = new Point(mouseManager.getMouseX(),mouseManager.getMouseY());
}
public void init()
{
display = new Display(title,width,height);
display.getFrame().addMouseListener(mouseManager);
display.getFrame().addMouseMotionListener(mouseManager);
display.getCanvas().addMouseListener(mouseManager);
display.getCanvas().addMouseMotionListener(mouseManager);
mousePoint = new Point(mouseManager.getMouseX(),mouseManager.getMouseY());
Assets.init();
menuState = new MenuState (this);
homeState = new HomeState(this);
timesUpState = new TimesUpState(this);
loadingState = new LoadingState(this,"MenuState");
loadingHome= new LoadingState(this,"HomeState");
currentState = homeState;
}
public void tick()
{
currentState.tick();
}
public void render()
{
bs = display.getCanvas().getBufferStrategy();
if(bs==null)
{
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//DRAW
g.fillRect(0, 0, width, height);
currentState.render(g);
//END
bs.show();
g.dispose();
}
public synchronized void start()
{
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop()
{
if(!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
init();
//CONSISTENT GAME LOOP
int fps = 60;
double timePerTick = 1000000000/fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
setTimer(0);
setTicks(0);
while(running)
{
now = System.nanoTime();
delta +=(now-lastTime)/timePerTick;
setTimer(getTimer() + now-lastTime);
lastTime = now;
if(delta>=1)
{
tick();
render();
setTicks(getTicks() + 1);
delta--;
}
}
stop();
}
//GETTERS AND SETTERS
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
public BufferStrategy getBs() {
return bs;
}
public void setBs(BufferStrategy bs) {
this.bs = bs;
}
public Graphics getG() {
return g;
}
public void setG(Graphics g) {
this.g = g;
}
public Display getDisplay() {
return display;
}
public void setDisplay(Display display) {
this.display = display;
}
public BufferedImage getTest() {
return test;
}
public void setTest(BufferedImage test) {
this.test = test;
}
public SpriteSheet getSheet() {
return sheet;
}
public void setSheet(SpriteSheet sheet) {
this.sheet = sheet;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public MouseManager getMouseManager() {
return mouseManager;
}
public void setMouseManager(MouseManager mouseManager) {
this.mouseManager = mouseManager;
}
public States getMenuState() {
return menuState;
}
public void setMenuState(States menuState) {
this.menuState = menuState;
}
public States getCurrentState() {
return currentState;
}
public void setCurrentState(States currentState) {
Game.currentState = currentState;
}
public float getMouseX()
{
return mouseManager.getMouseX();
}
public float getMouseY()
{
return mouseManager.getMouseY();
}
public Point getMousePoint() {
return mousePoint;
}
public void setMousePoint(Point mousePoint) {
this.mousePoint = mousePoint;
}
public long getTimer() {
return timer;
}
public void setTimer(long timer) {
this.timer = timer;
}
public int getTicks() {
return ticks;
}
public void setTicks(int ticks) {
this.ticks = ticks;
}
public static States getPreviousState() {
return previousState;
}
public static void setPreviousState(States previousState) {
Game.previousState = previousState;
}
public States getLoadingHome() {
return loadingHome;
}
public void setLoadingHome(States loadingHome) {
this.loadingHome = loadingHome;
}
public States getTimesUpState() {
return timesUpState;
}
public void setTimesUpState(States timesUpState) {
this.timesUpState = timesUpState;
}
public States getHomeState() {
return homeState;
}
public void setHomeState(States homeState) {
this.homeState = homeState;
}
public States getLoadingState() {
return loadingState;
}
public void setLoadingState(States loadingState) {
this.loadingState = loadingState;
}
}
|
3e03a3d7c2b6e72b2644a813768f479f26051a86 | 855 | java | Java | mongowp-core/src/main/java/com/torodb/mongowp/messages/response/ResponseOpCode.java | torodb/mongowp | 80db5ef560b4483a38965bab9f30d305727fb2ab | [
"Apache-2.0"
] | 19 | 2017-04-07T03:14:25.000Z | 2021-08-23T01:24:28.000Z | mongowp-core/src/main/java/com/torodb/mongowp/messages/response/ResponseOpCode.java | 8kdata/mongowp | 80db5ef560b4483a38965bab9f30d305727fb2ab | [
"Apache-2.0"
] | 27 | 2015-12-27T21:45:50.000Z | 2017-03-16T15:18:38.000Z | mongowp-core/src/main/java/com/torodb/mongowp/messages/response/ResponseOpCode.java | 8kdata/mongowp | 80db5ef560b4483a38965bab9f30d305727fb2ab | [
"Apache-2.0"
] | 12 | 2015-05-29T10:55:22.000Z | 2017-01-04T10:48:38.000Z | 25.147059 | 75 | 0.718129 | 1,502 | /*
* Copyright 2014 8Kdata Technology
*
* 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.torodb.mongowp.messages.response;
/**
*
*/
public enum ResponseOpCode {
OP_REPLY(1);
private final int opCode;
private ResponseOpCode(int opCode) {
this.opCode = opCode;
}
public int getOpCode() {
return opCode;
}
}
|
3e03a4ec935d1d2a478197fe7ba54266c4bb4078 | 5,383 | java | Java | tweed-data/src/main/java/de/siphalor/tweed4/data/DataContainer.java | Siphalor/tweed-api | d5eb3af6ce47a6ed5ecda107a44d9878deb810f5 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2020-07-28T15:42:16.000Z | 2022-03-10T12:11:02.000Z | tweed-data/src/main/java/de/siphalor/tweed4/data/DataContainer.java | Siphalor/tweed-api | d5eb3af6ce47a6ed5ecda107a44d9878deb810f5 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2019-05-19T20:27:29.000Z | 2021-01-16T19:42:00.000Z | tweed-data/src/main/java/de/siphalor/tweed4/data/DataContainer.java | Siphalor/tweed-api | d5eb3af6ce47a6ed5ecda107a44d9878deb810f5 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2019-07-21T18:51:41.000Z | 2020-10-24T20:45:32.000Z | 20.161049 | 154 | 0.650752 | 1,503 | /*
* Copyright 2021 Siphalor
*
* 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 de.siphalor.tweed4.data;
import java.util.Set;
public interface DataContainer<Key, V extends DataValue<V, L, O>, L extends DataList<V, L, O>, O extends DataObject<V, L, O>> extends DataValue<V, L, O> {
boolean has(Key key);
int size();
V get(Key key);
default boolean hasByte(Key key) {
return has(key) && get(key).isByte();
}
default boolean hasShort(Key key) {
return has(key) && get(key).isShort();
}
default boolean hasInt(Key key) {
return has(key) && get(key).isInt();
}
default boolean hasLong(Key key) {
return has(key) && get(key).isLong();
}
default boolean hasFloat(Key key) {
return has(key) && get(key).isFloat();
}
default boolean hasDouble(Key key) {
return has(key) && get(key).isDouble();
}
default boolean hasCharacter(Key key) {
return has(key) && get(key).isChar();
}
default boolean hasString(Key key) {
return has(key) && get(key).isString();
}
default boolean hasBoolean(Key key) {
return has(key) && get(key).isBoolean();
}
default boolean hasObject(Key key) {
return has(key) && get(key).isObject();
}
default boolean hasList(Key key) {
return has(key) && get(key).isList();
}
default byte getByte(Key key, byte def) {
V value = get(key);
if (value != null && value.isByte()) {
return value.asByte();
}
return def;
}
default short getShort(Key key, short def) {
V value = get(key);
if (value != null && value.isShort()) {
return value.asShort();
}
return def;
}
default int getInt(Key key, int def) {
V value = get(key);
if (value != null && value.isInt()) {
return value.asInt();
}
return def;
}
default long getLong(Key key, long def) {
V value = get(key);
if (value != null && value.isLong()) {
return value.asLong();
}
return def;
}
default float getFloat(Key key, float def) {
V value = get(key);
if (value != null && value.isFloat()) {
return value.asFloat();
}
return def;
}
default double getDouble(Key key, double def) {
V value = get(key);
if (value != null && value.isDouble()) {
return value.asDouble();
}
return def;
}
default char getCharacter(Key key, char def) {
V value = get(key);
if (value != null && value.isChar()) {
return value.asChar();
}
return def;
}
default String getString(Key key, String def) {
V value = get(key);
if (value != null && value.isString()) {
return value.asString();
}
return def;
}
default boolean getBoolean(Key key, boolean def) {
V value = get(key);
if (value != null && value.isBoolean()) {
return value.asBoolean();
}
return def;
}
default O getObject(Key key, O def) {
V value = get(key);
if (value != null && value.isObject()) {
return value.asObject();
}
return def;
}
default L getByte(Key key, L def) {
V value = get(key);
if (value != null && value.isList()) {
return value.asList();
}
return def;
}
V set(Key key, byte value);
V set(Key key, short value);
V set(Key key, int value);
V set(Key key, long value);
V set(Key key, float value);
V set(Key key, double value);
V set(Key key, char value);
V set(Key key, String value);
V set(Key key, boolean value);
V set(Key key, V value);
O addObject(Key key);
L addList(Key key);
/**
* Creates a new null representation with the given key. <br />
* <i>This should always be overridden. The default is only here for legacy reasons.</i>
* @param key The key to use.
* @return A new null representation. <code>null</code> indicates not supporting null values.
* @since 1.2
*/
default V addNull(Key key) {
return null;
}
@Override
default boolean isGenericNumber() {
return false;
}
@Override
default boolean isNumber() {
return false;
}
@Override
default boolean isByte() {
return false;
}
@Override
default boolean isShort() {
return false;
}
@Override
default boolean isInt() {
return false;
}
@Override
default boolean isLong() {
return false;
}
@Override
default boolean isFloat() {
return false;
}
@Override
default boolean isDouble() {
return false;
}
@Override
default boolean isChar() {
return false;
}
@Override
default boolean isString() {
return false;
}
@Override
default boolean isBoolean() {
return false;
}
@Override
default Number asNumber() {
return 0;
}
@Override
default byte asByte() {
return 0;
}
@Override
default short asShort() {
return 0;
}
@Override
default int asInt() {
return 0;
}
@Override
default long asLong() {
return 0;
}
@Override
default float asFloat() {
return 0;
}
@Override
default double asDouble() {
return 0;
}
@Override
default String asString() {
return "";
}
@Override
default boolean asBoolean() {
return !isEmpty();
}
Set<Key> keys();
void remove(Key key);
}
|
3e03a60fe4b2315f7df8c6f5f267e9988f6e82ab | 336 | java | Java | app/src/main/java/com/zhx/one/mvp/hp/view/iview/HPDetailView.java | zhanghanxuan123/One | e9509537103e3b7aecd984444d337e7b347dff21 | [
"Apache-2.0"
] | 1 | 2017-03-31T16:20:29.000Z | 2017-03-31T16:20:29.000Z | app/src/main/java/com/zhx/one/mvp/hp/view/iview/HPDetailView.java | zhanghanxuan123/One | e9509537103e3b7aecd984444d337e7b347dff21 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zhx/one/mvp/hp/view/iview/HPDetailView.java | zhanghanxuan123/One | e9509537103e3b7aecd984444d337e7b347dff21 | [
"Apache-2.0"
] | null | null | null | 17.684211 | 56 | 0.690476 | 1,504 | package com.zhx.one.mvp.hp.view.iview;
import com.zhx.one.base.MvpView;
import com.zhx.one.bean.HPDetailEntity;
/**
* Created by 张瀚漩 on 2016/11/30.
*/
public interface HPDetailView extends MvpView{
void getDataSuccess(HPDetailEntity hpDetailEntity);
void getError(String error);
void refresh();
}
|
3e03a6d9040731044666fd830a1840310d338f25 | 481 | java | Java | src/com/endava/drodriguez/domainmodel/DebitCard.java | Juan7655/uml-challenge | 9ee592eb8f1e15518f80346e46217ad10428177f | [
"MIT"
] | null | null | null | src/com/endava/drodriguez/domainmodel/DebitCard.java | Juan7655/uml-challenge | 9ee592eb8f1e15518f80346e46217ad10428177f | [
"MIT"
] | null | null | null | src/com/endava/drodriguez/domainmodel/DebitCard.java | Juan7655/uml-challenge | 9ee592eb8f1e15518f80346e46217ad10428177f | [
"MIT"
] | null | null | null | 22.904762 | 73 | 0.654886 | 1,505 | package com.endava.drodriguez.domainmodel;
import java.util.Date;
public class DebitCard extends PaymentMethod{
private int number;
private Date expDate;
private Issuer issuer;
public DebitCard(int number, Date expDate, Issuer issuer) {
this.number = number;
this.expDate = expDate;
this.issuer = issuer;
}
@Override
public void authorize() {
System.out.println("Check number: " + number + " -- authorized");
}
}
|
3e03a704a81cc30f84f5d63c99c9bca02a62f0b0 | 356 | java | Java | hongjf/src/main/java/com/hongjf/beanPostProcessor/Config.java | ishongjf/spring | 4beafad9d8d271d60e5078548d332c5864501bbf | [
"Apache-2.0"
] | null | null | null | hongjf/src/main/java/com/hongjf/beanPostProcessor/Config.java | ishongjf/spring | 4beafad9d8d271d60e5078548d332c5864501bbf | [
"Apache-2.0"
] | null | null | null | hongjf/src/main/java/com/hongjf/beanPostProcessor/Config.java | ishongjf/spring | 4beafad9d8d271d60e5078548d332c5864501bbf | [
"Apache-2.0"
] | null | null | null | 22.25 | 69 | 0.789326 | 1,506 | package com.hongjf.beanPostProcessor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @ClassName Config
* @Author hongjf
* @Date 2021/5/20 下午10:20
* @Version 1.0
*/
@ComponentScan("com.hongjf.beanPostProcessor")
@EnableAspectJAutoProxy
public class Config {
}
|
3e03a8d8d45249d38785caaf460fa60e384b4862 | 554 | java | Java | bsp-user-8001/src/main/java/com/neusoft/bsp/user/entity/User.java | William-Choe/bs-platform-backend | 6057e001736c15b5b924b6adfc239f70193615e1 | [
"Apache-2.0"
] | null | null | null | bsp-user-8001/src/main/java/com/neusoft/bsp/user/entity/User.java | William-Choe/bs-platform-backend | 6057e001736c15b5b924b6adfc239f70193615e1 | [
"Apache-2.0"
] | null | null | null | bsp-user-8001/src/main/java/com/neusoft/bsp/user/entity/User.java | William-Choe/bs-platform-backend | 6057e001736c15b5b924b6adfc239f70193615e1 | [
"Apache-2.0"
] | 1 | 2022-02-28T12:27:45.000Z | 2022-02-28T12:27:45.000Z | 22.16 | 42 | 0.722022 | 1,507 | package com.neusoft.bsp.user.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String userId;
private String username;
private String password;
private String name;
private String email;
private String phone;
private String lastLogin;
private String roleId;
private Role role;
private List<Permission> permissions;
private String walletId;
}
|
3e03a9148f0b421f843e2c45b6400661da811e3e | 1,667 | java | Java | acn-core/src/main/java/com/konexios/acn/client/model/TelemetryStatModel.java | konexios/acn-sdk-java | a6b49ce2304a9d1eaf0d8fa1ebeb6e7ee9504b6d | [
"Apache-2.0"
] | null | null | null | acn-core/src/main/java/com/konexios/acn/client/model/TelemetryStatModel.java | konexios/acn-sdk-java | a6b49ce2304a9d1eaf0d8fa1ebeb6e7ee9504b6d | [
"Apache-2.0"
] | null | null | null | acn-core/src/main/java/com/konexios/acn/client/model/TelemetryStatModel.java | konexios/acn-sdk-java | a6b49ce2304a9d1eaf0d8fa1ebeb6e7ee9504b6d | [
"Apache-2.0"
] | null | null | null | 25.257576 | 80 | 0.668866 | 1,508 | /*******************************************************************************
* Copyright 2021 Konexios, 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.konexios.acn.client.model;
import java.io.Serializable;
public class TelemetryStatModel implements Serializable {
private static final long serialVersionUID = -8112688070639907229L;
private String deviceHid;
private String name;
private String value;
public TelemetryStatModel withDeviceHid(String deviceHid) {
setDeviceHid(deviceHid);
return this;
}
public TelemetryStatModel withName(String name) {
setName(name);
return this;
}
public TelemetryStatModel withValue(String value) {
setValue(value);
return this;
}
public String getDeviceHid() {
return deviceHid;
}
public void setDeviceHid(String deviceHid) {
this.deviceHid = deviceHid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
3e03a9b804ae349f94cf13c630c99640d68c6c4b | 4,702 | java | Java | src/test/java/webase/event/client/front/FrontControllerTest.java | CodingCattwo/WeBASE-Event-Client | 16abce84618dfab61263aaa3f6aaea9f5135edb2 | [
"Apache-2.0"
] | 4 | 2020-02-26T08:37:33.000Z | 2020-05-11T08:26:54.000Z | src/test/java/webase/event/client/front/FrontControllerTest.java | CodingCattwo/WeBASE-Event-Client | 16abce84618dfab61263aaa3f6aaea9f5135edb2 | [
"Apache-2.0"
] | null | null | null | src/test/java/webase/event/client/front/FrontControllerTest.java | CodingCattwo/WeBASE-Event-Client | 16abce84618dfab61263aaa3f6aaea9f5135edb2 | [
"Apache-2.0"
] | 2 | 2020-02-21T10:11:22.000Z | 2020-02-21T12:12:01.000Z | 44.780952 | 822 | 0.707359 | 1,509 | /**
* Copyright 2014-2019 the original author or authors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 webase.event.client.front;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import webase.event.client.BaseTest;
import webase.event.client.front.entity.ReqNewBlockEventRegister;
import webase.event.client.front.entity.ReqContractEventRegister;
@WebAppConfiguration
public class FrontControllerTest extends BaseTest {
private MockMvc mockMvc;
private Integer groupId = 1;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* need to create exchange and queue with routing key in mq
* @throws Exception
*/
@Test
public void testRegisterBlockNotify() throws Exception {
ReqNewBlockEventRegister param = new ReqNewBlockEventRegister();
param.setExchangeName("exchange_group1");
param.setQueueName("alice");
param.setAppId("appId001");
param.setGroupId(groupId);
ResultActions resultActions = mockMvc
.perform(MockMvcRequestBuilders.post("/front/blockNotify").
content(JSON.toJSONString(param)).
contentType(MediaType.APPLICATION_JSON)
);
resultActions.
andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
System.out
.println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
/**
* need to create exchange and queue with routing key in mq
* @throws Exception
*/
@Test
public void testRegisterEventLogPush() throws Exception {
ReqContractEventRegister param = new ReqContractEventRegister();
param.setGroupId(groupId);
param.setAppId("appId3");
param.setExchangeName("exchange_group1");
param.setQueueName("alice");
param.setContractAbi("[{\"constant\":false,\"inputs\":[{\"name\":\"n\",\"type\":\"string\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"n\",\"type\":\"string\"}],\"name\":\"set2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"name\",\"type\":\"string\"}],\"name\":\"SetName\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"name\",\"type\":\"string\"}],\"name\":\"SetName2\",\"type\":\"event\"}]");
param.setFromBlock("latest");
param.setToBlock("latest");
param.setContractAddress("0x8ec4f530256ad3ee3957b2bdccc6d58252ecf29d");
List<String> topics = new ArrayList<>();
topics.add("SetName(string)");
param.setTopicList(topics);
ResultActions resultActions = mockMvc
.perform(MockMvcRequestBuilders.post("/front/eventLogPush").
content(JSON.toJSONString(param)).
contentType(MediaType.APPLICATION_JSON)
);
resultActions.
andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
System.out
.println("response:" + resultActions.andReturn().getResponse().getContentAsString());
}
}
|
3e03aa1051ea0c71f196ca07271574b6e5e79f9a | 2,236 | java | Java | core/src/main/java/org/hisp/dhis/android/core/arch/db/querybuilders/internal/ReadOnlySQLStatementBuilder.java | mohamedkhairy/dhis2-android-sdk | 476b5be377d7b460419e9150aa913a4237930900 | [
"BSD-3-Clause"
] | 34 | 2015-02-25T09:49:09.000Z | 2021-11-12T11:38:53.000Z | core/src/main/java/org/hisp/dhis/android/core/arch/db/querybuilders/internal/ReadOnlySQLStatementBuilder.java | mohamedkhairy/dhis2-android-sdk | 476b5be377d7b460419e9150aa913a4237930900 | [
"BSD-3-Clause"
] | 76 | 2015-03-26T12:46:49.000Z | 2022-03-09T07:12:34.000Z | core/src/main/java/org/hisp/dhis/android/core/arch/db/querybuilders/internal/ReadOnlySQLStatementBuilder.java | mohamedkhairy/dhis2-android-sdk | 476b5be377d7b460419e9150aa913a4237930900 | [
"BSD-3-Clause"
] | 79 | 2015-03-11T01:39:03.000Z | 2021-11-11T10:55:20.000Z | 43 | 83 | 0.771914 | 1,510 | /*
* Copyright (c) 2004-2021, University of Oslo
* 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 the HISP project 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.hisp.dhis.android.core.arch.db.querybuilders.internal;
import org.hisp.dhis.android.core.arch.db.sqlorder.internal.SQLOrderType;
public interface ReadOnlySQLStatementBuilder {
String selectWhere(String whereClause);
String selectWhere(String whereClause, int limit);
String selectWhere(String whereClause, String orderByClause);
String selectWhere(String whereClause, String orderByClause, int limit);
String selectOneOrderedBy(String orderingColumName, SQLOrderType orderingType);
String selectAll();
String count();
String countWhere(String whereClause);
String countAndGroupBy(String column);
}
|
3e03aa4f1d9f1f66c4f816a8f0449924823220ef | 3,121 | java | Java | plugins/griffon-tasks-plugin/src/test/java/org/codehaus/griffon/runtime/tasks/TaskExecutionTest.java | tschulte/griffon | 350d5e4a083175a03f43590245d6f64f085ab0ed | [
"Apache-2.0"
] | null | null | null | plugins/griffon-tasks-plugin/src/test/java/org/codehaus/griffon/runtime/tasks/TaskExecutionTest.java | tschulte/griffon | 350d5e4a083175a03f43590245d6f64f085ab0ed | [
"Apache-2.0"
] | null | null | null | plugins/griffon-tasks-plugin/src/test/java/org/codehaus/griffon/runtime/tasks/TaskExecutionTest.java | tschulte/griffon | 350d5e4a083175a03f43590245d6f64f085ab0ed | [
"Apache-2.0"
] | null | null | null | 33.612903 | 96 | 0.654511 | 1,511 | /*
* Copyright 2011 Eike Kettner
*
* 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.codehaus.griffon.runtime.tasks;
import griffon.core.injection.Module;
import griffon.core.test.GriffonUnitRule;
import griffon.core.threading.UIThreadManager;
import griffon.plugins.tasks.*;
import griffon.util.CollectionUtils;
import org.codehaus.griffon.runtime.core.injection.AbstractModule;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
/**
* @author <a href="mailto:[email protected]">Eike Kettner</a>
* @since 20.07.11 19:16
*/
public class TaskExecutionTest {
private final static Logger LOG = LoggerFactory.getLogger(TaskExecutionTest.class);
static {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
}
@Rule
public final GriffonUnitRule griffon = new GriffonUnitRule();
@Inject
private TaskManager manager;
@Test
public void testExceptionTask() throws Exception {
Task<Long, Long> task = new LongTask();
final TaskControl<Long> control = manager.create(task);
control.getContext().addListener(new TaskListener() {
public void stateChanged(ChangeEvent<Task.State> event) {
LOG.info(">>> State: " + event.getOldValue() + " => " + event.getNewValue());
if (event.getNewValue() == Task.State.STARTED) {
LOG.info("Started: " + event.getSource().getStartedTimestamp());
}
}
public void progressChanged(ChangeEvent<Integer> event) {
LOG.info(">>> Progress: " + event.getOldValue() + " => " + event.getNewValue());
}
public void phaseChanged(ChangeEvent<String> event) {
LOG.info(">>> Phase: " + event.getOldValue() + " => " + event.getNewValue());
}
});
Long value = control.waitFor();
assertNotNull(value);
assertEquals(value.intValue(), 40L);
LOG.info("Waited for task: " + value);
}
@Nonnull
private List<Module> moduleOverrides() {
return CollectionUtils.<Module>newList(new AbstractModule() {
@Override
protected void doConfigure() {
bind(UIThreadManager.class)
.to(SwingUIThreadManager.class)
.asSingleton();
}
});
}
}
|
Subsets and Splits