method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
0182a442-98db-4e76-81e9-ef353e5ea981 | 9 | private void list () {
String options;
String name;
boolean onlyArmed;
Item[] data;
while (true) {
name = "";
onlyArmed = false;
System.out.println("O que você deseja visualizar?\n" +
"a. Informações sobre um item\n" +
"b. Todos os itens no inventário\n" +
"c. Itens equipados\n" +
"d. Voltar");
//accepting multiple options
options = this.input.nextLine();
if (options.contains("d")) {
return;
}
if (options.contains("a")) {
System.out.print("Nome do ítem: ");
name = this.input.nextLine();
}
if (options.contains("c")) {
onlyArmed = true;
}
if (options.contains("b")) {
onlyArmed = false;
name = "";
}
data = this.manager.filter(this.manager.getAll(), this.manager.getRig(), name, onlyArmed);
if (data.length == 0) {
System.out.println("\nSem resultados.\n");
if (name.equals("")) {
break;
}
continue;
}
System.out.println("\nResultados:\n");
for (Item datum : data) {
if (datum != null) {
System.out.println("\n" + datum);
}
}
break;
}
} |
05ce4526-6fff-4a78-9686-a6f54fd3edb4 | 5 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((marca == null) ? 0 : marca.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((preco == null) ? 0 : preco.hashCode());
result = prime * result + ((tipo == null) ? 0 : tipo.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
} |
f6f1a330-e161-49fc-b6d8-2893a2a9dda3 | 2 | public static ConnectionType byPersistentName( String name ){
for( ConnectionType type : values() ){
if( type.getPersistentName().equals( name )){
return type;
}
}
throw new IllegalArgumentException( "unknown name: " + name );
} |
2e2bb7d7-acac-4802-b592-2229e72ea13e | 5 | public void analyseForKeywords(String filename)
{
LinkedList<String> foundKeywords = extractKeywords(filename);
Vector<String> keywordsToAdd = new Vector<String>();
for (String word : foundKeywords)
{
word = word.toLowerCase();
//for each word increment count for possible count
if (keyWordCount.containsKey(word))
{
int i = keyWordCount.get(word);
if (i < Integer.MAX_VALUE)
{
i++;
keyWordCount.put(word, i);
}
if (!keywords.contains(word) && i >= Settings.NEW_KEYWORD_OCCURANCE_COUNT)
{
System.out.println("Adding new keyword: " + word);
keywords.add(word);
}
}
else
keyWordCount.put(word, 1);
}
} |
d9f5a07c-e810-4d06-8f4d-c28a3f39ed66 | 4 | @Override
public void load() {
Plugin cp = Bukkit.getServer().getPluginManager().getPlugin("CoreProtect");
// Check that CoreProtect is loaded
if (cp != null && cp instanceof CoreProtect) {
this.coreprotect = ((CoreProtect)cp).getAPI();
if (coreprotect.isEnabled()==true){
if (coreprotect.APIVersion() >= 2) {
plugin.log("Coreprotect was loaded");
this.loaded = true;
}
else {
plugin.log("Coreprotect Version must be 2.0.8 or higher!");
}
}
else {
plugin.log("Coreprotect was found, but the CoreProtect API was disabled");
}
}
} |
45b64ce5-2c1d-4c58-a155-bb8fb52de6a1 | 0 | @Override
public void windowDeiconified(WindowEvent arg0)
{
} |
a50ffa18-93c4-4898-b8c0-2271f752cc07 | 4 | public static boolean isAlphanumericSpace(String str)
{
if (str == null)
{
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++)
{
if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' '))
{
return false;
}
}
return true;
} |
11a9bb07-3d98-4ae0-996f-a847f467bef7 | 2 | public V get(K key) {
for (int i = 0; i < currentSize; ++i) {
if (key == keys[i]) {
currentIndex = i;
return values[i];
}
}
return null;
} |
1d50eca2-3d27-487e-bcac-b6387a2f9b89 | 3 | @Override
public void copyFrom(Matrix source) {
if (!isSameLength(source))
throw new IndexOutOfBoundsException("mxn do not equal this matrix");
for (int i = 1; i <= this.getM(); i++) {
for (int j = 1; j <= this.getN(); j++) {
this.insert(i, j, source.get(i, j));
}
}
} |
95041405-47ab-4730-a38c-fed42211d1c4 | 8 | public NBestIterator(TagLattice<String> lattice,
int[] tokenStarts,
int[] tokenEnds,
int maxResults,
String beginTagPrefix,
String inTagPrefix,
String outTag) {
mBeginTagPrefix = beginTagPrefix;
mInTagPrefix = inTagPrefix;
mOutTag = outTag;
mLattice = lattice;
mTokenStarts = tokenStarts;
mTokenEnds = tokenEnds;
mMaxResults = maxResults;
Set<String> chunkTypeSet = new HashSet<String>();
SymbolTable tagSymbolTable = lattice.tagSymbolTable();
for (int k = 0; k < lattice.numTags(); ++k)
if (lattice.tag(k).startsWith(mInTagPrefix))
chunkTypeSet.add(lattice.tag(k).substring(mInTagPrefix.length()));
mChunkTypes = chunkTypeSet.toArray(Strings.EMPTY_STRING_ARRAY);
mBeginTagIds = new int[mChunkTypes.length];
mInTagIds = new int[mChunkTypes.length];
for (int j = 0; j < mChunkTypes.length; ++j) {
mBeginTagIds[j] = tagSymbolTable.symbolToID(mBeginTagPrefix + mChunkTypes[j]);
mInTagIds[j] = tagSymbolTable.symbolToID(mInTagPrefix + mChunkTypes[j]);
}
mOutTagId = tagSymbolTable.symbolToID(mOutTag);
mStateQueue = new BoundedPriorityQueue<NBestState>(ScoredObject.comparator(),
maxResults);
mChunkQueue = new BoundedPriorityQueue<Chunk>(ScoredObject.comparator(),
maxResults);
double[] nonContBuf = new double[lattice.numTags()-1];
for (int j = 0; j < mChunkTypes.length; ++j) {
int lastN = lattice.numTokens() - 1;
if (lastN < 0) continue;
String chunkType = mChunkTypes[j];
int inTagId = mInTagIds[j];
int beginTagId = mBeginTagIds[j];
// System.out.println("beginTagId=" + beginTagId + " lastN=" + lastN);
mChunkQueue.offer(ChunkFactory.createChunk(mTokenStarts[lastN],
mTokenEnds[lastN],
chunkType,
lattice.logProbability(lastN,beginTagId)));
if (lastN > 0) {
mStateQueue.offer(new NBestState(lattice.logBackward(lastN,inTagId),
lastN,lastN,j));
}
for (int n = 0; n < lastN; ++n) {
double nonCont = nonContLogSumExp(j,n,beginTagId,lattice,nonContBuf);
mChunkQueue.offer(ChunkFactory.createChunk(mTokenStarts[n],
mTokenEnds[n],
chunkType,
nonCont + lattice.logForward(n,beginTagId)
- lattice.logZ()));
}
for (int n = 1; n < lastN; ++n) {
double nonCont = nonContLogSumExp(j,n,inTagId,lattice,nonContBuf);
mStateQueue.offer(new NBestState(nonCont,n,n,j));
}
}
} |
91e7248a-7d7b-41cd-873d-ce2b1506fd2e | 0 | public Employee clone() throws CloneNotSupportedException
{
// call Object.clone()
Employee cloned = (Employee) super.clone();
// clone mutable fields
cloned.hireDay = (Date) hireDay.clone();
return cloned;
} |
40ca07fb-a511-4423-b3cc-9d344a175054 | 4 | private void addAll()
{
// Traverse hierarchy
Class<?> clazz = this.object.getClass();
do
{
// Traverse methods
for(Method m : clazz.getDeclaredMethods())
// Add
this.add(m);
}while((clazz = clazz.getSuperclass()) != IJeTTEventCallback.class &&
clazz != Object.class);
} |
1378590b-26c5-4da5-a278-9218d6a4c49b | 8 | private RepairCandidate errorRecovery(int error_token, boolean forcedError) {
this.errorToken = error_token;
this.errorTokenStart = lexStream.start(error_token);
int prevtok = lexStream.previous(error_token);
int prevtokKind = lexStream.kind(prevtok);
if(forcedError) {
int name_index = Parser.terminal_index[TokenNameLBRACE];
reportError(INSERTION_CODE, name_index, prevtok, prevtok);
RepairCandidate candidate = new RepairCandidate();
candidate.symbol = TokenNameLBRACE;
candidate.location = error_token;
lexStream.reset(error_token);
stateStackTop = nextStackTop;
for (int j = 0; j <= stateStackTop; j++) {
stack[j] = nextStack[j];
}
locationStack[stateStackTop] = error_token;
locationStartStack[stateStackTop] = lexStream.start(error_token);
return candidate;
}
//
// Try primary phase recoveries. If not successful, try secondary
// phase recoveries. If not successful and we are at end of the
// file, we issue the end-of-file error and quit. Otherwise, ...
//
RepairCandidate candidate = primaryPhase(error_token);
if (candidate.symbol != 0) {
return candidate;
}
candidate = secondaryPhase(error_token);
if (candidate.symbol != 0) {
return candidate;
}
if (lexStream.kind(error_token) == EOFT_SYMBOL) {
reportError(EOF_CODE,
Parser.terminal_index[EOFT_SYMBOL],
prevtok,
prevtok);
candidate.symbol = 0;
candidate.location = error_token;
return candidate;
}
//
// At this point, primary and (initial attempt at) secondary
// recovery did not work. We will now get into "panic mode" and
// keep trying secondary phase recoveries until we either find
// a successful recovery or have consumed the remaining input
// tokens.
//
while(lexStream.kind(buffer[BUFF_UBOUND]) != EOFT_SYMBOL) {
candidate = secondaryPhase(buffer[MAX_DISTANCE - MIN_DISTANCE + 2]);
if (candidate.symbol != 0) {
return candidate;
}
}
//
// We reached the end of the file while panicking. Delete all
// remaining tokens in the input.
//
int i;
for (i = BUFF_UBOUND; lexStream.kind(buffer[i]) == EOFT_SYMBOL; i--){/*empty*/}
reportError(DELETION_CODE,
Parser.terminal_index[prevtokKind],//Parser.terminal_index[lexStream.kind(prevtok)],
error_token,
buffer[i]);
candidate.symbol = 0;
candidate.location = buffer[i];
return candidate;
} |
1e9b53e2-8bb7-497d-8c36-99c86e5af9fe | 2 | private boolean pluginFile(String name) {
for (final File file : new File("plugins").listFiles()) {
if (file.getName().equals(name)) {
return true;
}
}
return false;
} |
36cab972-626d-44aa-8cc2-d19cfaed2e9b | 2 | public void save() {
String name = JOptionPane.showInputDialog(this, "Enter a name for the table.");
mortgage.setName(name);
mortgage.setStartCapital(startCapital);
try {
mortgages.addBusinessObject(mortgage);
dispose();
} catch (DuplicateNameException e) {
ActionUtils.showErrorMessage(ActionUtils.MORTGAGE_DUPLICATE_NAME);
} catch (EmptyNameException e) {
ActionUtils.showErrorMessage(ActionUtils.MORTGAGE_NAME_EMPTY);
}
} |
2f9f1540-6b88-49fb-8a48-0363b48bf948 | 4 | public void unMuteMedia() {
if (Debug.video) System.out.println("VideoPlayer -> unMuteMedia called");
if ((null != player) && realizeComplete) {
gainControl.setMute(false);
if (Debug.video) System.out.println("VideoPlayer -> unMuteMedia un-set");
}
} |
e6a4bb4b-10be-451d-a644-5b3ba2f13c6a | 9 | protected org.w3c.dom.Node getAdapter()
{
if (adapter == null)
{
switch (this.type)
{
case RootNode:
adapter = new DOMDocumentImpl(this);
break;
case StartTag:
case StartEndTag:
adapter = new DOMElementImpl(this);
break;
case DocTypeTag:
adapter = new DOMDocumentTypeImpl(this);
break;
case CommentTag:
adapter = new DOMCommentImpl(this);
break;
case TextNode:
adapter = new DOMTextImpl(this);
break;
case CDATATag:
adapter = new DOMCDATASectionImpl(this);
break;
case ProcInsTag:
adapter = new DOMProcessingInstructionImpl(this);
break;
default:
adapter = new DOMNodeImpl(this);
}
}
return adapter;
} |
9e6c9046-a8c1-4d3d-87f7-b3e2185f8b14 | 9 | private void readSubframe(int channel, int bps) throws IOException, FrameDecodeException {
int x;
x = bitStream.readRawUInt(8); /* MAGIC NUMBER */
boolean haveWastedBits = ((x & 1) != 0);
x &= 0xfe;
int wastedBits = 0;
if (haveWastedBits) {
wastedBits = bitStream.readUnaryUnsigned() + 1;
bps -= wastedBits;
}
// Lots of magic numbers here
if ((x & 0x80) != 0) {
frameListeners.processError("ReadSubframe LOST_SYNC: " + Integer.toHexString(x & 0xff));
//state = DECODER_SEARCH_FOR_FRAME_SYNC;
throw new FrameDecodeException("ReadSubframe LOST_SYNC: " + Integer.toHexString(x & 0xff));
//return true;
} else if (x == 0) {
frame.subframes[channel] = new ChannelConstant(bitStream, frame.header, channelData[channel], bps, wastedBits);
} else if (x == 2) {
frame.subframes[channel] = new ChannelVerbatim(bitStream, frame.header, channelData[channel], bps, wastedBits);
} else if (x < 16) {
//state = DECODER_UNPARSEABLE_STREAM;
throw new FrameDecodeException("ReadSubframe Bad Subframe Type: " + Integer.toHexString(x & 0xff));
} else if (x <= 24) {
//FLACSubframe_Fixed subframe = read_subframe_fixed_(channel, bps, (x >> 1) & 7);
frame.subframes[channel] = new ChannelFixed(bitStream, frame.header, channelData[channel], bps, wastedBits, (x >> 1) & 7);
} else if (x < 64) {
//state = DECODER_UNPARSEABLE_STREAM;
throw new FrameDecodeException("ReadSubframe Bad Subframe Type: " + Integer.toHexString(x & 0xff));
} else {
frame.subframes[channel] = new ChannelLPC(bitStream, frame.header, channelData[channel], bps, wastedBits, ((x >> 1) & 31) + 1);
}
if (haveWastedBits) {
int i;
x = frame.subframes[channel].getWastedBits();
for (i = 0; i < frame.header.blockSize; i++)
channelData[channel].getOutput()[i] <<= x;
}
} |
fb78867a-ca9e-432b-9e12-221549e43f96 | 1 | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainActivity window = new MainActivity();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
a28fca55-5c34-4db5-b314-36573d8d3c56 | 6 | private void loadDay() throws SQLException, Exception {
dDL = new DayDL(c);
DecimalFormat decFormat = new DecimalFormat("#.##");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = StrUtil.dateParser(dateFormat.format(date));
//fetching day details
d = dDL.fetchDayByDate(sqlDate);
//first clearing fields
clear();
//setting values on fields and check boxes
dateL.setText(dateL.getText() + dateFormat.format(date));
statusL.setText(date.toString());
if (d != null) {
existing = true;
id = d.getDayID();
summaryArea.setText(d.getSummary());
expensesF.setText(decFormat.format(d.getExpenses()));
if (d.getSex() == 1) {
sexChk.setSelected(true);
}
if (d.getWork() == 1) {
workChk.setSelected(true);
}
if (d.getFun() == 1) {
funChk.setSelected(true);
}
if (d.getSpecial() == 1) {
specialChk.setSelected(true);
}
if (d.getAlcohol() == 1) {
alcoholChk.setSelected(true);
}
loadContactL();
} else {
existing = false;
}
} |
295ea297-dd4a-4abb-b0ca-0bd245145f2e | 3 | private final void createStateManager() {
// I wonder if we can lazily load this each time somehow?
stateManager = new StateManager("mainMenuStateManager");
// Add the state which will animate the buttons coming into the screen
// from either set. When the buttons have reached the middle it will
// transition into the registerEvents state
stateManager.addPossibleState(new State("animatingButtons") {
@Override
public void logicUpdate(GameTime gameTime) {
// The current iteration within the foreach loop. foreach loop
// is faster than for(get(i)), this is why it's outside
int i = 0;
int plannedVelocity;
// iterate through each logical child added to the menuOptions
// gamelayer, in this case it will be only the
// GameButtonGraphical children
for (ILogical logicalObject : menuOptions.getAllLogicalChildren()) {
// Ilogical object doesn't implement IPositionable, so we
// have to typecast to the right interface. This allows us
// to update the x,y coords
IPositionable option = (IPositionable) logicalObject;
// Move right if endLocation > current x pos.
// We set the plannedVelocity to either be the desired
// menuVelocity given as a field within this class, or we
// set it to the closest distance that it can be to the goal
// location so that it doesn't 'overshoot' the mark given
plannedVelocity = endLocationX > option.getX() ?
Math.min((int) (endLocationX - option.getX()), menuVelocity) :
Math.max(-menuVelocity, (int) (endLocationX - option.getX()));
option.setX(option.getX() + plannedVelocity);
// Transiton to the next State, if we've reached our goal
// destination, progress to the next state. Otherwise the
// next state is our own.
setTransitionStateName(option.getX() == endLocationX ? "registerEvents" : getName());
}
}
});
// Registers the button's events by calling the method
// registerButtonEvents
stateManager.addPossibleState(new State("registerEvents") {
@Override
public void logicUpdate(GameTime gameTime) {
registerButtonEvents();
setTransitionStateName("idle");
}
});
stateManager.addPossibleState(new State("idle") {
@Override
public void logicUpdate(GameTime gameTime) {
setTransitionStateName(getName());
}
});
} |
fe710324-93db-4c58-8b2b-d9fbd657b6c4 | 3 | public void visitNewMultiArrayExpr(final NewMultiArrayExpr expr) {
final Expr[] dims = expr.dimensions;
for (int i = 0; i < dims.length; i++) {
if (dims[i] == previous) {
if (i > 0) {
check(dims[i - 1]);
} else {
previous = expr;
expr.parent().visit(this);
}
}
}
} |
1968ce61-fab9-432b-80ba-f942f6d75f27 | 0 | public int getACC() {
return acc;
} |
a0e7841b-5825-47ea-8ebc-537b3eed4ab7 | 9 | public int squeezOutOf(AABB r, Vec2D a_out)
{
// up, left, down, right
double[] squeeze = {max.y-r.min.y, max.x-r.min.x, r.max.y-min.y, r.max.x-min.x};
int collidingSide = 0;
for(int i = 0; i < squeeze.length; ++i)
{
if(squeeze[i] < squeeze[collidingSide])
collidingSide = i;
}
double dx = 0, dy = 0;
switch(collidingSide)
{
case N: dy = -squeeze[0];break;
case W: dx = -squeeze[1];break;
case S: dy = squeeze[2];break;
case E: dx = squeeze[3];break;
}
if(dx != 0 || dy != 0)
{
if(a_out != null)
{
a_out.x += dx;
a_out.y += dy;
}
translate(dx, dy);
return collidingSide;
}
return -1;
} |
dc996e6d-7c11-462a-a43f-51b7eb085fc3 | 7 | protected AbilityWorldConfig(FileConfiguration cfg, String folder)
{
/* ################ UseWorldSettings ################ */
if (folder.length() != 0)
{
useWorldSettings = cfg.getBoolean("UseWorldSettings", false);
set(cfg, "UseWorldSettings", useWorldSettings);
}
/* ################ EnabledSpawnReasons ################ */
enabledSpawnReasons = new EnumSettingContainer(SpawnReason.class, cfg.getList("EnabledSpawnReasons", null), "The Spawn Reason '%s' is invalid");
enabledSpawnReasons.addDefaults((Object[]) SpawnReason.values());
set(cfg, "EnabledSpawnReasons", enabledSpawnReasons.getList());
/* ################ MobAbilities ################ */
ConfigurationSection sect = cfg.getConfigurationSection("MobAbilities");
if (sect == null)
sect = cfg.createSection("MobAbilities");
set(cfg, "MobAbilities", sect);
if (!useWorldSettings || enabledSpawnReasons.getList().size() == 0)
return;
for (String key : sect.getKeys(false))
{
ExtendedEntityType mobType = ExtendedEntityType.valueOf(key);
if (mobType == null)
{
MMComponent.getAbilities().warning(String.format("No such mob named '%s' in %s", key, AbilityConfig.ABILITY_CONFIG_NAME));
continue;
}
ConfigurationSection mobSect = sect.getConfigurationSection(key);
if (mobSect == null)
mobSect = sect.createSection(key);
mobs.put(mobType, new MobAbilityConfig(mobType, mobSect));
set(sect, key, mobSect);
}
} |
7b23153a-6232-4540-9291-4c4ecd49ca1b | 8 | public String GetPreviousLine(int pindex) {
int tindex = pindex;
while ((tindex > 0 )&& (iExpr.toCharArray()[tindex] != '\n')) {
tindex--;
}
if (iExpr.toCharArray()[tindex] == '\n') {
tindex--;
} else {
return "";
}
while ((tindex > 0) && (iExpr.toCharArray()[tindex] != '\n')) {
tindex--;
}
if (iExpr.toCharArray()[tindex] == '\n') {
tindex--;
}
String CurrentLine = "";
while (tindex < length && (iExpr.toCharArray()[tindex] != '\n')) {
CurrentLine = CurrentLine + iExpr.toCharArray()[tindex];
tindex++;
}
return CurrentLine + "\n";
} |
1e018233-904f-4168-8909-6c8381473630 | 9 | private final void method678(boolean bool, byte i) {
if (6 * anInt5537 > (((ByteBuffer) (((OpenGlToolkit) aHa_Sub2_5598)
.aClass348_Sub49_Sub1_7798))
.payload).length)
((OpenGlToolkit) aHa_Sub2_5598).aClass348_Sub49_Sub1_7798
= new FloatBuffer(6 * (anInt5537 - -100));
else
((ByteBuffer)
((OpenGlToolkit) aHa_Sub2_5598).aClass348_Sub49_Sub1_7798).position
= 0;
anInt5630++;
if (i != 27)
WA();
FloatBuffer class348_sub49_sub1
= ((OpenGlToolkit) aHa_Sub2_5598).aClass348_Sub49_Sub1_7798;
if (((OpenGlToolkit) aHa_Sub2_5598).aBoolean7775) {
for (int i_12_ = 0; i_12_ < anInt5537; i_12_++) {
class348_sub49_sub1.putShort(aShortArray5592[i_12_]);
class348_sub49_sub1.putShort(aShortArray5579[i_12_]);
class348_sub49_sub1.putShort(aShortArray5566[i_12_]);
}
} else {
for (int i_13_ = 0;
(anInt5537 ^ 0xffffffff) < (i_13_ ^ 0xffffffff); i_13_++) {
class348_sub49_sub1.method3397(122, aShortArray5592[i_13_]);
class348_sub49_sub1.method3397(67, aShortArray5579[i_13_]);
class348_sub49_sub1.method3397(31, aShortArray5566[i_13_]);
}
}
if ((((ByteBuffer) class348_sub49_sub1).position ^ 0xffffffff)
!= -1) {
if (!bool)
((Class270) aClass270_5575).anInterface8_3463
= (aHa_Sub2_5598.method3733
(5123, i + -65,
((ByteBuffer) class348_sub49_sub1).position,
((ByteBuffer) class348_sub49_sub1).payload,
false));
else {
if (anInterface8_5647 == null)
anInterface8_5647
= aHa_Sub2_5598.method3733(5123, -39,
(((ByteBuffer)
class348_sub49_sub1)
.position),
(((ByteBuffer)
class348_sub49_sub1)
.payload),
true);
else
anInterface8_5647.method35
(((ByteBuffer) class348_sub49_sub1).payload,
5123, i ^ 0x23,
((ByteBuffer) class348_sub49_sub1).position);
((Class270) aClass270_5575).anInterface8_3463
= anInterface8_5647;
}
if (!bool)
aBoolean5555 = true;
}
} |
802263a0-377b-4ab7-a25e-6ea2365ab3d0 | 1 | protected void processLoop() {
currentTime = 0f;
if(reverse) {
endingValue.negate(endingValue);
}
} |
a8ddf0d4-be32-4520-8736-e1f405a44b10 | 9 | private void binData(boolean lPerformed) {
double max;
int bin;
boolean performLaplace = false;
min = max = data.get(0);
for(double d : data)
if(d>max)max=d;
else if(d<min)min=d;
interval = (max - min)/((double)numBins - 1.);
for(double d : data)
{
bin = (int)((d - min) / interval);
if(bin > numBins - 1) bin = numBins - 1;
bins[bin]++;
}
for(int i = 0; i< bins.length; i++)
if (bins[i]==0)
if(lPerformed)
{
bins[i] = 1;
//System.out.println("Fixing the fix");
}
else performLaplace = true;
if(performLaplace)laplacianCorrection();
clean = true;
} |
5dc48015-9f7d-448e-980a-46366d20d1ee | 8 | public void putAll( Map<? extends Long, ? extends Byte> map ) {
Iterator<? extends Entry<? extends Long,? extends Byte>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Long,? extends Byte> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} |
e5edda50-181d-440d-b34b-176476a42832 | 0 | private void initPopupMenu(){
mainPopupMenu = new JPopupMenu();
ImageIcon itemCopyIcon = new ImageIcon(Main.ICO_PATH + "page_copy.png");
JMenuItem itemCopy = new JMenuItem(" Copy ", itemCopyIcon);
itemCopy.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
copyToClipboard(getSelectedText());
}
});
ImageIcon itemCutIcon = new ImageIcon(Main.ICO_PATH + "cut.png");
JMenuItem itemCut = new JMenuItem(" Cut ", itemCutIcon);
itemCut.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
cutText(getSelectedText());
}
});
ImageIcon itemPasteIcon = new ImageIcon(Main.ICO_PATH + "page_paste.png");
JMenuItem itemPaste = new JMenuItem(" Past ", itemPasteIcon);
itemPaste.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
pasteText();
}
});
mainPopupMenu.add(itemCopy);
mainPopupMenu.add(itemCut);
mainPopupMenu.add(itemPaste);
} |
e69ca936-d191-4991-ad38-493fa2b712fa | 1 | public void cmpg(final Type type) {
mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPG : Opcodes.DCMPG);
} |
d3e2f2cb-f1ca-4728-b3e6-de495225fc46 | 9 | public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Usage: java -jar sezpoz.jar [ something.jar | some.serialized.Annotation ]+");
}
for (String arg : args) {
System.out.println("--- " + arg);
byte[] magic = new byte[4];
InputStream is = new FileInputStream(arg);
try {
is.read(magic, 0, 4);
} finally {
is.close();
}
if (Arrays.equals(magic, ZIP_MAGIC)) {
JarFile jf = new JarFile(arg, false);
try {
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith(Indexer.METAINF_ANNOTATIONS)) {
String annotation = name.substring(Indexer.METAINF_ANNOTATIONS.length());
if (annotation.isEmpty() || annotation.endsWith(".txt")) {
continue;
}
System.out.println("# " + annotation);
is = jf.getInputStream(entry);
try {
is.read(magic, 0, 4);
} finally {
is.close();
}
if ((Arrays.equals(magic, SER_MAGIC))) {
is = jf.getInputStream(entry);
try {
dump(is);
} finally {
is.close();
}
} else {
System.err.println("does not look like a Java serialized file");
}
}
}
} finally {
jf.close();
}
} else if (Arrays.equals(magic, SER_MAGIC)) {
is = new FileInputStream(arg);
try {
dump(is);
} finally {
is.close();
}
} else {
System.err.println("does not look like either a JAR file or a Java serialized file");
}
}
} |
1602f7e5-07fa-4a58-adda-772436bad856 | 4 | public static synchronized void loadFromPreferences() {
if (!LOADED) {
Preferences prefs = Preferences.getInstance();
for (Command cmd : StdMenuBar.getCommands()) {
String value = prefs.getStringValue(MODULE, cmd.getCommand());
if (value != null) {
if (NONE.equals(value)) {
cmd.setAccelerator(null);
} else {
cmd.setAccelerator(KeyStroke.getKeyStroke(value));
}
}
}
LOADED = true;
}
} |
9909e33b-21fa-48c2-bb1d-eb723177a6cd | 4 | PERange intersection(PERange rangeb) {
if(rangeb == null) {
return null;
}
int s = (this.begin < rangeb.begin) ? rangeb.begin : this.begin;
int e = (this.end < rangeb.getEnd()) ? this.end : rangeb.getEnd();
return (s > e) ? null : new PERange(s, e);
} |
d01e7c1e-4929-4f5d-8249-8d3105be86a2 | 4 | public static String downloadURL(URL url) {
InputStream in = null;
try {
in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
int bytesRead = 1;
while ((bytesRead = reader.read(buffer)) > 0) {
sb.append(buffer);
}
return sb.toString();
} catch (IOException ex) {
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
0f0dbea2-6765-4d12-bba5-9e67ccf06d4c | 9 | public String toString() {
String ns = "";
Talent currentTalent = null;
ns += name + ": " + (current?"Current":"Not Current") + "\n";
ns += "\n Offense:\n";
for (int i=0;i<offense.length;i++) {
for (int j=0;j<offense[0].length;j++) {
for (Talent e : talents) {
if (e.name().equals(offense[i][j])) {
currentTalent = e;
break;
}
}
ns += " " + pad((offense[i][j].equals("")
?"":(currentTalent!=null?"[" + currentTalent.rank() + "]":"[0]"))
+ " " + offense[i][j],26);
currentTalent = null;
}
ns += "\n";
ns += pad("",5);
for (int j=0;j<offenseLinks[0].length;j++) {
ns += pad((offenseLinks[i][j]?"||":""),28);
}
ns += "\n";
}
return ns;
} |
c0c93bef-5966-49c1-a3b4-b3adabbc4843 | 4 | public final void endElement(
final String ns,
final String lName,
final String qName) throws SAXException
{
// the actual element name is either in lName or qName, depending
// on whether the parser is namespace aware
String name = lName == null || lName.length() == 0 ? qName : lName;
// Fire "end" events for all relevant rules in reverse order
Rule r = (Rule) RULES.match(match);
if (r != null) {
r.end(name);
}
// Recover the previous match expression
int slash = match.lastIndexOf('/');
if (slash >= 0) {
match = match.substring(0, slash);
} else {
match = "";
}
} |
40dfb34e-ec32-46db-bf68-5dc0367b399d | 6 | public String appendToText(String name, String journalID, String text) {
Journal temp = null;
for (Journal j : db) {
if (journalID.equals(j.getID()))
temp = j;
}
if (nurses.contains(name)) {
if (name.equals(temp.getNurse())) {
temp.changeText(text);
log.addEntry(name, temp.getID(), "User added text: " + text);
return "Text added to journal";
}
} else if (doctors.contains(name)) {
if (name.equals(temp.getDoctor())) {
temp.changeText(text);
log.addEntry(name, temp.getID(), "User added text: " + text);
return "Text added to journal";
}
}
log.addEntry(name, journalID, "User tried to add text \"" + text
+ "\" to journal without permission.");
return "Did not add text to journal. Permission denied!";
} |
b04d8660-b77d-4239-b045-7e7f307cfbd6 | 6 | private boolean inputRFCHandling(String stdInString) {
// split standard Input into tokens, token cut by " "
String tokenToFind = " ";
StringTokenizer token = new StringTokenizer(stdInString, tokenToFind);
int arraySize = token.countTokens();
String foundToken[] = new String[arraySize];
// find all tokens and save tokens into array
for (int i = 0; token.hasMoreTokens(); i++) {
foundToken[i] = token.nextToken();
// debugging
System.out.println("Token: " + i + " inhalt: " + foundToken[i]);
}
// foundToken[0] contains ftp command
// fountToken[i] contains parameters
/*
* now we remove /n (newline) into tokens
*/
String cutstring = "\n";
String replacestring = "";
String newStdInString;
for (int i = 0; i < foundToken.length; i++) {
if (foundToken[i].contains(cutstring) == true) {
foundToken[i] = foundToken[i].replace(cutstring, replacestring);
}
}
/*
* just a command was sent without parameters
*/
if (foundToken[0].contains("HELP") == true) {
msgSocket.output().println("HELP");
return true;
}
if (fservice.userSendLIST(foundToken[0]) == true) {
return true;
}
if (fservice.userSendSYST(foundToken[0]) == true) { // any failure, check it !!!
return true;
}
/*
* just a command with parameter was send
*/
int count;
// if((count = foundToken.length) > 1 ) {
// if (fservice.downloadFile(foundToken[0], foundToken[1]) == true) {
// return true;
// }
// if(fservice.changeDirectory(foundToken[0], foundToken[1]) == true) {
// return true;
// }
// if(fservice.uploadFile(foundToken[0], foundToken[1]) == true) {
// return true;
// }
// }
return false; // jump back into endless crycle
} |
4b55dfc4-54ff-4c05-97aa-46c07399033a | 8 | public void update(double dt) {
xPos+=xVel*dt;
yPos+=yVel*dt;
xVel+=xAccel*dt;
yVel+=yAccel*dt;
setAccel(dt);
Ball b=null;
for(int i=0;i<MainClass.balls.size();i++) {
b=MainClass.balls.get(i);
if(b!=null && id<b.id && collides(b)) {
bounce(b,i);
}
}
if(xPos-radius<MainClass.wallThickness/2*MainClass.scale || xPos+radius>MainClass.resolution*MainClass.xWindows/MainClass.yWindows-MainClass.wallThickness/2*MainClass.scale) {
wallBounce(false);
}
if(yPos-radius<MainClass.wallThickness/2*MainClass.scale || yPos+radius>MainClass.resolution-MainClass.wallThickness/2*MainClass.scale) {
wallBounce(true);
}
} |
9a67a601-fedb-4896-a9dd-17f4285783b3 | 1 | public String toString() {
return "FROM:" + indexFrom + (indexTo == -1 ? "" : " TO " + indexTo) + " TYPE FROM: " + moveTypeFrom + " TYPE TO: " + moveTypeTo;
} |
14496714-64bd-47b3-ab68-5efb99193bef | 1 | private void handleOpenMenuItemClick() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Xml files", "xml");
fileChooser.setFileFilter(filter);
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
this.controller.onLoadMenuItemClick(fileChooser.getSelectedFile().getAbsolutePath());
}
} |
94b48c7f-05ab-4289-85e2-b97270610a14 | 2 | private void drawEmptyGrid(Graphics g) {
g.setColor(Color.BLACK);
for (int i = 0; i <= nbRows; i++) {
for (int j = 0; j <= nbColumns; j++) {
g.drawLine(caseHeight * i, 0, caseHeight * i, nbColumns
* caseHeight + 1);
g.drawLine(0, caseWidth * j, nbRows * caseWidth + 1,
caseWidth * j);
}
}
} |
9b9f6d5e-b59a-4d14-9e3a-f8c00f69e0c8 | 2 | public static boolean check_repeat_symbol(Symbol_table symbol_table, String name) {
for (int i = 0; i < symbol_table.symbol_name.size(); i++) {
if (symbol_table.symbol_name.get(i).toString().equals(name)) {
return false;
}
}
return true;
} |
6e83cfc2-60de-4e3f-96ed-448b23d4608c | 4 | private void nextPiece() {
if(current == null){
this.current = Tetromino.generatePiece();
this.next = Tetromino.generatePiece();
} else {
this.current = this.next;
this.next = Tetromino.generatePiece();
}
side.updateNext(next);
orientation = 0;
currentCol = current.getTiles()[0].length == 16 ? 2 : 3;
currentCol = current.getTiles()[0].length == 4 ? 4 : currentCol;
currentRow = 0;
boolean isOver = screen.addPiece(current, currentCol, currentRow, orientation);
if(!isOver){
gameOver = true;
}
} |
d2adba32-d0ab-48cf-ae91-a2b159ff6c18 | 4 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
int nEdges = Integer.parseInt(in.readLine().trim());
start = 1;
target = 2;
HashMap<String, Integer> mapNames = new HashMap<String, Integer>();
mapNames.put("A", start);
mapNames.put("Z", target);
ArrayList<String[]> edges = new ArrayList<String[]>(nEdges);
int idEdge = 3;
for (int i = 0; i < nEdges; i++) {
String[] e = in.readLine().trim().split(" ");
if(!mapNames.containsKey(e[0]))
mapNames.put(e[0], idEdge++);
if(!mapNames.containsKey(e[1]))
mapNames.put(e[1], idEdge++);
edges.add(e);
}
Dinic G = new Dinic(1+mapNames.size());
G.addEdge(start, 1, Integer.MAX_VALUE/2);
for (String[] e : edges){
int u = mapNames.get(e[0]);
int v = mapNames.get(e[1]);
int c = Integer.parseInt(e[2]);
G.addEdge(u, v, c);
}
int maxFlow = G.maxFlow(start, target);
out.append(maxFlow+"\n");
System.out.print(out);
} |
d692eda3-7416-4ad2-b322-b06923c1edb2 | 4 | private boolean Rule_0()
{
begin("");
if (!Name()) return rejectInner();
if (!EQUAL()) return rejectInner();
if (!RuleRhs()) return rejectInner();
DiagName();
if (!SEMI()) return rejectInner();
return acceptInner();
} |
2972f7a0-988e-4222-8665-2001f7d9bd63 | 3 | public static int[] sort(int[] list) {
if (list.length == 1) {
return list;
} else {
int[] listL = new int[list.length / 2];
int[] listR = new int[list.length - list.length / 2];
int Center = list.length / 2;
for (int i = 0; i < Center; i++) {
listL[i] = list[i];
}
for (int i = Center, j = 0; i < list.length; i++, j++) {
listR[j] = list[i];
}
int[] sortedListL = sort(listL);
int[] sortedListR = sort(listR);
int[] result = mergeTwoList(sortedListL, sortedListR);
return result;
}
} |
9401f9b9-8f5f-4522-842b-01b36ef3268e | 3 | public void writeOrFail(String fileName) throws IOException
{
String extension = this.extension; // the default is current
// create the file object
File file = new File(fileName);
File fileLoc = file.getParentFile(); // directory name
// if there is no parent directory use the current media dir
if (fileLoc == null)
{
fileName = FileChooser.getMediaPath(fileName);
file = new File(fileName);
fileLoc = file.getParentFile();
}
// check that you can write to the directory
if (!fileLoc.canWrite()) {
throw new IOException(fileName +
" could not be opened. Check to see if you can write to the directory.");
}
// get the extension
int posDot = fileName.indexOf('.');
if (posDot >= 0)
extension = fileName.substring(posDot + 1);
// write the contents of the buffered image to the file
ImageIO.write(bufferedImage, extension, file);
} |
fe572dd8-8cf7-4450-8671-c735d6594b88 | 4 | public List<String> getStringList(String path, List<String> def) {
if(def == null)
def = new ArrayList<String>();
List<?> list = super.getList(path, def);
if(list == null)
return def;
try {
@SuppressWarnings("unchecked")
List<String> sList = (List<String>) list;
return sList;
} catch (Exception e) {
e.printStackTrace();
}
return def;
} |
c6b51c78-39ba-4864-8bf5-0317bd6c4fca | 4 | @Override
public List<Object> getAll(String type){
try {
db.start();
DBCollection collection = db.getDB().getCollection("nonmoves");
XStream xStream = new XStream();
DBCursor cursor = collection.find();
if (cursor == null)
return null;
List<Object> commands = new ArrayList<Object>();
while(cursor.hasNext()) {
DBObject obj = cursor.next();
String xml = (String)obj.get(type);
if (xml != null)
commands.add((Object) xStream.fromXML(xml));
}
db.stop(true);
return commands;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
} |
9140868e-f9bd-48ea-b7a6-0ed7c8c6d453 | 2 | protected void cut(Fibonaccinode x, Fibonaccinode y) {
x.left.right = x.right;
x.right.left = x.left;
y.degree--;
if (y.child == x) {
y.child = x.right;
}
if (y.degree == 0) {
y.child = null;
}
x.left = min;
x.right = min.right;
min.right = x;
x.right.left = x;
x.parent = null;
x.mark = false;
} |
23716404-4678-4966-a7f8-ee8250cd84e9 | 4 | @Override
public void onAudioSamples(IAudioSamplesEvent event) {
if (currentSection != null) {
Long timeStamp = event.getTimeStamp(currentSection.getTimeUnit());
if (currentSection.getStart() < timeStamp) {
adjustVolume(event);
if (currentSection.getEnd() < timeStamp) {
// Next video section
if (++sectionIterator < randomSections.size())
{
currentSection = randomSections.get(
sectionIterator);
}
else
{
currentSection = null;
}
}
}
}
super.onAudioSamples(event);
} |
322e1b3a-c87b-4eda-b7bd-f054abc42105 | 4 | public RPCMessageImpl(AuthNodeId authNodeId, Authenticator authenticator, RPC rpc)
{
if (authNodeId == null)
throw new NullPointerException("The authNodeId is null!");
if (authenticator == null)
throw new NullPointerException("The authenticator is null!");
if (rpc == null)
throw new NullPointerException("The rpc is null!");
this.authNodeId = authNodeId;
this.authenticator = authenticator;
this.rpc = rpc;
RPC.OpCode rpcOpcode = rpc.getRPCOpCode();
if (rpcOpcode.isRequest())
this.opcode = DHTMessage.OpCode.RPC_REQ;
else
this.opcode = DHTMessage.OpCode.RPC_RES;
} |
ea629c4b-940b-4d2a-9fd3-5df066c5a6e0 | 7 | public InputSplit[] getSplits(JobConf jobConf, int numSplits) throws IOException {
// Get the splitsize (number of rows), defaults to 100,000 as much larger seems to
// screw up getting accurate rows
int splitSize = Integer.parseInt(jobConf.get(SimpleDBInputFormat.SIMPLEDB_SPLIT_SIZE, String.valueOf(MAX_SPLIT_SIZE)));
if (splitSize > MAX_SPLIT_SIZE) {
splitSize = MAX_SPLIT_SIZE;
}
// Get total number of rows to calculate number of splits required
SimpleDBDAO sdb = new SimpleDBDAO(jobConf);
long totalItems;
if (sdb.getWhereQuery() != null) {
totalItems = sdb.getCount();
} else {
totalItems = sdb.getTotalItemCount();
}
long totalSplits = 1;
if (splitSize < totalItems) {
totalSplits = totalItems / splitSize;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Total Rows:" + String.valueOf(totalItems));
LOG.debug("Total Splits:" + String.valueOf(totalSplits));
}
// Array to hold splits
ArrayList<SimpleDBInputSplit> splits = new ArrayList<SimpleDBInputSplit>();
// Create Splits
for (int i = 0; i < totalSplits; i++) {
String splitToken = sdb.getSplitToken(i, splitSize);
long startRow = i * splitSize;
long endRow = startRow + splitSize;
if (endRow > totalItems) {
endRow = totalItems;
}
SimpleDBInputSplit split = new SimpleDBInputSplit(startRow, endRow, splitToken);
splits.add(split);
if (LOG.isDebugEnabled()) {
LOG.debug("Created Split: " + split.toString());
}
}
// Return array of splits
return splits.toArray(new SimpleDBInputSplit[splits.size()]);
} |
294df646-a5f7-4417-9d7c-07e5db839730 | 8 | @Override
public void run() {
if (stopped || this.tokens.length == 0)
return;
System.out.println("executing search");
try {
this.cmd = getCmd(getLongest(tokens));
String line;
String file;
int n = 0;
String[] dbentry;
p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = input.readLine()) != null) {
if (stopped) {
System.out.println("I noticed I was stopped");
break;
}
dbentry = line.split("\t");
if (dbentry.length <= ResultListModel.DB_ENTRYNR_FILE) {
System.err.println("weird db entry " + dbentry.length
+ ": " + line);
} else {
file = dbentry[ResultListModel.DB_ENTRYNR_FILE];
if (isMatch(file, tokens)) {
this.model.add(dbentry);
}
n++;
}
}
System.out.println("handled " + n + " entries.");
input.close();
input = new BufferedReader(
new InputStreamReader(p.getErrorStream()));
while ((line = input.readLine()) != null) {
System.err.println(line);
}
input.close();
this.model.refreshDisplay(-1);
} catch (Exception err) {
err.printStackTrace();
}
System.out.println("search done");
} |
da9108f1-3681-455b-96e6-7977204a1534 | 2 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((adjacentNodes == null) ? 0 : adjacentNodes.hashCode());
result = prime * result + ((edgeState == null) ? 0 : edgeState.hashCode());
return result;
} |
954b3cdb-cbbe-4cdc-bb0b-90aa22d27a1d | 8 | public void onTurn(Board board) {
if (board.getMovablePos().isEmpty()) {
System.out.println("pass your turn");
board.pass();
return;
}
while(true) {
System.out.print("input point ex.\"f5\" or (u:undo/x:exit):");
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
try {
String line = stdin.readLine();
switch (line) {
case "u":
System.out.println("undo processing...");
board.undo();
return;
case "x":
System.out.println("exiting...");
System.exit(0);
break;
default:
try {
byte[] asc = line.getBytes("US-ASCII");
int x = asc[0] - "a".getBytes("US-ASCII")[0] + 1;
int y = Integer.parseInt(line.substring(1,2));
int color = board.getCurrentColor();
Disc disc = new Disc(x, y, color);
System.out.println("" + disc.x + "," + disc.y + ":" + color);
if (!board.put(disc.getPos(), color)) {
System.out.println("cannot put there");
}
if (Debug.state) { printPattern(board); }
return;
} catch (Exception e) {
e.printStackTrace();
System.out.println("invalid input");
}
break;
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
} |
b00e95cd-f2d3-4e50-b4c1-e82dfe8409aa | 3 | public void initKeyListeners() {
KeyListener deleteListener;
deckTable.addKeyListener(deleteListener = new KeyListener() {
public void keyPressed(KeyEvent k) {
if (k.getComponent() instanceof JList) {
switch (k.getKeyCode()) {
case KeyEvent.VK_DELETE: removeCardsInImageListBuffer();
break;
}
}
else {
switch (k.getKeyCode()) {
case KeyEvent.VK_DELETE: removeCardsInBuffer();
break;
}
}
}
public void keyTyped(KeyEvent k) {
}
public void keyReleased(KeyEvent k) {
}
});
imageList.getList().addKeyListener(deleteListener);
} |
493110bf-6ea3-42a6-bf02-2c7c419547a6 | 4 | public APacket getNewPacketOfID(int id) {
try {
return PList.get(id).getConstructor().newInstance();
} catch(InstantiationException e) {
e.printStackTrace();
//Log.getInstance().logError("PacketRegistrie", "Could not Instantiate " + PList.get(id) + " probably missing public default Constructor");
throw new RuntimeException("Instantiation Exception while Instantiating " + PList.get(id));
} catch(IllegalAccessException e) {
e.printStackTrace();
//Log.getInstance().logError("PacketRegistrie", "Could not Instantiate " + PList.get(id) + " probably missing public default Constructor");
throw new RuntimeException("IllegalAccess Exception while Instantiating " + PList.get(id));
} catch(NoSuchMethodException e) {
e.printStackTrace();
throw new RuntimeException("NoSuchMethodException while Instantiating " + PList.get(id));
} catch(InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException("InvocationTargetException while Instantiating " + PList.get(id));
}
} |
374e8be8-f2d0-43ee-aab5-3c7bb65aac74 | 2 | @Override
public int compareTo(CubeNode b) {
if (this.heuristic < b.heuristic) {
return -1;
} else if (this.heuristic > b.heuristic) {
return 1;
}
return 0;
} |
0a95a3e5-b21f-4f30-9cbe-7651ab1f95bd | 3 | public void logShip (String mmsi) {
UserIdentifier uid=new UserIdentifier();
// First check if a ship has already been logged and is in the list
int a;
for (a=0;a<listLoggedShips.size();a++) {
if (listLoggedShips.get(a).getMmsi().equals(mmsi)) {
// Increment the log count and return
listLoggedShips.get(a).incrementLogCount();
return;
}
}
// Now check if the ship is in ships.xml
Ship loggedShip=uid.getShipDetails(mmsi);
// If null then we need to create a ship object
if (loggedShip==null) {
Ship newShip=new Ship();
newShip.setMmsi(mmsi);
newShip.incrementLogCount();
listLoggedShips.add(newShip);
}
else {
// Increment the ship objects log counter and add it to the list
loggedShip.incrementLogCount();
listLoggedShips.add(loggedShip);
}
} |
e8a4d9a9-354c-45c3-a9c0-f40c832d164a | 2 | public void zeichneKartenAusschnitt(Graphics g){
//fenster.ofView
int ausschnitt_x = fenster.ofView.x;
int ausschnitt_y = fenster.ofView.y;
int ausschnitt_ende_x = ausschnitt_x+20,ausschnitt_ende_y = ausschnitt_y+20;
for(int x = ausschnitt_x, rx =0;x < ausschnitt_ende_x;x++,rx++){ /*level.karte.getWidth()*/ /*ausschnitt_x; x < ausschnitt_x + 320*/
for(int y = ausschnitt_y, ry =0;y < ausschnitt_ende_x;y++,ry++){ /*level.karte.getHeight() */ /*ausschnitt_y; y < ausschnitt_y + 320*/
int id = level.getID(x,y);
BufferedImage pic = tileset.tiles.get(id).getImage();
g.drawImage(pic,rx*32,ry*32,null );
//System.out.println("tileID: "+ level.getID(x, y));
//System.out.println("x,y: "+ x +", "+ y);
//System.out.println("ausschnitt_x,y: "+ ausschnitt_x +", "+ ausschnitt_y);
}
}
} |
46058941-87fb-4969-a1f4-347838b3b191 | 5 | public ArrayList<FullLocation> list(String locationName) throws URISyntaxException{
log.trace("Retrieving location list");
JsonObject response = null;
JsonElement locationsAsJson = null;
JsonElement cityAsJson = null;
JsonElement metroAreaAsJson = null;
FullLocation fullLocation = null;
ArrayList<FullLocation> locations = new ArrayList<FullLocation>();
if(currentLocation == null || !currentLocation.equals(locationName)){
currentLocation = locationName;
setPage(1);
}
search(locationName);
if(!checkResponse()){
locations = null;
}
//da : http://www.songkick.com/developer/location-search
response = getJsonResponse();
locationsAsJson = response.getAsJsonObject("resultsPage").getAsJsonObject("results").getAsJsonArray("location");
if(response.getAsJsonObject("resultsPage").get("totalEntries").getAsInt() > response.getAsJsonObject("resultsPage").get("perPage").getAsInt())
setPages(response.getAsJsonObject("resultsPage").get("totalEntries").getAsInt() / response.getAsJsonObject("resultsPage").get("perPage").getAsInt());
else
setPages(1);
JsonArray locationsArray = locationsAsJson.getAsJsonArray();
for(JsonElement location : locationsArray){
metroAreaAsJson = location.getAsJsonObject().getAsJsonObject("metroArea");
cityAsJson = location.getAsJsonObject().getAsJsonObject("city");
fullLocation = new FullLocation(Extractor.extractMetroArea(metroAreaAsJson),
Extractor.extractCity(cityAsJson));
locations.add(fullLocation);
}
clearQuery();
log.trace("Succesfully retrieved locations");
return locations;
} |
5b24c313-fcdb-4022-8599-91b399d2f52b | 3 | public void valueChanged(ListSelectionEvent e) {
resetCardBuffer();
if (!e.getValueIsAdjusting()) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for (int i = minIndex; i <= maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
cardBuffer.add(i);
}
}
}
} |
f8dca0e3-7d1d-4d74-b3dd-41fc18534846 | 7 | public void killOpen(ArrayList<Enemy> e, Rachel r){
if(getXScreen() > 0 && r.getXScreen() > 0){
for(int i = 0; i < e.size(); i++){
Enemy en = e.get(i);
if(en.getXScreen() > 0 && en.getYScreen() > 0){
if(en.isDead()){
killed++;
}//en.isdead
}//en.getxscreen
}//for loop
if(killed >= cnum){
opener++;
}
}
} |
c0eb0d26-8ae5-43f5-af09-3db0406588fb | 7 | public void senseLeverDown() throws LeverErrorException {
if((l.getLeverPosition()).equals("OFF")) {
System.out.println("ERROR: leverPosition already at OFF.");
throw new LeverErrorException();
}
else if((l.getLeverPosition()).equals("INT")) {
l.setLeverPosition("OFF");
w.setWiperSpeed(0);
}
else if((l.getLeverPosition()).equals("LOW")) {
l.setLeverPosition("INT");
switch(d.getDialPosition()) {
case 1: {
w.setWiperSpeed(4);
break;
}
case 2: {
w.setWiperSpeed(6);
break;
}
case 3: {
w.setWiperSpeed(12);
break;
}
}
}
else if((l.getLeverPosition()).equals("HIGH")) {
l.setLeverPosition("LOW");
w.setWiperSpeed(30);
}
} |
c2105409-d98a-4de0-baf9-bb75f4031563 | 4 | protected void wireLayers(List<? extends Neuron> inputs, List<? extends Neuron> outputs) {
double weight = 1d / outputs.size();
for (Neuron input : inputs) {
for (Neuron output : outputs) {
output.setInputWeight(input, weight);
}
}
} |
5cd5809c-cbf9-4aa0-ad69-0c6f79fe8891 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AgendaPrincGrafica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AgendaPrincGrafica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AgendaPrincGrafica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AgendaPrincGrafica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new AgendaPrincGrafica().setVisible(true);
}
});
} |
822f5598-dbef-41c9-b6f0-673d97bb2379 | 8 | private void createAnswerArea(Attributes attrs) {
answerArea = new AnswerArea(answerAreaDef);
// loop through all attributes, setting appropriate values
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getQName(i).equals("id"))
answerArea.setId(Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("x"))
answerArea.getStartPoint().setX(
Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("y"))
answerArea.getStartPoint().setY(
Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("width"))
answerArea.setWidth(Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("height"))
answerArea.setHeight(Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("starttime"))
answerArea.setStartTime(Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("endtime"))
answerArea.setEndTime(Integer.valueOf(attrs.getValue(i)));
}
} |
f5df8562-cc8d-4231-b538-7d9f195401b0 | 3 | public void printDefinitons() {
for (String key:definitions.keySet()) {
System.out.println(key+":");
for (Vector<PatternComponent> list:definitions.get(key)) {
for (int i = 0; i < list.size(); i++) {
System.out.println("\t"+list.get(i));
}
}
}
} |
67ae9d92-851b-4800-be15-e10b901e18a6 | 9 | public void turnAndMove(double distance, double radians) {
if (distance == 0) {
turnBody(radians);
return;
}
// Save current max. velocity and max. turn rate so they can be restored
final double savedMaxVelocity = commands.getMaxVelocity();
final double savedMaxTurnRate = commands.getMaxTurnRate();
final double absDegrees = Math.abs(Math.toDegrees(radians));
final double absDistance = Math.abs(distance);
// -- Calculate max. velocity for moving perfect in a circle --
// maxTurnRate = 10 * 0.75 * abs(velocity) (Robocode rule), and
// maxTurnRate = velocity * degrees / distance (curve turn rate)
//
// Hence, max. velocity = 10 / (degrees / distance + 0.75)
final double maxVelocity = Math.min(Rules.MAX_VELOCITY, 10 / (absDegrees / absDistance + 0.75));
// -- Calculate number of turns for acceleration + deceleration --
double accDist = 0; // accumulated distance during acceleration
double decDist = 0; // accumulated distance during deceleration
int turns = 0; // number of turns to it will take to move the distance
// Calculate the amount of turn it will take to accelerate + decelerate
// up to the max. velocity, but stop if the distance for used for
// acceleration + deceleration gets bigger than the total distance to move
for (int t = 1; t < maxVelocity; t++) {
// Add the current velocity to the acceleration distance
accDist += t;
// Every 2nd time we add the deceleration distance needed to
// get to a velocity of 0
if (t > 2 && (t % 2) > 0) {
decDist += t - 2;
}
// Stop if the acceleration + deceleration > total distance to move
if ((accDist + decDist) >= absDistance) {
break;
}
// Increment turn for acceleration
turns++;
// Every 2nd time we increment time for deceleration
if (t > 2 && (t % 2) > 0) {
turns++;
}
}
// Add number of turns for the remaining distance at max velocity
if ((accDist + decDist) < absDistance) {
turns += (int) ((absDistance - accDist - decDist) / maxVelocity + 1);
}
// -- Move and turn in a curve --
// Set the calculated max. velocity
commands.setMaxVelocity(maxVelocity);
// Set the robot to move the specified distance
setMoveImpl(distance);
// Set the robot to turn its body to the specified amount of radians
setTurnBodyImpl(radians);
// Loop thru the number of turns it will take to move the distance and adjust
// the max. turn rate so it fit the current velocity of the robot
for (int t = turns; t >= 0; t--) {
commands.setMaxTurnRate(getVelocity() * radians / absDistance);
execute(); // Perform next turn
}
// Restore the saved max. velocity and max. turn rate
commands.setMaxVelocity(savedMaxVelocity);
commands.setMaxTurnRate(savedMaxTurnRate);
} |
87604e2d-9801-4d3f-8684-8d1ec8224ce8 | 7 | public float parseFloat() throws IOException {
int sign = 1;
int c = nextNonWhitespace();
if( c == '+' ) {
// Unclear if whitespace is allowed here or not
c = read();
} else if( c == '-' ) {
sign = -1;
// Unclear if whitespace is allowed here or not
c = read();
}
if( c == '0' ) {
int d = read();
if( d == 'x' || d == 'X' ) {
int val = (int)parseIntString(16, "hexidecimal");
return Float.intBitsToFloat(val) * sign;
} else if( d == 'b' || d == 'B' ) {
return Float.intBitsToFloat((int)parseIntString(1, "binary")) * sign;
} else {
pushBack(d);
}
}
// If we got here then we didn't use the original character
// we read at the top of the method... or the one we read to
// replace it
pushBack(c);
// Else read the number while we have digits
float result = (float)(parseFloatString() * sign);
return result;
} |
683fdcae-40d0-48f4-b9b9-0e095e51726b | 6 | public void fusion(){
if(!this.isRacine()){
int index = this.pere.getPointeur().indexOf(this);
Noeud<T> brother;
if(index>0){
brother = this.pere.getPointeur().get(index-1);
if(!this.feuille){
Noeud<T> childOfBrother = brother.getPointeur().get(brother.getPointeur().size()-1);
brother.getValeur().add(childOfBrother.getValeur().get(childOfBrother.getValeur().size()-1));
this.copierPointeurDansNoeud(brother, 0, this.pointeur.size());
}else{
this.copierPointeurFichierDansNoeud(brother, 0, this.getPointeurFichier().size());
}
this.copierValeurDansNoeud(brother, 0, this.getValeur().size());
pere.getValeur().remove(index-1);
}else{
brother = this.pere.getPointeur().get(index+1);
if(!this.feuille){
this.valeur.add(this.pointeur.get(this.pointeur.size()-1).getValeur().get(this.pointeur.get(this.pointeur.size()-1).getValeur().size()-1));
this.copierPointeurDansNoeud(brother, 0, this.pointeur.size(), 0);
}else{
this.copierPointeurFichierDansNoeud(brother, 0, this.getPointeurFichier().size());
}
this.copierValeurDansNoeud(brother, 0, this.getValeur().size(), 0);
pere.getValeur().remove(index);
}
brother.mettreAJourTauxDeRemplissage();
this.pere.getPointeur().remove(index);
pere.mettreAJourTauxDeRemplissage();
brother.checkSplit();
if(pere.isRacine()){
if(pere.getValeur().size() == 0){
arbre.setRacine(brother);
brother.setRacine(true);
brother.setPere(null);
}
}else{
pere.checkFusion();
}
}
} |
db3019e4-f495-4da9-ae7a-a8b1f98c031e | 6 | public static boolean compareHydrated(String ion, int ii){
boolean test = false;
if(ion.equals(IonicRadii.hydratedIons1[ii])||ion.equals(IonicRadii.hydratedIons2[ii])||ion.equals(IonicRadii.hydratedIons3[ii])||ion.equals(IonicRadii.hydratedIons4[ii])||ion.equals(IonicRadii.hydratedIons5[ii])||ion.equals(IonicRadii.hydratedIons6[ii])){
test = true;
}
return test;
} |
8460d7f8-9782-4573-8d4e-1fbc44c80d13 | 4 | String toString(Object o) {
String message = "Could not serialize to json, reason = ";
try {
return gson.toJson(o);
} catch (Exception e) {
message += e.getMessage() + ".";
} catch (StackOverflowError e) {
message += e.getMessage() + ".";
}
try {
String toStringResult = String.valueOf(o);
message += " String.valueOf(result) = ";
return message + toStringResult;
} catch (Exception e) {
message += " String.valueOf(result) also failed, reason = " + e.getMessage() + ".";
} catch (StackOverflowError e) {
message += " String.valueOf(result) also failed, reason = " + e.getMessage() + ".";
}
return message;
} |
c8a70d8e-3265-4d91-b62f-5438725b77d8 | 4 | public InvestManagerDto getInvestManagerDto(String mgrName){
PreparedStatement stmt = null;
ResultSet rs = null;
InvestManagerDto investManagerDto = null;
try {
stmt = conn
.prepareStatement("select mgrName,mgrInfo from InvestManager where mgrName = ? ");
stmt.setString(1, mgrName);
rs = stmt.executeQuery();
String name = "";
String info="";
if(rs.next()) {
investManagerDto=new InvestManagerDto();
name = rs.getString(1);
info = rs.getString(2);
investManagerDto.setName(name);
investManagerDto.setInfo(info);
}
if (stmt != null)
stmt.close();
if (rs != null)
rs.close();
} catch (Exception e) {
// TODO: handle exception
logger.debug(e.getMessage());
}
return investManagerDto;
} |
4664459c-64d0-4d3a-9cf6-63f4a6be62fa | 6 | public static void printKifWrapper(LiteralWrapper self) {
{ OutputStream stream = ((OutputStream)(Logic.$PRINTLOGICALFORMSTREAM$.get()));
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfIntegerP(testValue000)) {
{ IntegerWrapper self000 = ((IntegerWrapper)(self));
stream.nativeStream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfLongIntegerP(testValue000)) {
{ LongIntegerWrapper self000 = ((LongIntegerWrapper)(self));
stream.nativeStream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfFloatP(testValue000)) {
{ FloatWrapper self000 = ((FloatWrapper)(self));
stream.nativeStream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfBooleanP(testValue000)) {
{ BooleanWrapper self000 = ((BooleanWrapper)(self));
stream.nativeStream.print(self000.wrapperValue);
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper self000 = ((StringWrapper)(self));
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
stream.nativeStream.print(self000);
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
}
}
else if (Surrogate.subtypeOfCharacterP(testValue000)) {
{ CharacterWrapper self000 = ((CharacterWrapper)(self));
{ Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
stream.nativeStream.print(self000);
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001);
}
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
} |
1b3826e6-3f70-46fd-8886-4d072213f6cb | 1 | public static void main(String[] args) {
Thread t = new Thread(new LiftOff());
// t.start();
System.out.println("Waiting for LiftOff");
for(int i = 0; i < 5; i++)
new Thread(new LiftOff()).start();
} |
1bac45a2-ccf6-4d1d-b950-b1da09b1022a | 3 | public void addItem(int type){
for(int i = 0; i < invCount; i++){
if(inv[i].type == 0){
inv[i].type = type;
if(invCount < inv.length)invCount++;
break;
}
}
} |
93592fc2-299a-4f02-8b77-f6e13d1d882b | 4 | public double rawPersonVariance(int index){
if(!this.dataPreprocessed)this.preprocessData();
if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive");
if(!this.variancesCalculated)this.meansAndVariances();
return this.rawPersonVariances[index-1];
} |
ebdcd21c-e890-4823-a9c2-abc27d44c337 | 2 | public static DirectionEnum fromValue(String v) {
for (DirectionEnum c: DirectionEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
} |
675f96d0-c4e8-4372-8864-b8116929b564 | 6 | private void quicksort(Comparable[] items, int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
Comparable pivot = items[low + (high - low) / 2];
// Divide into two lists
while (i <= j) {
while (items[i].compareTo(pivot) < 0) {
i++;
}
while (items[j].compareTo(pivot) > 0) {
j--;
}
if (i <= j) {
exchange(items, i, j);
i++;
j--;
}
}
// Recursion
if (low < j) {
quicksort(items, low, j);
}
if (i < high) {
quicksort(items, i, high);
}
} |
4ea2f702-e011-489a-b21b-0d151b91499c | 0 | public TreeSelectionListener[] getTreeSelectionListeners() {
return (TreeSelectionListener[]) treeSelectionListeners.toArray();
} |
64ca7f0a-5653-446c-ba7d-ec022a2dd578 | 4 | public AssociationList getAssociationList(int aiMaxSize, String asLastModified,
String asDeactivated) {
String lsParam = "";
if (aiMaxSize > 0) {
lsParam += "&max_size=" + Integer.toString(aiMaxSize);
}
if (UtilityMethods.isValidString(asLastModified)) {
lsParam += "&last_modified=" + asLastModified;
}
if (UtilityMethods.isValidString(asDeactivated)) {
lsParam += "&deactivated=" + asDeactivated;
}
if (UtilityMethods.isValidString(lsParam)) {
lsParam = lsParam.replaceFirst("&", "?");
}
return get(AssociationList.class, REST_URL_ASSOCIATIONS + lsParam);
} |
5998f8b9-f803-4ac8-adbb-e2068dbd6a9d | 6 | public void scanVariable() {
final char first = ch;
if (ch != '@' && ch != ':') {
throw new ELException("illegal variable");
}
int hash = first;
np = bp;
sp = 1;
char ch;
if (buf[bp + 1] == '@') {
hash = 31 * hash + '@';
bp++;
sp++;
}
for (;;) {
ch = buf[++bp];
if (!isIdentifierChar(ch)) {
break;
}
hash = 31 * hash + ch;
sp++;
continue;
}
this.ch = buf[bp];
stringVal = symbolTable.addSymbol(buf, np, sp, hash);
TinyELToken tok = keywods.getKeyword(stringVal);
if (tok != null) {
token = tok;
} else {
token = TinyELToken.IDENTIFIER;
}
} |
79eb38f4-6a71-4c71-95aa-d5410dfe1c1e | 0 | @Override
public void method2() {
System.out.println("ClassA method2()");
} |
4f8b59a6-a1b7-4c18-88b8-2930f1be1d21 | 8 | @Override
public String toString()
{
switch(this)
{
case DayPref:
return "Day Pref";
case MON:
return "Monday";
case TUES:
return "Tuesday";
case WED:
return "Wednesday";
case THUR:
return "Thursday";
case FRI:
return "Friday";
case SAT:
return "Saturday";
case NOPREF:
return "No Preference";
default:
return "Day Pref";
}
} |
47eba379-78a6-4966-8451-daff7b4257ca | 6 | public final Clip loadAudioClip(URL clipName) {
Clip loadedClip = null;
try {
// Open an input stream to the specified clip and retrieve clip format information
AudioInputStream inputStream = AudioSystem.getAudioInputStream(clipName);
AudioFormat format = inputStream.getFormat();
// Convert ULAW/ALAW compressed clip formats to (uncompressed) PCM format
// This is to prevent any problems with a lack of support for ULAW/ALAQ within
// the AudioSystem
if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
|| (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
AudioFormat pcmFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
format.getSampleSizeInBits() * 2, format.getChannels(),
format.getFrameSize() * 2, format.getFrameRate(), true);
inputStream = AudioSystem.getAudioInputStream(pcmFormat, inputStream);
format = pcmFormat;
}
// Check to see if the specified audio format is supported
DataLine.Info clipInfo = new DataLine.Info(Clip.class, format);
if (AudioSystem.isLineSupported(clipInfo) == false)
throw new IllegalArgumentException(
"AssetLoader.loadAudioClip: Clip format for "
+ clipName + " is not supported.");
// Load the specified audio stream into the Clip instance
loadedClip = (Clip) AudioSystem.getLine( clipInfo );
loadedClip.open(inputStream);
inputStream.close();
// Ensure the playback position is set to the start of the clip
loadedClip.setFramePosition(0);
} catch (UnsupportedAudioFileException exception) {
throw new IllegalArgumentException("AssetLoader.loadAudioClip: " +
"Unsupported audio file exception generated for " + clipName);
} catch (LineUnavailableException exception) {
throw new IllegalArgumentException("AssetLoader.loadAudioClip: " +
"Unsupported audio file exception generated for " + clipName);
} catch (IOException exception) {
throw new IllegalArgumentException("AssetLoader.loadAudioClip: " +
"Could not read from " + clipName);
}
return loadedClip;
} |
398e5d04-f27c-4e02-8eb8-6e0c5fb2acc8 | 6 | private void unpackData() {
File tmp = new File(backup);
if(!tmp.exists()) {
error("It seems you don't have a '" + backup + "' yet. Stopping.");
return;
}
try {
BufferedInputStream input = new BufferedInputStream(new FileInputStream(tmp));
new File(filePrefix).mkdirs();
new File(filePrefix).delete();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filePrefix));
byte header[] = new byte[24];
Util.readBlocking(header, input);
// System.out.println("Read header 24 bytes once");
TarExtractor tar = new TarExtractor(new InflaterStream(input));
TarHeader theader = null;
while((theader = tar.readNextFileHeader()) != null) {
byte[] content = tar.readNextFile();
System.out.println("Found file " +
theader.getFileName());
if(theader.getFileName().endsWith(file)) {
System.out.println("Found file " +
theader.getFileName());
out.close();
new File(fileHeader).mkdirs();
new File(fileHeader).delete();
out = new BufferedOutputStream(new FileOutputStream(fileHeader));
out.write(header); // As good a place as anywhere else
out.write(theader.getBytes());
out.close();
new File(fileSave).mkdirs();
new File(fileSave).delete();
out = new BufferedOutputStream(new FileOutputStream(fileSave));
out.write(content);
out.close();
new File(filePostfix).mkdirs();
new File(filePostfix).delete();
out = new BufferedOutputStream(new FileOutputStream(filePostfix));
continue;
}
// System.out.println("Skipping file " + theader.getFileName());
out.write(theader.getBytes());
if(content.length > 0) {
out.write(content);
if(content.length % 512 != 0) {
out.write(new byte[512 - content.length % 512]);
}
}
}
out.close();
input.close();
} catch(Exception e) {
error("It seems something went wrong: " + e.getMessage());
e.printStackTrace();
return;
}
info("Your file '" + fileSave + "' is now ready.");
} |
4a3bc300-c93d-4ee5-a35e-01d81161921b | 5 | @Override
public boolean checkTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException {
try {
//Connection connection = getConnection();
this.connection = this.getConnection();
Statement statement = this.connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM " + table);
if (result == null)
return false;
if (result != null)
return true;
} catch (SQLException e) {
if (e.getMessage().contains("exist")) {
return false;
} else {
this.writeError("Error in SQL query: " + e.getMessage(), false);
e.printStackTrace();
}
}
if (query("SELECT * FROM " + table) == null) return true;
return false;
} |
298b18f6-6960-4975-8d32-720f7deca371 | 4 | public BaseArtifactType newArtifactInstance() {
try {
BaseArtifactType baseArtifactType = getArtifactType().getTypeClass().newInstance();
baseArtifactType.setArtifactType(getArtifactType().getApiType());
if (DocumentArtifactType.class.isAssignableFrom(baseArtifactType.getClass())) {
((DocumentArtifactType) baseArtifactType).setContentType(getMimeType());
}
if (getArtifactType() == ArtifactTypeEnum.ExtendedArtifactType) {
baseArtifactType.getOtherAttributes().put(SrampConstants.SRAMP_CONTENT_TYPE_QNAME, getMimeType());
((ExtendedArtifactType) baseArtifactType).setExtendedType(getExtendedType());
}
if (getArtifactType() == ArtifactTypeEnum.ExtendedDocument) {
baseArtifactType.getOtherAttributes().put(SrampConstants.SRAMP_CONTENT_TYPE_QNAME, getMimeType());
((ExtendedDocument) baseArtifactType).setExtendedType(getExtendedType());
}
return baseArtifactType;
} catch (Exception e) {
// throw new RuntimeException(Messages.i18n.format("ARTIFACT_INSTANTIATION_ERROR", getArtifactType().getTypeClass()), e); //$NON-NLS-1$
throw new RuntimeException("ARTIFACT_INSTANTIATION_ERROR", e); //$NON-NLS-1$
}
} |
890352a7-d98d-45ff-849a-ec4c8ba7aab2 | 2 | public boolean hasElement(T a)
{ if(this.a.equals(a))
{ return true;}
else if(this.next!=null)
{ return this.next.hasElement(a);
}
else
{ return false;
}
} |
d4c66ff8-37b6-404a-912f-c2e9d51b12b0 | 4 | public void handleWeaponStyle() {
if (c.fightMode == 0) {
c.getPA().sendFrame36(43, c.fightMode);
} else if (c.fightMode == 1) {
c.getPA().sendFrame36(43, 3);
} else if (c.fightMode == 2) {
c.getPA().sendFrame36(43, 1);
} else if (c.fightMode == 3) {
c.getPA().sendFrame36(43, 2);
}
} |
bc3cfcf4-8abf-4b89-abc8-919d08787035 | 9 | private void parsePacket()
throws MpegDecodeException, IOException
{
Statistics.startLog(PARSE_PACKET_STRING);
System.out.println("Parsing packet");
if(m_ioTool.getBits(24) != 0x1 )
{
Debug.println(Debug.ERROR, "Synchronization error in packet");
throw new MpegDecodeException("Synchronization error in packet");
}
int streamId = m_ioTool.getBits(8);
int pktLength = m_ioTool.getBits(16);
if( streamId != PRIVATE_STREAM2 )
{
pktLength -= parseTimeStamps();
}
if(( streamId & 0xE0 ) == 0xC0 )
{
// Audio Stream
//pktLength -= m_ioTool.getReadBytes();
decodeAudio( pktLength );
}
else
{
if( (0xF0 & streamId) == 0xE0 )
{
decodeVideo(pktLength );
}
else if( ( 0xF0 & streamId ) == 0xF0 )
{
// Reserved Stream ID
;
}
else
{
switch(streamId)
{
case RESERVED_STREAM:
case PRIVATE_STREAM1:
case PADDING_STREAM:
case PRIVATE_STREAM2:
break;
default:
Debug.println(Debug.ERROR, "Unknown Stream: " + streamId);
throw new MpegDecodeException("Unknown Stream: " + streamId);
}
}
}
Statistics.endLog(PARSE_PACKET_STRING);
} |
b7f04a4b-4b42-4d9b-800f-a955f4ae25d0 | 9 | protected void saveEditDebates() {
String topicTitle = titleCDJtxt.getText()
, maxTurns = maxTurnsJcbx.getSelectedItem().toString()
, maxTime = maxTimeJcbx.getSelectedItem().toString()
, description = descriptionCDJtxa.getText()
, materials = "";
int teamASize = teamACDDLM.getSize()
, teamBSize = teamBCDDLM.getSize();
String teams[][];
if (teamASize > teamBSize) {
teams = new String[2][teamASize];
} else {
teams = new String[2][teamBSize];
}
for (int i = 0; i < teamASize; i++) {
teams[0][i] = teamACDDLM.getElementAt(i).toString();
}
for (int i = 0; i < teamBSize; i++) {
teams[1][i] = teamBCDDLM.getElementAt(i).toString();
}
String teamAS = null, teamBS = null;
for (int i = 0; i < teams[0].length; i++) {
teamAS += teams[0][i];
teamBS += teams[0][i];
}
int maxTurnsValue = 0;
if (maxTurns != null) {
maxTurnsValue = Integer.parseInt(maxTurns.toString());
}
String[] teamLeader = {teamALeader, teamBLeader};
// Materials
for (int i = 0; i < litratureCDDLM.getSize(); i++) {
Object litrature = litratureCDDLM.getElementAt(i);
if (litrature != null) {
if (i == 0) {
materials = litrature.toString();
} else {
materials += "," + litrature.toString();
}
}
}
Debate debateCreate = new Debate(currentDebate.getId(), maxTurnsValue, topicTitle, description, teams, -1
, maxTime, materials, teamLeader, null, false, currentDebate.getCurentTurnTeam(), currentDebate.getStatus()
, currentDebate.getAcceptPositionTeam(), currentDebate.getTurnDuration(), currentDebate.getTimeLeft());
if (debate.editDebat(debateCreate)) {
JOptionPane.showMessageDialog(this, "You have edited a debate successfully", "Success", JOptionPane.YES_OPTION);
createDebateJfme.dispose();
// Refresh debate list
debateList = debate.getDebateList();
getDebateList();
} else {
JOptionPane.showMessageDialog(this, "You have edited a debate failed", "fail", JOptionPane.YES_OPTION);
}
} |
8cb63066-21f3-4ace-8ac0-b641b3902d8c | 5 | public void rechacharamistad(String emisor, String nick){
try {
String queryString = "DELETE FROM peticionAmistad WHERE emisor=? and receptor=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, emisor);
ptmt.setString(2, nick);
ptmt.executeUpdate();
System.out.println("Data Deleted Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
909e6751-2090-4d44-bb63-a47d1495506f | 3 | int bNNIRetestEdge( heap p, heap q, edge e, double[][] avgDistArray,
double[] weights, direction[] location, int possibleSwaps )
{
direction tloc;
tloc = location[e.head.index+1];
location[e.head.index+1] =
bNNIEdgeTest( e,avgDistArray,weights, e.head.index+1 );
if ( direction.NONE == location[e.head.index+1])
{
if ( direction.NONE != tloc )
p.popHeap(q,weights,possibleSwaps--,q.p[e.head.index+1]);
}
else
{
if ( direction.NONE == tloc )
p.pushHeap( q,weights,possibleSwaps++,q.p[e.head.index+1] );
else
p.reHeapElement( q, weights, possibleSwaps, q.p[e.head.index+1] );
}
return possibleSwaps;
} |
2b05d31f-ba4b-4e30-b4a1-34a6140bdf25 | 4 | @Test
public void testCompPerformance() {
int size = 100000;
int[] inVals = Permutation.randomPermutation(size);
int testVal = inVals[size / 2];
TreeMap<Integer, Integer> treeMap = new TreeMap<Integer, Integer>(comp);
long t1 = System.currentTimeMillis();
for (int i = 0; i < inVals.length; i++) {
treeMap.put(inVals[i], inVals[i]);
}
long t2 = System.currentTimeMillis();
System.out.println(String.format("TreeMap loaded %d items in %d ms.", size, t2 - t1));
RedBlackTree<Integer, Integer> rbTree = new RedBlackTree<Integer, Integer>(comp);
t1 = System.currentTimeMillis();
for (int i = 0; i < inVals.length; i++) {
rbTree.insert(inVals[i], inVals[i]);
}
t2 = System.currentTimeMillis();
System.out.println(String.format("RedBlackTree loaded %d items in %d ms.", size, t2 - t1));
t1 = System.nanoTime();
Integer v = rbTree.get(testVal);
t2 = System.nanoTime();
System.out.println(String.format("RBT found key in %d ms", (t2 - t1) / 1000));
t1 = System.nanoTime();
v = treeMap.get(testVal);
t2 = System.nanoTime();
System.out.println(String.format("TreeMap found key in %d ms", (t2 - t1) / 1000));
t1 = System.nanoTime();
int removeSize = size / 10;
for (int i = 0; i < removeSize; i++) {
treeMap.remove(inVals[i]);
}
t2 = System.nanoTime();
System.out.println(String.format("Treemap removed %d in %d ms.", removeSize, (t2 - t1) / 1000));
t1 = System.nanoTime();
for (int i = 0; i < removeSize; i++) {
rbTree.delete(inVals[i]);
}
t2 = System.nanoTime();
System.out.println(String.format("RedBlackTree removed %d in %d ms.", removeSize, (t2 - t1) / 1000));
assertTrue(rbTree.checkRedBlack());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.