method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
1a0a699f-8758-4b3a-a140-61d8e7b99bd7
| 4 |
private void multicast(Command com) {
try {
byte[] buffer = null;
if(com instanceof Send)
buffer = Utils.toByteArray((Send)com);
if(com instanceof Join)
buffer = Utils.toByteArray((Join)com);
if(com instanceof Leave)
buffer = Utils.toByteArray((Leave)com);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
m_multicastGroup, K.UDP_CLIENT_PORT);
m_multicastConn.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
|
7b360f27-0b2a-47d9-b2f1-5910f996d119
| 2 |
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line ;
while ((line = br.readLine()) != null) {
String tail = "";
if (line.contains("//")) {
int pos = line.indexOf("//");
tail = line.substring(pos);
line = line.substring(0, pos);
}
line = line.replaceAll("->", ".");
System.out.println(line + tail);
}
}
|
c5d65db5-6b6b-4a34-b988-2cf422d09bbf
| 4 |
private boolean canMoveDiagonal(Grid grid, Position pos) {
for (Element element : grid.getElementsOnGrid()) {
if (element instanceof Player
&& ((Player) element).getLightTrail().getPositions().contains(new Position(pos.getxCoordinate() - 1, pos.getyCoordinate()))
&& ((Player) element).getLightTrail().getPositions().contains(new Position(pos.getxCoordinate(), pos.getyCoordinate() + 1)))
return false;
}
return true;
}
|
f8771393-3eb8-4118-81e8-8ea07dfec0cc
| 7 |
@Override
public boolean equals(Object obj)
{
if(this == obj)
return true;
if(!(obj instanceof VirtualIPAddress))
return false;
if(!super.equals(obj))
return false;
// same VNO
VirtualIPAddress that = (VirtualIPAddress) obj;
return this.getVNO() == null && that.getVNO() == null ||
this.getVNO() != null && that.getVNO() != null &&
this.getVNO().equals(that.getVNO());
}
|
d389a398-5173-49a6-8f0c-d8253dc66173
| 3 |
public void saveSignals() {
final String signalsFilePath = dlgSignals.open();
if (signalsFilePath != null) {
Yaml yaml = new Yaml();
BufferedWriter stream = null;
try {
stream = new BufferedWriter(new FileWriter(signalsFilePath));
stream.write(yaml.dump(signals));
stream.close();
} catch (FileNotFoundException ex) {
showMessage(Messages.ERROR_FILE_NOT_FOUND + signalsFilePath, "Error");
} catch (IOException ex) {
showMessage(Messages.ERROR_CANT_WRITE_TO_FILE + signalsFilePath, "Error");
}
String message = Messages.FILE_SAVED + signalsFilePath;
status(message);
signalEditorPrepare();
se_signal.select(-1);
signalEditorSignalsChanged();
signalEditorSelectionChanged();
} else {
status(Messages.SIGNALS_FILE_NOT_SELECTED);
}
}
|
637ebb13-d1a5-4539-9c33-b16ce9d9697b
| 3 |
@Override
public void updateProduct(Product product) throws SQLException {
Session session=null;
try{
session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(product);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null && session.isOpen())
session.close();
}
}
|
e85d9fa0-272a-49ec-88ba-fc8aabb2ce99
| 8 |
public void keyReleased()
{ // keys released for avatar movement
if(key == CODED && keyCode == RIGHT)
{
rightKey = false;
}
if(key == CODED && keyCode == LEFT)
{
leftKey = false;
}
if(key == CODED && keyCode == UP)
{
upKey = false;
}
if(key == CODED && keyCode == DOWN)
{
downKey = false;
}
}
|
322eee77-159a-417a-ba7b-cf327ed2e84e
| 2 |
public void actionPerformed(ActionEvent e) {
if (e.getSource() == converter) {
berekenMensualiteit();
} else if (e.getSource() == create) {
createTable();
}
activateButtons();
}
|
3c71525d-e78c-4e97-9a4f-18725ed5a6c9
| 6 |
@Override
public boolean equals(Object o)
{
if (!(o instanceof RGBColor)) return false;
if (this == o) return true;
final RGBColor comp = (RGBColor) o;
if (Float.compare(r, comp.r) != 0) return false;
if (Float.compare(g, comp.g) != 0) return false;
if (Float.compare(b, comp.b) != 0) return false;
if (Float.compare(a, comp.a) != 0) return false;
return true;
}
|
952d496e-db11-4223-a4db-329f059f5235
| 5 |
@Override
public boolean equals(Object obj) {
if (obj != null
&& (obj.getClass().equals(TCard.class)
|| obj.getClass().equals(Token.class))) {
if (this.ID == null || ((TCard) obj).ID == null) {
Debug.p("Comparing cards with null ID!", Debug.W);
return false;
} else {
return this.ID.equals(((TCard) obj).ID);
}
} else {
return false;
}
}
|
fcdf477f-e08f-4e59-a162-8ccd43291f74
| 7 |
public void writeTofile(Network net) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/Users/jackgraham/Documents/MatLab/test2.m"));
out.write("net = network;");
out.newLine();
out.write("net.numInputs=(" + net.getInputAmount() +");");
out.newLine();
out.write("net.numLayers=(" + net.getLayerAmount() +");");
out.newLine();
for (int x =1;x<net.getInputAmount()+1;x++)
{
out.write("net.inputs{"+x+"}.size = 1;");
out.newLine();
}
for (int x =1;x<net.getLayerAmount()+1;x++)
{
out.write("net.layers{"+x+"}.size = 1;");
out.newLine();
}
connections = net.getConnections();
for (int x =0;x<connections.size();x++)
{
int[] temp = connections.get(x);
out.write("net.inputConnect("+temp[0]+","+temp[1]+") = 1;");
out.newLine();
}
for (int x=1;x<net.getOutputSize()+1;x++)
{
out.write("net.outputConnect("+x+") = 1;");
out.newLine();
}
weights = net.getWeights();
for (int x =0;x<weights.size();x++)
{
String temp = weights.get(x);
weightArray += (""+temp);
if (x!=weights.size())
{
weightArray+=",";
}
temp ="";
}
out.write("net = setwb(net,["+weightArray+"]);");
out.newLine();
out.write("view(net)");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("Exception ");
}
}
|
4e70a49d-8383-4c0f-9454-0c42d75f89ed
| 0 |
@Override
public void windowClosing(WindowEvent e)
{
// System.exit(0);
super.windowClosing(e);
System.exit(0);
}
|
ebddb60f-2a0b-4708-a906-23232cfc17e4
| 0 |
public void setPlainValue(byte[] value) {
this.plainValue = value;
}
|
b53c465c-a496-4f1f-854a-f361b4e80e59
| 9 |
public static void clearFolder (File folder) {
if (folder.exists()) {
for (String file : folder.list()) {
if (new File(folder, file).isDirectory()) {
clearFolder(new File(folder, file));
}
if (file.toLowerCase().endsWith(".zip") || file.toLowerCase().endsWith(".jar") || file.toLowerCase().endsWith(".disabled") || file.toLowerCase().endsWith(".litemod")) {
try {
boolean b = FTBFileUtils.delete(new File(folder, file));
if (!b)
Logger.logInfo("Error deleting " + file);
} catch (IOException e) {
Logger.logWarn(e.getMessage(), e);
}
}
}
}
}
|
a135d748-0b07-438f-bfde-5d851fb5bae9
| 6 |
private boolean verifyNewTradeRoute() {
Player player = getFreeColClient().getMyPlayer();
// Check that the name is unique
for (TradeRoute route : player.getTradeRoutes()) {
if (route.getId().equals(originalRoute.getId())) continue;
if (route.getName().equals(tradeRouteName.getText())) {
getGUI().errorMessage("traderouteDialog.duplicateName");
return false;
}
}
// Verify that it has at least two stops
if (stopListModel.getSize() < 2) {
getGUI().errorMessage("traderouteDialog.notEnoughStops");
return false;
}
// Check that all stops are valid
for (int index = 0; index < stopListModel.getSize(); index++) {
Stop stop = (Stop) stopListModel.get(index);
if (!TradeRoute.isStopValid(player, stop)) {
return false;
}
}
return true;
}
|
ddca1f76-3b51-4f49-8ceb-eb2646c2844e
| 9 |
public void thisMenuBarMouseReleased(java.awt.event.MouseEvent e)
{
Object src = e.getSource() ;
if ( src == jMenuFileLoad )
{
tbLoadButtonActionPerformed( null ) ;
}
else if ( src == jMenuFileReload )
{
tbReloadButtonActionPerformed( null ) ;
}
else if ( src == jMenuFileNew )
{
tbNewInstrButtonActionPerformed( null ) ;
}
else if ( src == jMenuFileQuit )
{
thisWindowClosing( null ) ;
}
else if ( src == jMenuRunnerStart )
{
tbStartForwardButtonActionPerformed( null ) ;
}
else if ( src == jMenuRunnerReset )
{
tbResetButtonActionPerformed( null ) ;
}
else if ( src == jMenuRunnerOneStep )
{
tbStep1ForwardButtonActionPerformed( null ) ;
}
else if ( src == jMenuHelpAbout )
{
new SSMAbout() ;
}
else if ( src == jMenuHelpHelponTopic )
{
new SSMHelp( helper ) ;
}
}
|
b7f4a940-25bc-4255-979f-ed050a6b809d
| 9 |
public String getPath(rpc.Helper.PathType type)
{
String ret = rpc.Helper.getRelativePath(this.getCurrentPackage(), type);
switch(type)
{
case eInterfaceHeader:
case eApiFolder:
case eProxyHeader:
case eStubBaseHeader:
ret = outputDir+"/api/" + ret;
break;
case eImplFolder:
case eParamsHeader:
case eProxySource:
case eParamsSource:
case eStubBaseSource:
ret = outputDir+"/impl/" + ret;
break;
default:
break;
}
return ret;
}
|
8555eadb-eb7d-4c70-8953-eb987ab21652
| 8 |
public TableStats (int tableid, int ioCostPerPage)
{
this.tableid = tableid;
this.ioCpstPerPage = ioCostPerPage;
Catalog catalog = Database.getCatalog();
DbFile dbFile = catalog.getDbFile(tableid);
TupleDesc tupleDesc = dbFile.getTupleDesc();
int numFields = tupleDesc.numFields();
MinMaxPair[] pairs = new MinMaxPair[numFields];
statFields = new Histogram[numFields];
try
{
getRowCount(dbFile);
for (int i = 0; i < numFields ; i++)
{
Type type = tupleDesc.getType(i);
switch(type)
{
case INT_TYPE:
{
MinMaxPair computedMinMax = computeMinMaxForIntField(i, dbFile);
pairs[i] = computedMinMax;
break;
}
case STRING_TYPE:
{
pairs[i] = new MinMaxPair();
break;
}
}
}
for (int i = 0; i < numFields ; i++)
{
Histogram histogram = null;
Type type = tupleDesc.getType(i);
switch(type)
{
case INT_TYPE:
{
histogram = new IntHistogram(NUM_HIST_BINS, pairs[i].min, pairs[i].max);
break;
}
case STRING_TYPE:
{
histogram = new StringHistogram(NUM_HIST_BINS);
break;
}
}
createAndPopulateHistogram(i, dbFile,pairs[i], histogram);
statFields[i] = histogram;
}
}
catch (DbException e)
{
}
catch (TransactionAbortedException e)
{
}
}
|
a57ffd0e-1abb-4b03-90a2-0efd036ba2bb
| 7 |
public static Stella_Object convertToLiteral(Stella_Object renamed_Object) {
if (renamed_Object == null) {
return (renamed_Object);
}
{ Surrogate testValue000 = Stella_Object.safePrimaryType(renamed_Object);
if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_LITERAL_WRAPPER)) {
{ LiteralWrapper object000 = ((LiteralWrapper)(renamed_Object));
return (object000);
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol object000 = ((Symbol)(renamed_Object));
if (object000 == Stella.SYM_STELLA_TRUE) {
return (Stella.TRUE_WRAPPER);
}
if (object000 == Stella.SYM_STELLA_FALSE) {
return (Stella.FALSE_WRAPPER);
}
return (object000);
}
}
else if (Surrogate.subtypeOfKeywordP(testValue000)) {
{ Keyword object000 = ((Keyword)(renamed_Object));
return (object000);
}
}
else if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate object000 = ((Surrogate)(renamed_Object));
return (object000);
}
}
else {
Stella.STANDARD_WARNING.nativeStream.println("Warning: `convert-to-literal': Can't handle non-boolean literals");
return (null);
}
}
}
|
1ade01b8-658d-4ced-83ee-ea270001a569
| 7 |
public void computeColorManagers() {
double maximumValue = 0;
double minimumValue = 0;
for (List<PointWithHamma> pointWithHammaList : solver.getFlyingPointsWithHama().values()) {
for (PointWithHamma pointWithHamma : pointWithHammaList) {
if (pointWithHamma.getHamma() > maximumValue) {
maximumValue = pointWithHamma.getHamma();
}
if (pointWithHamma.getHamma() < minimumValue) {
minimumValue = pointWithHamma.getHamma();
}
}
}
for (PointWithHamma pointWithHamma : shape.getAllPoints()) {
double hamma = pointWithHamma.getHamma();
if (hamma > maximumValue) {
maximumValue = hamma;
}
if (hamma < minimumValue) {
minimumValue = hamma;
}
}
negativePointColorManager = new ColorManager(minimumValue, 0, new Color(10, 10, 255), new Color(255, 255, 255));
positivePointColorManager = new ColorManager(0, maximumValue, new Color(255, 255, 255), new Color(255, 10, 10));
negativePointColorManagerDrawer.setColorManager(negativePointColorManager);
positivePointColorManagerDrawer.setColorManager(positivePointColorManager);
}
|
5575dc3f-f508-4b1d-ac7e-cd5eb1553b63
| 7 |
private void resizeScreenIfNeeded() {
TerminalSize newSize;
synchronized(resizeQueue) {
if(resizeQueue.isEmpty())
return;
newSize = resizeQueue.getLast();
resizeQueue.clear();
}
int height = newSize.getRows();
int width = newSize.getColumns();
ScreenCharacter [][]newBackBuffer = new ScreenCharacter[height][width];
ScreenCharacter [][]newVisibleScreen = new ScreenCharacter[height][width];
ScreenCharacter newAreaCharacter = new ScreenCharacter('X', Terminal.Color.GREEN, Terminal.Color.BLACK);
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
if(x < backbuffer[0].length && y < backbuffer.length)
newBackBuffer[y][x] = backbuffer[y][x];
else
newBackBuffer[y][x] = new ScreenCharacter(newAreaCharacter);
if(x < visibleScreen[0].length && y < visibleScreen.length)
newVisibleScreen[y][x] = visibleScreen[y][x];
else
newVisibleScreen[y][x] = new ScreenCharacter(newAreaCharacter);
}
}
backbuffer = newBackBuffer;
visibleScreen = newVisibleScreen;
wholeScreenInvalid = true;
terminalSize = new TerminalSize(newSize);
}
|
d3b150ac-d365-4e7d-bb31-ddbc7dd78717
| 8 |
public void storeDefinition(boolean isStatic, String variable, String value) {
int i1 = variable.indexOf("[");
if (i1 != -1) {
int i2 = variable.indexOf("]");
if (i2 != -1) {
int size = getArraySize(variable.substring(0, i1));
String index = variable.substring(i1 + 1, i2).trim();
int ix = 0;
String s = definition.get(index);
if (s != null) {
ix = (int) Double.parseDouble(s);
}
else {
index = index.trim();
if (index.startsWith("\"")) {
index = index.substring(1);
}
if (index.endsWith("\"")) {
index = index.substring(0, index.length() - 1);
}
double ixd = parseMathExpression(index);
if (Double.isNaN(ixd)) {
out(ScriptEvent.FAILED, "Array index error: " + variable);
return;
}
ix = (int) ixd;
}
if (ix >= size) {
out(ScriptEvent.FAILED, "Array index out of bound (" + size + "): " + ix + " in " + variable);
return;
}
variable = variable.substring(0, i1 + 1) + ix + variable.substring(i2);
}
}
if (isStatic) {
storeSharedDefinition(variable, value);
}
else {
definition.put(variable, value);
}
}
|
902338ae-4bba-471b-88a9-8a45b3d1cbab
| 7 |
public static boolean isIntensityParam(String accession) {
return INTENSITY_SUBSAMPLE1.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE2.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE3.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE4.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE5.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE6.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE7.getAccession().equals(accession) ||
INTENSITY_SUBSAMPLE8.getAccession().equals(accession);
}
|
3f967e5f-1fe0-44ac-81ef-21a0411e04fb
| 5 |
public static Packet readPacketFromFile(String filename, Node serverNode) throws IOException, NullPointerException {
if (filename == null || serverNode == null) {
throw new NullPointerException();
}
BufferedReader bfr = new BufferedReader(new FileReader(filename));
String line = bfr.readLine();
boolean oriented = (line.equals("T")) ? true : false;
line = bfr.readLine();
boolean resendImmediately = (line.equals("T")) ? true : false;
line = bfr.readLine();
String command = line;
Packet packet = new Packet(command, serverNode);
packet.setOriented(oriented);
packet.setResendImmediately(resendImmediately);
packet.addData("num", "11");//TODO do vstupu
String[] splits;
while ((line = bfr.readLine()) != null) {
splits = line.split(" ");
Node node = new Node(null, InetAddress.getByName(splits[0]),
Integer.valueOf(splits[1]));
packet.addNodeToVisit(node);
}
bfr.close();
return packet;
}
|
a5730ade-066d-4ae2-bdc2-6aeb7c6b4600
| 3 |
public VariableStack mapStackToLocal(VariableStack stack) {
VariableStack newStack;
int params = cond.getFreeOperandCount();
if (params > 0) {
condStack = stack.peek(params);
newStack = stack.pop(params);
} else
newStack = stack;
VariableStack after = VariableStack.merge(thenBlock
.mapStackToLocal(newStack), elseBlock == null ? newStack
: elseBlock.mapStackToLocal(newStack));
if (jump != null) {
jump.stackMap = after;
return null;
}
return after;
}
|
bc65f138-6cfa-4d4c-9f76-0a8f6b192577
| 6 |
public WorldImage makeImage( ) {
WorldImage world = new RectangleImage( new Posn( 500, 325 ), 1000, 650, new White( ) );
if( level == 0 ) {
world = new OverlayImages( world, new FromFileImage( new Posn( 500, 325 ), "images/titlescreen.png" ) );
}
else if( level == 1 ) {
world = new OverlayImages( world, new TextImage(
new Posn( 500, 600 ),
"LEVEL ONE", 50, new Black( ) ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 500, 250 ),
"images/bigbomb.png" ) );
}
else if( level == 2 ) {
world = new OverlayImages( world, new TextImage(
new Posn( 500, 600 ),
"LEVEL TWO", 50, new Black( ) ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 350, 250 ),
"images/bigbomb.png" ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 650, 250 ),
"images/bigbomb.png" ) );
}
else if( level == 3 ) {
world = new OverlayImages( world, new TextImage(
new Posn( 500, 600 ),
"LEVEL THREE", 50, new Black( ) ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 200, 250 ),
"images/bigbomb.png" ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 500, 250 ),
"images/bigbomb.png" ) );
world = new OverlayImages( world, new FromFileImage(
new Posn( 800, 250 ),
"images/bigbomb.png" ) );
}
else if( level == 4 ) {
world = new OverlayImages( world, new FromFileImage(
new Posn( 500, 350 ),
"images/congrats.png" ) );
}
else if( level == 5 ) {
world = new OverlayImages( world, new FromFileImage(
new Posn( 490, 250 ),
"images/gameover.png" ) );
}
return world;
}
|
5c6bcef7-53d2-4805-9a46-341dfe0a0a39
| 7 |
@Override
public void execute(CommandSender s, String[] args){
if(!open){
Broadcast.vote("The vote is not currently open.", s);
return;
}
if(args.length == 1){
String name;
if(s instanceof Player) name = ((Player)s).getName();
else name = "CONSOLE";
String cast = args[0];
VoteCast vote = null;
if(cast.equalsIgnoreCase("A")) vote = VoteCast.A;
else if(cast.equalsIgnoreCase("B")) vote = VoteCast.B;
else if(cast.equalsIgnoreCase("R")) vote = VoteCast.R;
else{
Broadcast.error("Incorrect usage.", s);
Broadcast.error("Usage: /vote [A/B/R]", s);
return;
}
if(votes.containsKey(name)){
VoteCast oldVote = votes.get(name);
uncastVote(oldVote);
}castVote(vote);
votes.put(name, vote);
updatePlayerReadout();
Broadcast.vote("You have voted for " + vote.toString(), s);
}else{
Broadcast.error("Incorrect usage.", s);
Broadcast.error("Usage: /vote [A/B/R]", s);
}
}
|
cc0c88ec-9cf0-40d6-bd63-69e152f1af48
| 7 |
public boolean isCreatable() {
return (!is_abstract && !is_attribute && !name.equals("Class") && !name.equals("Attribute")
&& !is_enum && !is_enum_value && !name.equals("EnumerationType")
&& !name.equals("EnumerationLiteral"));
}
|
9ba43bbf-590f-4ada-8c53-664fc821603e
| 3 |
private void notifyBlockOfNeighborChange(int var1, int var2, int var3, int var4) {
if (!this.editingBlocks && !this.multiplayerWorld) {
Block var5 = Block.blocksList[this.getBlockId(var1, var2, var3)];
if (var5 != null) {
var5.onNeighborBlockChange(this, var1, var2, var3, var4);
}
}
}
|
ff0ed208-bce9-4172-b711-cc020a9a938f
| 2 |
public void printEntrypoints(){
if (this.entrypoints == null)
System.out.println("Entry points not initialized");
else {
System.out.println("Classes containing entry points:");
for (String className : entrypoints)
System.out.println("\t" + className);
System.out.println("End of Entrypoints");
}
}
|
3b0cf0f5-570e-4e64-a563-6fc8081646c7
| 8 |
public void setValueRangeAndState(ConfigurationIntegerValueRange[] regionAndState) {
if(regionAndState != null) {
_regionAndState = regionAndState;
// Bei den Zuständen darf jeder Wert und jeder Name nur einmal vorkommen.
final Set<String> stateNames = new HashSet<String>();
final Set<Long> stateValues = new HashSet<Long>();
for(ConfigurationIntegerValueRange configurationIntegerValueRange : _regionAndState) {
if(configurationIntegerValueRange instanceof ConfigurationState) {
final ConfigurationState configurationState = (ConfigurationState)configurationIntegerValueRange;
if(stateNames.contains(configurationState.getName()) == true || stateValues.contains(configurationState.getValue()) == true){
// Der Name oder/und der Wert wurde bereits vergeben -> Das ist verboten
final StringBuffer errorText = new StringBuffer();
// Die passende Fehlermeldung zusammenbauen
if(stateNames.contains(configurationState.getName()) == true && stateValues.contains(configurationState.getValue()) == true){
// Sowohl der Name als auch der Wert sind schon vergeben
errorText.append("Sowohl der Name als auch der Wert eines Zustands wurden schon einmal vergeben: \"Name: " + configurationState.getName() + "\" \"Wert: " + configurationState.getValue() + "\"");
}else if(stateNames.contains(configurationState.getName()) == true){
errorText.append("Der Name des Zustands wurde schon einmal vergeben: \"Name: " + configurationState.getName() + "\" \"Wert: " + configurationState.getValue() + "\"");
}else{
errorText.append("Der Wert des Zustands wurde schon einmal vergeben: \"Name: " + configurationState.getName() + "\" \"Wert: " + configurationState.getValue() + "\"");
}
throw new IllegalArgumentException(errorText.toString());
}
stateNames.add(configurationState.getName());
stateValues.add(configurationState.getValue());
}
}//for
}
}
|
5fd03f5c-a6e6-4449-aa02-72989fcf3629
| 4 |
public void setSelectedColor(Color newColor) {
if (null == newColor) {
setSelectedIndex(-1);
return;
}
for (int i = 0; i < getItemCount(); i++) {
ColorValue cv = (ColorValue) getItemAt(i);
if (newColor.equals(cv.color)) {
setSelectedItem(cv);
return;
}
}
if (allowCustomColors) {
removeCustomValue();
ColorValue cv = new ColorValue(newColor, true);
DefaultComboBoxModel model = (DefaultComboBoxModel) getModel();
model.insertElementAt(cv, 0);
setSelectedItem(cv);
}
}
|
e61226a3-6dfc-4233-bd6f-2c904263e10c
| 5 |
public static Esstyp vonName(String s) {
if (s.equals("VEGETARIER")) return VEGETARIER;
if (s.equals("VEGANER")) return VEGANER;
if (s.equals("FLEXITARIER")) return FLEXITARIER;
if (s.equals("FISCHFRESSER")) return FISCHFRESSER;
if (s.equals("FLEISCHFRESSER")) return FLEISCHFRESSER;
return VEGETARIER;
}
|
3b26be2b-4a39-4184-803b-eafbeb263263
| 7 |
protected boolean isStraight(final Deck deck) {
usesLow = false;
usesAllCards = false;
for (Rank rank : Rank.values()) {
high = rank;
low = rank;
kickers.clear();
boolean fail = false;
for (int i = 0; i < 5; i++) {
if (low == null || deck.getRank(low).size() == 0) {
fail = true;
break;
}
if (low == Rank.DEUCE && i == 3) {
low = Rank.ACE;
} else {
low = low.getLower();
}
}
if (!fail) {
low = null;
return true;
}
}
low = null;
return false;
}
|
d449cbd0-568e-43ca-9de8-8da68878ca87
| 8 |
@Override
public void collides(Entity... en) {
if (cullable) {
return;
}
for (Entity e : en) {
if (e == null || e.getBounds() == null || e == this || e.cull())
continue;
Polygon p = e.getBounds();
if (shape.intersects(e.getBounds())
|| shape.contains(e.getBounds())) {
takeDamage(e.doDamage());
e.takeDamage(doDamage());
continue;
}
}
return;
}
|
b0ee092b-11ad-4388-addf-37e4f01c2bd2
| 3 |
public AngleDR Ds2tp(AngleDR r, AngleDR rz) throws palError {
double sdecz, sdec, cdecz, cdec, radif, sradif, cradif, denom, xi, eta;
double ra = r.getAlpha(), dec = r.getDelta();
double raz = rz.getAlpha(), decz = rz.getDelta();
String Errmsg = null;
TRACE("Ds2tp");
/* Trig functions */
sdecz = Math.sin(decz);
sdec = Math.sin(dec);
cdecz = Math.cos(decz);
cdec = Math.cos(dec);
radif = ra - raz;
sradif = Math.sin(radif);
cradif = Math.cos(radif);
/* Reciprocal of star vector length to tangent plane */
denom = sdec * sdecz + cdec * cdecz * cradif;
/* Handle vectors too far from axis */
if (denom > TINY) {
Status = 0;
} else if (denom >= 0.0) {
Status = 1;
Errmsg = "star too far from axis";
denom = TINY;
} else if (denom > -TINY) {
Status = 2;
Errmsg = "antistar on tangent plane";
denom = -TINY;
} else {
Status = 3;
Errmsg = "antistar too far from axis";
}
/* Compute tangent plane coordinates (even in dubious cases) */
xi = cdec * sradif / denom;
eta = (sdec * cdecz - cdec * sdecz * cradif) / denom;
ENDTRACE("Ds2tp");
return new AngleDR(xi, eta);
}
|
80e46425-1c33-4f1d-ab3e-389734d7a7cf
| 3 |
public static byte[] getData() {
try {
ExtendedByteArrayOutputStream buffer = new ExtendedByteArrayOutputStream();
buffer.putShort(cache.size());
for (int index = 0; index < cache.size(); index++) {
RSInterface rsi = cache.get(index);
if (rsi == null) {
continue;
}
buffer.write(Utilities.getHeaderChunk(rsi));
buffer.write(Utilities.getTypeChunk(rsi));
}
buffer.close();
return buffer.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
|
b5e5e290-c776-4fb3-8525-40c8da0df1a4
| 2 |
public static void play() {
try {
if(currentPlayback != null) {
currentPlayback.play();
System.out.println("Now playing: " + currentTrack);
}
} catch (MediaException e) {
System.out.println("Invalid media type.");
}
}
|
43fda009-2f7d-472b-bb2e-b07994d28374
| 9 |
private void updateCurrentLogFile()
{
// get the log file name from the file system
File logFolder = new File(slateComponent.getLogDirectoryName());
File[] listOfLogFiles = logFolder.listFiles();
numLogFiles = listOfLogFiles.length;
if (numLogFiles == 0)
{
return;
}
if ((RotationParadigm.Bounded.equals(slateComponent.getSlateSettings().getRotationParadigm()) && (currentLogFileCounter < 0)) ||
(RotationParadigm.Continuous.equals(slateComponent.getSlateSettings().getRotationParadigm()) && (currentLogFileCounter >= numLogFiles)))
{
currentLogFileCounter = 0;
}
if ((RotationParadigm.Bounded.equals(slateComponent.getSlateSettings().getRotationParadigm()) && (currentLogFileCounter >= numLogFiles)) ||
(RotationParadigm.Continuous.equals(slateComponent.getSlateSettings().getRotationParadigm()) && (currentLogFileCounter < 0)))
{
currentLogFileCounter = numLogFiles - 1;
}
// Now, get the log file
currentLogFile = listOfLogFiles[currentLogFileCounter];
}
|
b3e68020-9632-4a5e-b6f0-b04c3f53c0eb
| 0 |
private Xpp3Dom getCurrentTestCase() {
return currentTestCase.get();
}
|
0efa1dbf-8ca2-4df9-8942-24da77d405eb
| 1 |
public void setPath(String path) {
this.path = path;
if (this.path != null) {
this.path_list = new ArrayList();
parsePath(this.path_list, this.path);
}
}
|
76bc24b2-add0-4859-bdff-5410afeeb96a
| 0 |
public void onTimeChanged(int time)
{
timeButton.setText(TimeManager.getTimeString(time));
}
|
88fb0e20-acd6-4f79-951d-c9c143cf7805
| 5 |
public Cmd()
{
int nivelDeDificuldade = teclado.nextInt("Nivel de dificuldade [0 ou 1] >");
e = new Engine( nivelDeDificuldade );
e.init();
Util.println("Cima: "+KEY_UP+" | Baixo: "+KEY_DOWN+" | Esquerda: "+KEY_LEFT+" | Direita: "+KEY_RIGHT);
while( !e.isGameOver() )
{
drawArena();
switch( teclado.nextChar(">") )
{
case KEY_UP:
e.getCobra().setDireccao('u');
break;
case KEY_DOWN:
e.getCobra().setDireccao('d');
break;
case KEY_LEFT:
e.getCobra().setDireccao('l');
break;
case KEY_RIGHT:
e.getCobra().setDireccao('r');
break;
default:
break;
}
e.run();
}
drawArena();
Util.println("Game Over - Pontuação: "+e.getPontuacao().getValor());
}
|
b40b7a6b-9117-4cd0-a2ec-ed3f6acb6f67
| 8 |
protected synchronized void doStop()
throws InterruptedException
{
for (int l=0;l<_listeners.size();l++)
{
HttpListener listener =(HttpListener)_listeners.get(l);
if (listener.isStarted())
{
try{listener.stop();}
catch(Exception e)
{
if (log.isDebugEnabled())
log.warn(LogSupport.EXCEPTION,e);
else
log.warn(e.toString());
}
}
}
HttpContext[] contexts = getContexts();
for (int i=0;i<contexts.length;i++)
{
HttpContext context=contexts[i];
context.stop(_gracefulStop);
}
if (_notFoundContext!=null)
{
_notFoundContext.stop();
removeComponent(_notFoundContext);
}
_notFoundContext=null;
if (_requestLog!=null && _requestLog.isStarted())
_requestLog.stop();
}
|
a150758d-10c9-4da5-aa06-7b971820ef82
| 0 |
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
|
4d6515d0-ef40-47d5-b3a4-ff6fb67ce05b
| 9 |
@Override
public synchronized String[] readDirectoryEntries(SyndicateFSPath path) throws FileNotFoundException, IOException {
if(path == null) {
LOG.error("path is null");
throw new IllegalArgumentException("path is null");
}
SyndicateFSPath absPath = getAbsolutePath(path);
SyndicateFSFileStatus status = getFileStatus(absPath);
if(status == null) {
LOG.error("directory does not exist : " + absPath.getPath());
throw new FileNotFoundException("directory does not exist : " + absPath.getPath());
}
List<String> entries = new ArrayList<String>();
Future<ClientResponse> readDirFuture = this.client.listDir(absPath.getPath());
if(readDirFuture != null) {
try {
DirectoryEntries processReadDir = this.client.processListDir(readDirFuture);
// remove duplicates
Map<String, StatRaw> entryTable = new HashMap<String, StatRaw>();
// need to remove duplicates
int entry_cnt = 0;
for(StatRaw statRaw : processReadDir.getEntries()) {
entry_cnt++;
if(entry_cnt <= 2) {
// ignore . and ..
continue;
}
StatRaw eStatRaw = entryTable.get(statRaw.getName());
if(eStatRaw == null) {
// first
entryTable.put(statRaw.getName(), statRaw);
} else {
if(eStatRaw.getVersion() <= statRaw.getVersion()) {
// replace
entryTable.remove(statRaw.getName());
entryTable.put(statRaw.getName(), statRaw);
}
}
}
entries.addAll(entryTable.keySet());
// put to memory cache
for(StatRaw statRaw : entryTable.values()) {
SyndicateFSPath entryPath = new SyndicateFSPath(absPath, statRaw.getName());
this.filestatusCache.remove(entryPath);
SyndicateFSFileStatus entryStatus = new SyndicateFSFileStatus(this, absPath, statRaw);
this.filestatusCache.put(entryPath, entryStatus);
}
} catch (Exception ex) {
LOG.error("exception occurred", ex);
throw new IOException(ex);
}
} else {
throw new IOException("Can not create a REST client");
}
return entries.toArray(new String[0]);
}
|
318101a2-296a-4ea9-b97f-f1b7f1f20f67
| 6 |
public static void main(String[] args) {
StackArray[] stacks = {new StackArray(), new StackFIFO(), new StackHanoi()};
StackList stack2 = new StackList();
for (int i = 1; i < 15; ++i) {
stacks[0].push(i);
stack2.push(i);
stacks[1].push(i);
}
Random random = new Random();
for (int i = 1; i < 15; ++i) {
stacks[2].push(random.nextInt(20));
}
while (!stacks[0].isEmpty()) {
System.out.print(stacks[0].pop() + BLANK_SPACE);
}
System.out.println();
while (!stack2.isEmpty()) {
System.out.print(stack2.pop() + BLANK_SPACE);
}
System.out.println();
while (!stacks[1].isEmpty()) {
System.out.print(stacks[1].pop() + BLANK_SPACE);
}
System.out.println();
while (!stacks[2].isEmpty()) {
System.out.print(stacks[2].pop() + BLANK_SPACE);
}
System.out.println();
System.out.println("Total rejected is: " + ((StackHanoi) stacks[2]).reportRejected());
}
|
e0109b1c-c714-4c61-8925-dee24523074d
| 4 |
private void loadJniResources() {
boolean wasLoadSuccessful = loadX64ResourcesFromSysPath();
if (!wasLoadSuccessful) {
wasLoadSuccessful = loadWin32ResourcesFromSysPath();
if (!wasLoadSuccessful) {
setLibDirectory();
wasLoadSuccessful = copyAndLoadX64FromTemp();
if (!wasLoadSuccessful) {
wasLoadSuccessful = copyAndLoadWin32FromTemp();
if (wasLoadSuccessful) {
throw new UnsatisfiedLinkError("Could Not Load myo and myo-java libs");
}
}
}
}
}
|
d42a67d6-c2cf-4d67-a03c-ad224c9bee6a
| 4 |
@Override
public void undo() {
if (oldKey == null) {
if (newKey == null) {
// Do Nothing, since this should never happen.
} else {
node.removeAttribute(newKey);
}
} else {
if (newKey == null) {
node.setAttribute(oldKey, oldValue, oldReadOnly);
} else {
if (!oldKey.equals(newKey)) {
node.removeAttribute(newKey);
}
node.setAttribute(oldKey, oldValue, oldReadOnly);
}
}
}
|
b34bbd9d-af31-49fd-9d04-1dc3eda8c472
| 7 |
@SuppressWarnings("CallToThreadDumpStack")
public static void main(String[] args) throws Exception {
System.out.println("model used: " + model);
DB db = new DB();
String sql_op;
try {
Tickets tickets = new Tickets();
Technicians technicians = new Technicians();
TicketTechnicians ticket_technicians = new TicketTechnicians();
Entries entries = new Entries();
TicketEntries ticket_entries = new TicketEntries();
// Loop which creates tables:
for (DBTable table : new DBTable[]{tickets, technicians, ticket_technicians, entries, ticket_entries}) {
String table_name = table.getTableName();
System.out.println();
sql_op = String.format("drop table if exists `%s`", table_name);
System.out.println(sql_op);
db.exec(sql_op);
String table_def_file =
"setup" + java.io.File.separator + table_name + "-" + model + ".sql";
String table_def = Util.readTextFile(table_def_file);
sql_op = String.format("create table `%s` (%s)", table_name, table_def);
System.out.println(sql_op);
db.exec(sql_op);
}
if (!populate) {
return;
}
// =======================================================================
// Test data:
// The user selects ticket ID in case the company takes a ticket from another company.
tickets.add("title1", "open", "Bob", "ABC Broadcasting", "7/8/81");
tickets.add("title2", "closed", "Steve", "Philmont Acadamey", "8/7/13");
tickets.add("title3", "open", "Steve", "Philmont Acadamey", "8/7/13");
System.out.println("\n\nOur Tickets are: ");
for (Ticket t : tickets.fetchAll()) {
System.out.println(t.toString());
}
technicians.add("a", "a", "A", 0); // For testing
technicians.add("b", "b", "B", 1); // Admin For testing
technicians.add("corbus", "maximus1", "Corbin", 0); // 1
technicians.add("davidus", "apple1", "David", 0); // 2
technicians.add("quinntus", "mango1", "Quinn", 1); // 2
System.out.println("\n\nOur Technicians are: ");
for (Technician t : technicians.fetchAll()) {
System.out.println(t.toString());
}
// Add a technician to a ticket: (TechID, TicketID)
ticket_technicians.add(1, 1); // put Gary on ticket 1
ticket_technicians.add(1, 2); // put Gary on ticket 2
ticket_technicians.add(2, 1); // put Peter on ticket 1
ticket_technicians.add(3, 1);
ticket_technicians.add(3, 3); // put Corbin on Ticket
// Fetch all of Tech #1 tickets:
System.out.println("\n\nTechnician 1's tickets:");
for (Ticket t : tickets.fetchAllForTechnician(1)) {
System.out.println(t.toString());
}
// Fetch all of Corbin's tickets:
System.out.println("\n\nCorbin's tickets are:");
for (Ticket t : tickets.fetchAllForTechnician(3)) {
System.out.println(t.toString());
}
// This call removes a technician from a ticket
ticket_technicians.remove(3, 1);
// Added functionality 4/30/13:
// Create Entry:
entries.add("4/29/13", "Gary", "Had a lot of fun working with ABC");
// Associate it with appropriate ticket: (entryID, ticketID)
ticket_entries.add(1, 1);
// Create Entry:
entries.add("1/1/13", "Corbin", "Had a lot of fun working with the ball");
// Associate it with appropriate ticket: (entryID, ticketID)
ticket_entries.add(2, 1);
} catch (Exception ex) {
ex.printStackTrace();
}
}
|
05a95139-02a1-4290-b603-06796268a44d
| 7 |
public double getSimilarityScore(FeatureVector t1, FeatureVector t2) {
ArrayList<Feature> featureList1 = null;
ArrayList<Feature> featureList2 = null;
try {
//System.out.println("fv1:"+t1.getFeatureList().get(0).getId());
//System.out.println("fv2:"+t2.getFeatureList().get(0).getId()+" "+t2.getFeatureList().get(1).getId());
featureList1 = t1.getFeatureList();
featureList2 = t2.getFeatureList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double denom1=0;
double denom2=0;
Collections.sort(featureList1);
Collections.sort(featureList2);
for(int i=0;i<featureList1.size();i++){
Feature f1 = featureList1.get(i);
denom1 += f1.getScore()*f1.getScore();
}
for(int i=0;i<featureList2.size();i++){
Feature f2 = featureList2.get(i);
denom2 += f2.getScore()*f2.getScore();
}
double num=0;
int i=0;
int j=0;
while(i<featureList1.size() && j<featureList2.size()){
Feature f1 = featureList1.get(i);
Feature f2 = featureList2.get(j);
if(f1.getId()==f2.getId()){
num += f1.getScore()*f2.getScore();
}
if(f1.getId()<f2.getId()){
i++;
}else{
j++;
}
}
return num/(Math.sqrt(denom1)*Math.sqrt(denom2));
}
|
be2d8d1a-137d-4941-85dd-78ae2d541746
| 5 |
private void removeComposedBlocks() {
List<GenericTreeNode<LayoutParserTreeElement>> list = this.layoutParser.XMLTree
.build(GenericTreeTraversalOrderEnum.PRE_ORDER);
for (GenericTreeNode<LayoutParserTreeElement> element : list) {
if (element.getData().elementType == LayoutParserTreeElement.ElementType.COMPOSEDBLOCK) {
// Get all children.
List<GenericTreeNode<LayoutParserTreeElement>> childrenList = element
.getChildren();
// Get parrent.
GenericTreeNode<LayoutParserTreeElement> parent = element
.getParent();
// Add ComposedBlock's children to it's parent.
for (GenericTreeNode<LayoutParserTreeElement> child : childrenList) {
parent.addChild(child);
}
// Delete ComposedBlock.
for (int i = 0; i < parent.getNumberOfChildren(); i++) {
if (parent.getChildAt(i) == element) {
parent.removeChildAt(i);
break;
}
}
}
}
}
|
9a6fb9ab-bf38-4ac9-817d-ce0a6c0a14d4
| 3 |
@Override
public boolean equals(Object obj) {
if ((obj == null) || (!(obj instanceof HardwareAddress))) {
return false;
}
HardwareAddress hwAddr = (HardwareAddress) obj;
return ((this.hardwareType == hwAddr.hardwareType) &&
(Arrays.equals(this.hardwareAddress, hwAddr.hardwareAddress)));
}
|
789b51f7-35d9-48fe-a069-2e245b63c8ea
| 6 |
public String ValidarCampo(Prospecto BEEntidades){
// Nombre, ApellidosPaterno, ApellidoMaterno, Email, NroDocumento, Telefono
sb.append(Common.IsNullOrEmpty(BEEntidades.getNombre())? "nombre inválido,": "");
sb.append(Common.IsNullOrEmpty(BEEntidades.getApellidoPaterno())? "nombre inválido,": "");
sb.append(Common.IsNullOrEmpty(BEEntidades.getApellidoMaterno())? "nombre inválido,": "");
sb.append(Common.IsNullOrEmpty(BEEntidades.getEmail())? "nombre inválido,": "");
sb.append(Common.IsNullOrEmpty(BEEntidades.getNroDocumento())? "nombre inválido,": "");
sb.append(Common.IsNullOrEmpty(BEEntidades.getTelefono())? "nombre inválido,": "");
rs.SetResult(ResultType.Advertencia, "Error de campo", sb.toString());
return rs.toString();
}
|
31e880fc-2c7d-411d-840c-5c984513bfd4
| 1 |
public void visitAttribute(final Attribute attr) {
checkState();
if (attr == null) {
throw new IllegalArgumentException(
"Invalid attribute (must not be null)");
}
cv.visitAttribute(attr);
}
|
fc5350da-bea3-4e09-a929-8269f5947a52
| 8 |
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerInteractBlock(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
if(player.hasPermission("skeptermod.useitem.hellsword") || (event.getPlayer().isOp()))
{
if(player.getItemInHand().getTypeId() == Material.STONE_SWORD.getId() && event.getPlayer().getItemInHand().getEnchantmentLevel(Enchantment.DAMAGE_ALL) == 16960)
{
if(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
player.getWorld().strikeLightning(player.getTargetBlock(null, 200).getLocation());
player.getWorld().createExplosion(player.getTargetBlock(null, 200).getLocation(), 3.0F);
player.setHealth(player.getHealth() - 2);
player.setFoodLevel(player.getFoodLevel() - 10);
}}
}else{
}
}
|
952d6d81-2e96-4ed2-bffd-d655721c004e
| 5 |
public void applyModifiers(PlayerAttributes attr) {
for(int i = 0; i < 3; i++) {
if(equipped[i] != null && equipped[i] instanceof AttributeItem) {
attr.applyRaw(((AttributeItem) equipped[i]).getRawModifiers());
attr.applyRelative(((AttributeItem) equipped[i]).getRelativeModifiers());
}
}
for(ArmorItem item : armor.values()) {
if(item != null) {
attr.applyRaw(item.getRawModifiers());
attr.applyRelative(item.getRelativeModifiers());
}
}
}
|
05c983f8-a80d-447d-b7b2-f5a2b637b998
| 3 |
protected double calculatePressure(){
//The pressure of the condenser is the current pressure + input flow of steam - output flow of water.
ArrayList<Component> inputs = super.getRecievesInputFrom();
Iterator<Component> it = inputs.iterator();
Component c = null;
double totalInputFlowRate = 0;
while(it.hasNext()){
c = it.next();
if(!(c.getName().contains("Coolant"))){
totalInputFlowRate += c.getOutputFlowRate();
}
}
if(temperature > 100){
return pressure + totalInputFlowRate - super.getOutputFlowRate();
}else{
return (pressure-pressure/temperature) + totalInputFlowRate - super.getOutputFlowRate();
}
}
|
31dd2c76-be68-43df-bfe0-d8d3496b8c3d
| 2 |
private static void test_xor(TestCase t) {
// Print the name of the function to the log
pw.printf("\nTesting %s:\n", t.name);
// Run each test for this test case
int score = 0;
for (int i = 0; i < t.tests.length; i += 3) {
int exp = (Integer) t.tests[i];
int arg1 = (Integer) t.tests[i + 1];
int arg2 = (Integer) t.tests[i + 2];
int res = HW2Operations.xor(arg1, arg2);
boolean cor = exp == res;
if (cor) {
++score;
}
pw.printf("%s(%8X, %8X): Expected: %8X Result: %8X Correct: %5b\n",
t.name, arg1, arg2, exp, res, cor);
pw.flush();
}
// Set the score for this test case
t.score = (double) score / (t.tests.length / 3);
}
|
7c2d6997-dd32-4410-b1be-e8db2dbe0f71
| 8 |
private boolean handleMousePressed(MouseEvent e, int x, int y) {
Point ptBCP = new Point(0, 0); // Block center point
Cube3D iClosestBlock = world.get(0);
float sfDSquared = 0;
float sfAdjust = 0;
float sfMin = 100000000; // 2d distance to block closest to click.
// Find the closest block (a very simple solution to the selection
// interaction task (seems to work fine)):
for (Cube3D block : world.getBlocks()) {
// Compute the distance from the cube centerpoint to the mouse
// point:
Point3D TempPoint = block.getCenterPoint();
TempPoint.transform(hmPerspXform);
sfAdjust = getFocalLength() / TempPoint.getZ(); // Adjust x and y
// for
// perspective view
ptBCP.x = getWidth() / 2 + ((int) (TempPoint.getX() * sfAdjust));
ptBCP.y = getHeight() / 2 - ((int) (TempPoint.getY() * sfAdjust));
sfDSquared = (ptBCP.x - x) * (ptBCP.x - x) + (ptBCP.y - y) * (ptBCP.y - y);
if (sfDSquared < sfMin) {
sfMin = sfDSquared;
iClosestBlock = block;
}
}
if (sfMin > MAX_CLICK_DISTANCE) {
if (bSelectedDest) {
showStatus("move " + BWEnvironment.blockName(iSourceBlock) + " to floor");
bSelectedDest = false; // Toggle the selection state
iSourceBlock.setSelected(false);
world.move(iSourceBlock, null);
return true;
} else {
showStatus("nothing selected");
}
return false;
}
if (iClosestBlock.topBlock()) {
if (bSelectedDest && iClosestBlock == iSourceBlock) {
this.showStatus(
"Block " + BWEnvironment.blockName(iClosestBlock) + " cannot be stacked on top of itself.");
} else {
if (bSelectedDest) {
// We are selecting the destination block for stacking the
// previously selected block
iDestBlock = iClosestBlock;
bSelectedDest = false; // Toggle the selection state
iSourceBlock.setSelected(false);
world.move(iSourceBlock, iDestBlock);
this.showStatus("Block " + BWEnvironment.blockName(iSourceBlock) + " stacked on block "
+ BWEnvironment.blockName(iDestBlock) + ".");
} else {
// We are selecting the source block for stacking on the
// next block selected
this.showStatus("Block " + BWEnvironment.blockName(iClosestBlock) + " selected.");
// Change the selected block color to red and redisplay:
iClosestBlock.setSelected(true);
repaint(); // pure gui change, need to ask for repaint.
iSourceBlock = iClosestBlock;
bSelectedDest = true; // Toggle the selection state
}
}
} else {
this.showStatus("Block " + BWEnvironment.blockName(iClosestBlock) + " has a block above it.");
}
return true;
}
|
e6bef7fd-fe7d-4100-a780-de6d54754d0e
| 3 |
public static void main(String[] args) throws IOException {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
System.out.println("Host ID not found!");
System.exit(1);
}
userEntry = new Scanner(System.in);
do {
System.out.print("\nEnter name ('Dave' or 'Karen'): ");
name = userEntry.nextLine();
} while (!name.equals("Dave") && !name.equals("Karen"));
talkToServer();
}
|
faef66d0-ee67-4d75-a56b-d7567a3ebd2c
| 7 |
@Override
public void exec(CommandSender sender, String label, String[] args, Player player, boolean isPlayer) {
if (isPlayer) {
String p = player.getName();
String user = p.toLowerCase();
if (!player.hasPermission("stickii.use")) {
player.sendMessage(ChatColor.RED + "Access Denied.");
return;
}
if (args.length < 1) {
player.sendMessage(ChatColor.GOLD + "Correct usage: /stickii <type> <block id>");
player.sendMessage(ChatColor.GOLD + "Use /stickii help if you need help.");
return;
}
if (args[0].equalsIgnoreCase("help")) {
player.sendMessage(ChatColor.AQUA + "");
player.sendMessage(ChatColor.GOLD + "Stickii Help:");
player.sendMessage(ChatColor.AQUA + "");
player.sendMessage(ChatColor.AQUA + "Correct usage: /stickii <type> <block id>");
player.sendMessage(ChatColor.AQUA + "Types: delete replace");
player.sendMessage(ChatColor.AQUA + "");
player.sendMessage(ChatColor.AQUA + "Block ID " + ChatColor.UNDERLINE + "is not" + ChatColor.RESET + ChatColor.AQUA + " required for the delete type");
player.sendMessage(ChatColor.AQUA + "Will act as a mask to stop you deleting other blocks.");
player.sendMessage(ChatColor.AQUA + "");
player.sendMessage(ChatColor.AQUA + "Block ID " + ChatColor.UNDERLINE + "is" + ChatColor.RESET + ChatColor.AQUA + " required for the replace type.");
player.sendMessage(ChatColor.AQUA + "Will be the replacement block.");
player.sendMessage(ChatColor.AQUA + "");
return;
}
if (args[0].equalsIgnoreCase("delete")) {
this.plugin.toggleStickiiDelete(player, args, p, user);
giveStick(player, args, p, user);
return;
}
if (args[0].equalsIgnoreCase("replace")) {
if (args.length < 2) {
player.sendMessage(ChatColor.RED + "Correct usage: /stickii replace <block id>");
} else {
this.plugin.toggleStickiiReplace(player, args, p, user);
}
giveStick(player, args, p, user);
return;
}
// Will only happen if the player tries an invalid command.
player.sendMessage(ChatColor.GOLD + "Correct usage: /stickii <type> <block id>");
player.sendMessage(ChatColor.GOLD + "Use /stickii help if you need help.");
}
}
|
c2a1441b-abd9-4f50-b81e-3fb681d0355b
| 2 |
@SuppressWarnings("rawtypes")
public static final Class[] toClasses(Object[] args)
{
if(args.length <= 0)
return new Class[0];
Class[] value = new Class[args.length];
int iter = 0;
for(Object A : args)
{
value[iter] = A.getClass();
iter++;
}
return value;
}
|
089e7e80-d2f1-4351-8cf2-0602e7696420
| 5 |
public static boolean wasActionOffensive(JSONObject action){
if(action == null) return false;
try {
String actiontype = action.getString("type");
switch (actiontype){
case "laser":
return true;
case "droid":
return true;
case "mortar":
return true;
default:
return false;
}
}
catch (JSONException e){
return false;
}
}
|
9f3abf42-4268-4940-9059-0805aeeda6a0
| 8 |
public boolean next(Buffer _buf) throws Exception{
int i,j;
switch(state){
case SSH_MSG_KEXDH_REPLY:
// The server responds with:
// byte SSH_MSG_KEXDH_REPLY(31)
// string server public host key and certificates (K_S)
// mpint f
// string signature of H
j=_buf.getInt();
j=_buf.getByte();
j=_buf.getByte();
if(j!=31){
System.err.println("type: must be 31 "+j);
return false;
}
K_S=_buf.getString();
// K_S is server_key_blob, which includes ....
// string ssh-dss
// impint p of dsa
// impint q of dsa
// impint g of dsa
// impint pub_key of dsa
//System.err.print("K_S: "); //dump(K_S, 0, K_S.length);
byte[] f=_buf.getMPInt();
byte[] sig_of_H=_buf.getString();
dh.setF(f);
K=dh.getK();
//The hash H is computed as the HASH hash of the concatenation of the
//following:
// string V_C, the client's version string (CR and NL excluded)
// string V_S, the server's version string (CR and NL excluded)
// string I_C, the payload of the client's SSH_MSG_KEXINIT
// string I_S, the payload of the server's SSH_MSG_KEXINIT
// string K_S, the host key
// mpint e, exchange value sent by the client
// mpint f, exchange value sent by the server
// mpint K, the shared secret
// This value is called the exchange hash, and it is used to authenti-
// cate the key exchange.
buf.reset();
buf.putString(V_C); buf.putString(V_S);
buf.putString(I_C); buf.putString(I_S);
buf.putString(K_S);
buf.putMPInt(e); buf.putMPInt(f);
buf.putMPInt(K);
byte[] foo=new byte[buf.getLength()];
buf.getByte(foo);
sha.update(foo, 0, foo.length);
H=sha.digest();
//System.err.print("H -> "); //dump(H, 0, H.length);
i=0;
j=0;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
String alg=Util.byte2str(K_S, i, j);
i+=j;
boolean result=false;
if(alg.equals("ssh-rsa")){
byte[] tmp;
byte[] ee;
byte[] n;
type=RSA;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
ee=tmp;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
n=tmp;
SignatureRSA sig=null;
try{
Class c=Class.forName(session.getConfig("signature.rsa"));
sig=(SignatureRSA)(c.newInstance());
sig.init();
}
catch(Exception e){
System.err.println(e);
}
sig.setPubKey(ee, n);
sig.update(H);
result=sig.verify(sig_of_H);
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"ssh_rsa_verify: signature "+result);
}
}
else if(alg.equals("ssh-dss")){
byte[] q=null;
byte[] tmp;
byte[] p;
byte[] g;
type=DSS;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
p=tmp;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
q=tmp;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
g=tmp;
j=((K_S[i++]<<24)&0xff000000)|((K_S[i++]<<16)&0x00ff0000)|
((K_S[i++]<<8)&0x0000ff00)|((K_S[i++])&0x000000ff);
tmp=new byte[j]; System.arraycopy(K_S, i, tmp, 0, j); i+=j;
f=tmp;
SignatureDSA sig=null;
try{
Class c=Class.forName(session.getConfig("signature.dss"));
sig=(SignatureDSA)(c.newInstance());
sig.init();
}
catch(Exception e){
System.err.println(e);
}
sig.setPubKey(f, p, q, g);
sig.update(H);
result=sig.verify(sig_of_H);
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"ssh_dss_verify: signature "+result);
}
}
else{
System.err.println("unknown alg");
}
state=STATE_END;
return result;
}
return false;
}
|
6a380e70-7544-468a-9cbe-8c8a55c64acd
| 6 |
public boolean hasPermissions( CommunityAccount who, PublishedSwarm swarm ) {
if( swarm == null ) {
return false;
}
boolean canModerate = false;
if( who != null ) {
canModerate = who.canModerate();
}
if( canModerate ) {
return true;
}
if( swarm.isNeeds_moderated() && System.getProperty(EmbeddedServer.Setting.REQUIRE_SWARM_MODERATION.getKey()).equals(Boolean.TRUE.toString()) ) {
return false;
}
if( swarm.isRemoved() ) {
return false;
}
return true;
}
|
483399b1-2e45-44bf-8210-eeb140481f72
| 5 |
public void recharge(final MapleClient c, final byte slot) {
final IItem item = c.getPlayer().getInventory(MapleInventoryType.USE).getItem(slot);
if (item == null || (!InventoryConstants.isThrowingStar(item.getItemId()) && !InventoryConstants.isBullet(item.getItemId()))) {
return;
}
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
short slotMax = ii.getSlotMax(item.getItemId());
slotMax += 200;
if (item.getQuantity() < slotMax) {
final int price = (int) Math.round(ii.getPrice(item.getItemId()) * (slotMax - item.getQuantity()));
if (c.getPlayer().getMeso() >= price) {
item.setQuantity(slotMax);
c.getSession().write(MaplePacketCreator.updateInventorySlot(MapleInventoryType.USE, (Item) item, false));
c.getPlayer().gainMeso(-price, false, true, false);
c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0x8));
}
}
}
|
eeff8a3a-38e4-4085-97c7-29fe3759067d
| 1 |
private Configuration(Tetromino tName, int tRotations, Point[] tCoords) {
name = tName;
coords = tCoords;
states = new Rotation[tRotations];
for (int i = 0; i < tRotations; ++i) {
states[i] = new Rotation(coords, i);
}
}
|
e5378477-bd8f-498d-827b-afcda884b76e
| 3 |
private void comboCidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCidadeActionPerformed
String item = String.valueOf(comboModelCidade.getSelectedItem());
if(item.equals("Selecionar ...") || item == "null"){
System.out.println("Olá");
if(listaCheia == true){
comboModelBairro.removeAllElements();
comboModelBairro.addElement("Selecionar ...");
}
comboBairro.setSelectedIndex(0);
}else{
System.out.println("Carregando bairros!");
carregaBairros();
listaCheia = true;
}
}//GEN-LAST:event_comboCidadeActionPerformed
|
51261881-43c5-45ad-b683-ca8a3802a47b
| 6 |
protected void changeOffsetDisplay()
{
if (ABS_HEX_MODE == offsetDisplayMode)
offsetDisplayMode = ABS_DECIMAL_MODE;
else if (ABS_DECIMAL_MODE == offsetDisplayMode)
offsetDisplayMode = REL_BASE_HEX_MODE;
else if (REL_BASE_HEX_MODE == offsetDisplayMode)
offsetDisplayMode = REL_BASE_DECIMAL_MODE;
else if (REL_BASE_DECIMAL_MODE == offsetDisplayMode)
offsetDisplayMode = REL_HEX_MODE;
else if (REL_HEX_MODE == offsetDisplayMode)
offsetDisplayMode = REL_DECIMAL_MODE;
else if (REL_DECIMAL_MODE == offsetDisplayMode)
offsetDisplayMode = ABS_HEX_MODE;
else
{
displayError("Illegal offsetDisplayMode: " + offsetDisplayMode, "Error");
return;
}
fireTableDataChanged();
}
|
dddd46c2-ced1-41c5-b755-88a8e07557bc
| 7 |
@Override
public boolean capturar(Posicao posicaoFinal) {
/* peao preto */
if (this.getCor().equals(Cores.preto)) {
if ((posicaoFinal.getLinha() == getPosicao().getLinha() - 1)
&& ((posicaoFinal.getColuna() == getPosicao().getColuna() + 1) || (posicaoFinal
.getColuna() == getPosicao().getColuna() - 1))) {
return true;
}
} /* peao branco */ else {
if ((posicaoFinal.getLinha() == getPosicao().getLinha() + 1)
&& ((posicaoFinal.getColuna() == getPosicao().getColuna() + 1) || (posicaoFinal
.getColuna() == getPosicao().getColuna() - 1))) {
return true;
}
}
return false;
}
|
2b1abbe4-0313-4a62-a376-3243713d472e
| 6 |
public static List<String> extractLinks(String url, LinkFilter filter) {
List<String> links = new ArrayList<String>();
try {
Parser parser = new Parser(url);
parser.setEncoding("gb2312");
NodeFilter frameNodeFilter = new NodeFilter(){
public boolean accept(Node node) {
if (node.getText().startsWith("frame src="))
return true;
else
return false;
}
};
NodeFilter aNodeFilter = new NodeClassFilter(LinkTag.class);
OrFilter linkFilter = new OrFilter(frameNodeFilter, aNodeFilter);
NodeList nodeList = parser.extractAllNodesThatMatch(linkFilter);
for(int i = 0; i<nodeList.size();i++)
{
Node node = nodeList.elementAt(i);
String linkURL = "";
if(node instanceof LinkTag)
{
LinkTag link = (LinkTag)node;
linkURL= link.getLink();
}
if(filter.accept(linkURL) && !links.contains(linkURL))
links.add(linkURL);
}
} catch (ParserException e) {
e.printStackTrace();
}
return links;
}
|
2bd40902-6698-411a-9e71-fe6b36ceffb1
| 9 |
@Test(groups = { "tck" })
public void test_factory_string_hours_minutes_colon() {
for (int i = -17; i <= 17; i++) {
for (int j = -59; j <= 59; j++) {
if ((i < 0 && j <= 0) || (i > 0 && j >= 0) || i == 0) {
String str = (i < 0 || j < 0 ? "-" : "+") + Integer.toString(Math.abs(i) + 100).substring(1) + ":"
+ Integer.toString(Math.abs(j) + 100).substring(1);
ZoneOffset test = ZoneOffset.of(str);
doTestOffset(test, i, j, 0);
}
}
}
ZoneOffset test1 = ZoneOffset.of("-18:00");
doTestOffset(test1, -18, 0, 0);
ZoneOffset test2 = ZoneOffset.of("+18:00");
doTestOffset(test2, 18, 0, 0);
}
|
42ce9ddc-73e9-4742-afc0-9e32cef05005
| 6 |
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == Actions.SERVER.name()) {
server = new Server(PROTOCAL.NOPROTOCAL);
System.out.println("Server");
} else if (e.getActionCommand() == Actions.T2.name()) {
server = new Server(PROTOCAL.T2);
System.out.println("T2");
} else if (e.getActionCommand() == Actions.T3.name()) {
server = new Server(PROTOCAL.T3);
System.out.println("T3");
} else if (e.getActionCommand() == Actions.T4.name()) {
server = new Server(PROTOCAL.T4);
System.out.println("T4");
} else if (e.getActionCommand() == Actions.T5.name()) {
server = new Server(PROTOCAL.T5);
System.out.println("T5");
}
try {
this.server.serverStart();
} catch (Exception e1) {
System.out.println("Server cannot start");
e1.printStackTrace();
}
}
|
39b6a9d5-3e07-444d-a1e7-006c1407a52d
| 3 |
public static boolean isConnectionFromBottom(Position posa, Position posb) {
return posa.getX() > posb.getX() && posa.getY() < posb.getY()
|| posa.getX() < posb.getX() && posa.getY() > posb.getY();
}
|
273bb986-0234-4ac8-a1d1-535458dff88c
| 0 |
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
parentarena.playerLeave(player, "Ϸر,");
}
|
6e48b94f-54ce-493a-bb09-c0507464ff92
| 6 |
@Override
public String saveAnswer(Question question) {
if (question == null) {
return "Не передан объект вопроса";
}
if (question.getIdTest() == null) {
return "В переданом объекте отсутствует ссылка на тест";
}
if (question.getIdQuestion() == null) {
return "В переданом объекте вопроса нет его кода";
}
answer = new Answer();
answer.setQuestion(question);
answer.setIsRightAnswer(this.isRightAnswer());
answer.setNameAnswer(this.getTextAnswer());
try {
int ret = answer.insertInto();
if (ret == -1) {
return "Такой Ответ на вопрос уже есть";
}
} catch (SQLException ex) {
return ex.toString();
}
try {
answer.setIdAnswer(answer.getIdFromDataBase());
} catch (SQLException ex) {
Logger.getLogger(ItemSelectedPanel.class.getName()).log(Level.SEVERE, null, ex);
return ex.toString();
}
return null;
}
|
74203bfb-7ae2-4162-bd45-213c01ddb981
| 6 |
public void testCollisionWhithBomb(){
for (int iw = 0; iw < weapon.size(); iw++) {
Weapon w = weapon.get(iw);
if(boss.getRect().intersects(w.getRect())){
weapon.remove(iw);
boss.hp--;
if(boss.hp == 0){
JOptionPane.showMessageDialog(null, "NOOOOO!");
System.exit(1);
}
}
for (int ie = 0; ie < enemies.size(); ie++) {
Enemy e = enemies.get(ie);
if(e.getRect().intersects(w.getRect())){
enemies.remove(ie);
weapon.remove(iw);
player.xp = player.xp + 10;
if(player.xp >= 200)addBoss();
}
}
}
}
|
42647322-737f-42cc-a309-b95ee82c09c1
| 5 |
public Pong(GameStateManager gsm) {
super(gsm);
panel = new JPanel();
this.gsm = gsm;
timer = new Timer(10,this);
cd = new Timer(30, t1);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
double[] a = coords.get("PLAYER1");
a[DY] = 5;
coords.put("PLAYER1", a);
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
double[] a = coords.get("PLAYER1");
a[DY] = -5;
coords.put("PLAYER1", a);
}
if(e.getKeyCode() == KeyEvent.VK_0) {
double[] a = coords.get("BALL");
speedX += 5;
a[DX] = speedX;
coords.put("BALL", a);
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
double[] a = coords.get("PLAYER1");
a[DY] = 0;
coords.put("PLAYER1", a);
}
if(e.getKeyCode() == KeyEvent.VK_UP) {
double[] a = coords.get("PLAYER1");
a[DY] = 0;
coords.put("PLAYER1", a);
}
}
});
}
|
327b44dd-3f23-4bb3-8263-c707400b258e
| 9 |
boolean whitelisted(String page, String user, String summary, String project) {
if (config.whitelistModel.contains(user + "#" + project)
|| config.tempwhitelistModel.contains(user + "#" + project))
return (true);
else {
int size = config.regexpwhiteModel.getSize(), i;
for (i = 0; i < size; i++)
if ((config.getBooleanProp("rwhiteuser") && user
.matches((String) config.regexpwhiteModel.getElementAt(i)))
|| (config.getBooleanProp("rwhitepage") && page
.matches((String) config.regexpwhiteModel.getElementAt(i)))
|| (config.getBooleanProp("rwhitesummary") && summary
.matches((String) config.regexpwhiteModel.getElementAt(i))))
return (true);
}
return (false);
}
|
405116da-59ba-4045-b381-0be01791c1a2
| 5 |
@Override
public int loop() {
//6 hour paint thing (wann keep dem paints up)
//or whatever it is :/
if (Game.getClientState() != Game.INDEX_MAP_LOADED) {
return 1000;
}
if (client != Bot.client()) {
WidgetCache.purge();
Bot.context().getEventManager().addListener(this);
client = Bot.client();
}//end 6 hour thing
if(Game.isLoggedIn()){
for(Node job : jobs){
if(job.activate()){
System.out.println(job.getClass().getName());
job.execute();
}
}//end node loop
}//end if game is logged in
return Random.nextInt(100, 200);
}
|
6f4a6f9b-5232-4d69-9766-75c75973cbee
| 8 |
public void beforeDie(List<CardFighter> battleField) {
// PROTECT_INFANTRY
if (this.getCard().getProtectInfantry() > 0) {
for (CardFighter cardFighter : battleField) {
if (!cardFighter.equals(this) && cardFighter.getCard().getType() == Card.TYPE_INFANTRY) {
cardFighter.defense -= this.getCard().getProtectInfantry();
}
}
}
// END PROTECT_INFANTRY
// COMMAND INFANTRY
if (this.getCard().getCommantInfantry() > 0) {
for (CardFighter cardFighter : battleField) {
if (!cardFighter.equals(this) && cardFighter.getCard().getType() == Card.TYPE_INFANTRY) {
cardFighter.attack -= this.getCard().getCommantInfantry();
}
}
}
// END COMMAND INFANTRY
}
|
9acb8c1f-4e4b-4f35-8904-54070b494c23
| 0 |
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
// not implemented
}
|
f759e55d-1184-4190-a812-db2a8e3c25ac
| 0 |
public IdleAction(Being b) {
being = b;
}
|
5858f4b7-19c0-44c9-aca8-1e1b2044fe43
| 5 |
public void runScript(InputStream stream) throws JStrykerException, IllegalArgumentException {
if (stream == null) {
throw new IllegalArgumentException("Stream cannot be null.");
}
try {
List<String> commands = parse(stream);
for (String command : commands) {
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute(command.toString());
} finally {
if (statement != null) {
statement.close();
}
}
}
} catch (SQLException e) {
throw new JStrykerException(e.getMessage(), e);
} catch (IOException e) {
throw new JStrykerException(e.getMessage(), e);
}
}
|
e408c89f-a8d2-43d2-825d-e44fc4dc220c
| 7 |
public final int checkForNewline(byte[] data, int pos) {
// Note that pos pointing just past end of data is permitted.
assert pos >= 0 && pos <= data.length;
switch (this) {
case LF:
return pos < data.length && data[pos] == 10 ? 1 : 0;
case CR:
return pos < data.length && data[pos] == 13 ? 1 : 0;
default:
throw new RuntimeException("bug detected");
}
}
|
10534834-2c7f-453a-a41f-07f8d69a97eb
| 2 |
public static String join(Object[] items, String delim) {
// Return an empty string for an empty list
if (items.length == 0)
return "";
// Otherwise build up the joined string
StringBuilder out = new StringBuilder();
// Put the delimiter after all but the last item
for (int i = 0; i < items.length - 1; i++) {
out.append(items[i].toString());
out.append(delim);
}
// Add the last element
out.append(items[items.length - 1]);
return out.toString();
}
|
97e72438-d2bb-4ecb-a6b8-b7e739a91e4c
| 2 |
public void priceUpdate(){
double bidMedian = bids.getMedian();
double askMedian = asks.getMedian();
price = (bidMedian + askMedian) / 2; // new price is average of their medians
price = (double)(Math.round(price * 100)) / 100; // rounds to 10th
double newBid = newPurchase(); // calls helper method to create new purchase
bids.insert(newBid);
double newAsk = newPurchase();
asks.insert(newAsk);
updatePercent(); // method that updates percent change
if (price > high)
high = price;
if (price < low)
low = price;
}
|
f1e5eab0-eb55-4eef-9df3-b668406536db
| 0 |
public LaucherModule(){
setAuthor("Sinrel Group");
setName("minecraft game laucnher");
setVersion("1.0.0");
}
|
b35b574c-285c-4385-8b46-022fb9490f4d
| 1 |
public AnnotationVisitor visitAnnotation(
final String desc,
final boolean visible)
{
return new SAXAnnotationAdapter(getContentHandler(),
"annotation",
visible ? 1 : -1,
null,
desc);
}
|
d6d0077d-5d49-45dc-afd1-68bd8a60a14b
| 5 |
protected void ensureSimpleValues(Map.Entry<String,Set<RDFNode>> prop, Class<?> expectedClass, Path path) {
for( RDFNode n : prop.getValue() ) {
if( !n.hasOnlySimpleValue() ) {
logPathError("Expected a simple value for "+prop.getKey(), path);
anyErrors = true;
}
if( n.simpleValue != null && !expectedClass.isInstance(n.simpleValue) ) {
logPathError("Expected "+prop.getKey()+" to be a "+expectedClass.getSimpleName()+
", but found a "+n.simpleValue.getClass().getSimpleName(), path);
}
}
}
|
40325e82-587a-4543-96d7-da688777cea0
| 0 |
public void removeTreeSelectionListener(TreeSelectionListener l) {
treeSelectionListeners.remove(l);
}
|
deca700a-5615-4ac6-b80b-68d59f971163
| 4 |
public BorderDetectorDialog(final Panel panel, final String title) {
setTitle(title);
this.panel = panel;
setBounds(1, 1, 450, 150);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width/3 - getWidth()/3, size.height/3 - getHeight()/3);
this.setResizable(false);
setLayout(null);
JPanel synthetizationPanel = new JPanel();
synthetizationPanel.setBorder(BorderFactory.createTitledBorder("Sinthetization:"));
synthetizationPanel.setBounds(0, 0, 450, 80);
final JRadioButton absRadioButton = new JRadioButton("Module", true);
final JRadioButton maxRadioButton = new JRadioButton("Maximum");
final JRadioButton minRadioButton = new JRadioButton("Minimum");
final JRadioButton avgRadioButton = new JRadioButton("Average");
maxRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
maxRadioButton.setSelected(true);
minRadioButton.setSelected(!maxRadioButton.isSelected());
avgRadioButton.setSelected(!maxRadioButton.isSelected());
absRadioButton.setSelected(!maxRadioButton.isSelected());
}
});
minRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
minRadioButton.setSelected(true);
maxRadioButton.setSelected(!minRadioButton.isSelected());
avgRadioButton.setSelected(!minRadioButton.isSelected());
absRadioButton.setSelected(!minRadioButton.isSelected());
}
});
avgRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
avgRadioButton.setSelected(true);
maxRadioButton.setSelected(!avgRadioButton.isSelected());
minRadioButton.setSelected(!avgRadioButton.isSelected());
absRadioButton.setSelected(!avgRadioButton.isSelected());
}
});
absRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
absRadioButton.setSelected(true);
maxRadioButton.setSelected(!absRadioButton.isSelected());
minRadioButton.setSelected(!absRadioButton.isSelected());
avgRadioButton.setSelected(!absRadioButton.isSelected());
}
});
JButton okButton = new JButton("OK");
okButton.setBounds(100, 80, 250, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SynthetizationType synthetizationType = null;
if(maxRadioButton.isSelected()) {
synthetizationType = SynthetizationType.MAX;
} else if(minRadioButton.isSelected()) {
synthetizationType = SynthetizationType.MIN;
} else if(avgRadioButton.isSelected()) {
synthetizationType = SynthetizationType.AVG;
} else if(absRadioButton.isSelected()) {
synthetizationType = SynthetizationType.ABS;
} else {
throw new IllegalStateException();
}
BorderDetectorDialog.this.applyFunction(synthetizationType);
}
});
synthetizationPanel.add(absRadioButton);
synthetizationPanel.add(maxRadioButton);
synthetizationPanel.add(minRadioButton);
synthetizationPanel.add(avgRadioButton);
this.add(synthetizationPanel);
this.add(okButton);
}
|
518127b8-4e91-442c-9cf8-b1d21e6493e4
| 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(ProfilClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProfilClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProfilClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProfilClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ProfilClient().setVisible(true);
}
});
}
|
b6f25d30-4749-4054-9665-cad883332934
| 5 |
public BasicStringType( String str ) {
super( BasicType.TYPE_STRING );
this.string = str;
if( str == null )
return;
// Try to parse number values
if( !parseIntegerType(str) && !parseDoubleType(str) )
;
if( !parseBooleanType(str) )
;
if( !parseUUIDType(str) )
;
}
|
2bc4c834-e9b1-484b-a5bf-84aede0663b3
| 2 |
public final void setFName(String fname) {
if(fname == null || fname.isEmpty()){
throw new IllegalArgumentException();
}
this.fName = fname;
}
|
e0450eea-a9d0-4caa-a289-34402658f076
| 8 |
private void dealCards(RuleChecker rc) throws IllegalMoveException{
ArrayList<Card> deck = Card.makeDeck();
for (int i = 0; i < 8 * 4; i++) {
players.get(i % 4).giveCard(deck.get(i));
}
for (Player p : players) {
boolean greatTaipan = p.informFirstDeal();
if (greatTaipan) {
rc.greatTaipan(p.getID());
for (Player q : players) {
q.informGreatTaipan(p.getID());
}
}
}
for (int i = 8 * 4; i < 14 * 4; i++) {
players.get(i % 4).giveCard(deck.get(i));
}
for (Player p : players) {
boolean taipan = p.informSecondDeal();
if (taipan) {
rc.taipan(p.getID());
for (Player q : players) {
q.informTaipan(p.getID());
}
}
}
}
|
de0e7208-545a-4cf6-b444-9ad51ae62c60
| 3 |
private void displayRavagePatternAnalysis(){
set_tolerance(64);
System.out.printf("");
System.out.println();
System.out.println("SPACESHIP PATTERN MATCHING ANALYSIS WITH TOLERANCE LEVEL OF "+get_tolerance());
RavagePatternDetector ravagePattern;
List<RavagePatternDetector> foundRavagePatterns = new LinkedList<RavagePatternDetector>();
int startIndex = 0;
for(startIndex=0;startIndex<ravageDetectedPatterns.size();startIndex++){
ravagePattern = ravageDetectedPatterns.get(startIndex);
if(ravagePattern.getConfidence()>=get_tolerance()){
foundRavagePatterns.add(ravagePattern);
}
}
for(startIndex=0;startIndex<foundRavagePatterns.size();startIndex++){
ravagePattern = foundRavagePatterns.get(startIndex);
System.out.println("Target Type : SPACESHIP " );
System.out.println("Coordinates : x -"+ravagePattern.getX()+" y - "+ravagePattern.getY());
System.out.println("Degree of Confidence - "+ravagePattern.getConfidence());
}
}
|
9590ef1d-fb22-409f-baf0-6ae2dc5edee5
| 0 |
public boolean isProperty() {return prop;}
|
3571b556-5ddc-4ab9-8ce9-bd4f8cc271e8
| 9 |
public void updateResolutionsByColumnByMergeIdUsingResolutionsByColumnAsJSONObject(
Integer mergeId, JSONObject resolutionsByColumnAsJsonObject) {
//Note: This also updates the merge's total conflict count.
//for each index in column_number, update the fields present (except for keys)
MergeModel mergeModel = new MergeModel();
mergeModel.setId(mergeId);
Connection connection = this.getDatabaseModel().getNewConnection();
if (connection != null) {
try {
//Insert all the joins from this JSON Object
JSONArray columnNumbers = resolutionsByColumnAsJsonObject.optJSONArray("column_number");
JSONArray conflictIds = resolutionsByColumnAsJsonObject.optJSONArray("conflict_id");
JSONArray solutionByColumnIds = resolutionsByColumnAsJsonObject.optJSONArray("solution_by_column_id");
if (columnNumbers == null) {
columnNumbers = new JSONArray();
columnNumbers.put(resolutionsByColumnAsJsonObject.optInt("column_number"));
}
if (conflictIds == null) {
conflictIds = new JSONArray();
conflictIds.put(resolutionsByColumnAsJsonObject.optInt("conflict_id"));
}
if (solutionByColumnIds == null) {
solutionByColumnIds = new JSONArray();
solutionByColumnIds.put(resolutionsByColumnAsJsonObject.optInt("solution_by_column_id"));
}
for (int i = 0; i < columnNumbers.length(); i++) {
ResolutionByColumnModel resolutionByColumnModel = new ResolutionByColumnModel();
resolutionByColumnModel.setMergeModel(mergeModel);
resolutionByColumnModel.setColumnNumber(columnNumbers.getInt(i));
ConflictModel problemByColumnModel = new ConflictModel();
problemByColumnModel.setId(conflictIds.getInt(i));
resolutionByColumnModel.setConflictModel(problemByColumnModel);
//FIXME: Don't want to overwrite conflicts_count with null. Don't set to 0 if you have a solution (loses data).
//Merge's total_conflicts_count will only count conflicts that have no solution.
SolutionByColumnModel solutionByColumnModel = new SolutionByColumnModel();
//optInt returns 0 if not an Integer
if (solutionByColumnIds.optInt(i) != 0) {
solutionByColumnModel.setId(solutionByColumnIds.getInt(i));
} else {
solutionByColumnModel.setId(null);
}
resolutionByColumnModel.setSolutionByColumnModel(solutionByColumnModel);
if (resolutionsByColumnAsJsonObject.has("constant-" + columnNumbers.getInt(i))) {
resolutionByColumnModel.setConstant(resolutionsByColumnAsJsonObject.getString("constant-" + columnNumbers.getInt(i)));
} else {
resolutionByColumnModel.setConstant(null);
}
this.updateResolutionByColumnUsingResolutionByColumnModel(resolutionByColumnModel, connection);
}
//TODO: Recount the conflicts (take problems with solutions as 0, otherwise use the resolution conflict_count)
MergeScripts mergeScripts = new MergeScripts();
mergeModel = mergeScripts.retrieveMergeAsMergeModelThroughDeterminingTotalConflictsCountUsingMergeModel(mergeModel, connection);
}
catch (Exception e) {
this.logger.severe(e.toString());
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
this.logger.severe("connection.isClosed");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.