method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
d0d57463-b711-43aa-86e9-89bbe8cf280f | 4 | public InternetHeaders getControlHeaders ()
{
final InternetHeaders headers = new InternetHeaders();
headers.addHeader(_name.getField(), _name.getFieldValue());
headers.addHeader(_version.getField(), _version.getFieldValue());
headers.addHeader(_section.getField(), _section.getFieldValue());
headers.addHeader(_priority.getField(), _priority.getFieldValue());
headers.addHeader(_architecture.getField(), _architecture.getFieldValue());
if (_dependencies.size() > 0) {
headers.addHeader(_dependencies.getField(), _dependencies.getFieldValue());
}
if (_conflicts.size() > 0) {
headers.addHeader(_conflicts.getField(), _conflicts.getFieldValue());
}
if (_replacements.size() > 0) {
headers.addHeader(_replacements.getField(), _replacements.getFieldValue());
}
headers.addHeader(_maintainer.getField(), _maintainer.getFieldValue());
headers.addHeader(_description.getField(), _description.getFieldValue());
if(_source!=null) {
headers.addHeader(_source.getField(), _source.getFieldValue());
}
return headers;
} |
7d56611a-0604-4ce4-ac99-b8ccd169462a | 8 | public void Update() {
//the following all increase the speed as a key is pressed
// Calculating speed for moving up
if (Canvas.keyboardKeyState(KeyEvent.VK_W)) {
if (speedY >= TOP_SPEED * - 0.5) {
speedY -= speedAccelerating;
} else {
speedY += speedStopping;
}
}
// Calculating speed for moving down.
if (Canvas.keyboardKeyState(KeyEvent.VK_S)) {
if (speedY <= TOP_SPEED * 0.5) {
speedY += speedAccelerating;
} else {
speedY -= speedStopping;
}
}
// Calculating speed for moving or stopping to the left.
if (Canvas.keyboardKeyState(KeyEvent.VK_A)) {
speedX -= speedAccelerating;
} else if (speedX < 0) {
speedX += speedStopping;
}
// Calculating speed for moving or stopping to the right.
if (Canvas.keyboardKeyState(KeyEvent.VK_D)) {
speedX += speedAccelerating;
} //if no keys are being press slow the car
else if (speedX > 0) {
speedX -= speedStopping;
}
// Moves the car.
x += speedX;
y += speedY;
} |
2c92cfc9-4b86-41b4-a36b-55cc4dc41942 | 5 | double getCharge() {
double result = 0;
switch (getMovie().getPriceCode()) {
case Movie.REGULAR:
result += 2;
if (getDaysRented() > 2)
result += (getDaysRented() - 2) * 1.5;
break;
case Movie.NEW_RELEASE:
result += getDaysRented() * 3;
break;
case Movie.CHILDRENS:
result += 1.5;
if (getDaysRented() > 3)
result += (getDaysRented() - 3) * 1.5;
break;
}
return result;
} |
db1786d5-09a1-42fa-8737-cc3f9c1ccf0c | 3 | public static String encrypt(final String text) {
String encryptedText = null;
TripleDesCipher cipher = new TripleDesCipher();
cipher.setKey("GWT_DES_KEY_16_BYTES".getBytes());
try {
encryptedText = cipher.encrypt(String.valueOf(text));
} catch (DataLengthException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
} catch (IllegalStateException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
} catch (InvalidCipherTextException e1) {
e1.printStackTrace();
// Window.alert(e1.getMessage());
}
return encryptedText;
} |
e9db75a9-df6a-477f-90a2-61cde805c353 | 5 | @SuppressWarnings ("unchecked" )
public ReflectMethod( Method method )
{
Class<?>[] parameters = method.getParameterTypes();
int calculatedMaxSize = 0;
reflects = new Reflect[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
Reflect<Object> r = ReflectFactory.create( parameters[i] );
if (r == null)
{
throw new RuntimeException( "A Reflect implementation was not found for parameter: " + parameters[i] );
}
reflects[i] = r;
if (calculatedMaxSize != -1)
{
if (r.maxSize() == -1)
{
calculatedMaxSize = -1;
}
else
{
calculatedMaxSize += r.maxSize();
}
}
}
maxSize = calculatedMaxSize;
this.method = method;
} |
171c623d-2a80-4868-ac44-8b3e3735cffd | 1 | @Override
public boolean equals(Object o)
{
Point other = (Point)o;
return x==other.x && y==other.y;
} |
f12f11c9-5db4-4e5d-a204-d11494f2eb67 | 1 | private int getBowlScore(int[] bowl) {
int score = 0;
for (int i = 0; i < NFRUIT; i++) {
score += bowl[i] * mPreferences[i];
}
return score;
} |
b90b0aa3-d2eb-42f4-baf2-89a68acfd19b | 5 | public static double[] doLinearRegressionFromTo(int start,int end,double[][] args) //input int start, int end
{ //input double[1]=array of prices
double[] answer = new double[3];
int n = 0;
int numDays=end-start;
double[] x = new double[numDays];
double[] y = new double[numDays];
for(int i=0;i<numDays;i++){x[i]=args[0][i+start];}
for(int i=0;i<numDays;i++){y[i]=args[1][i+start];}
double sumx = 0.0, sumy = 0.0;
for(int i=0;i<x.length;i++) {
sumx += x[i];
sumy += y[i];
n++;
}
double xbar = sumx / n;
double ybar = sumy / n;
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
double beta1 = xybar / xxbar;
double beta0 = ybar - beta1 * xbar;
//System.out.println("y = " + beta1 + " * x + " + beta0);
double ssr = 0.0;
for (int i = 0; i < n; i++) {
double fit = beta1*x[i] + beta0;
ssr += (fit - ybar) * (fit - ybar);
}
double R2 = ssr / yybar;
//System.out.println("R^2 = " + R2);
answer[0]=beta1; //returns m(gradient)
answer[1]=beta0; //returns c(y-intercept)
answer[2]=R2; //returns R-squared
return answer;
} |
ca5ec8c6-bd91-4ea4-b646-9ec7deb4d802 | 6 | public void add(T element) {
// create a node for that element
Node z = new Node();
z.key = element;
Node y = null;
Node x = root; // the root
// loop while x is not null
while (x != null) {
// set y to x
y = x;
// compare the key of the element to be inserted with x
int compare = z.key.compareTo(x.key);
// if smaller we go in the left subtree
if (compare < 0) {
x = x.left;
} else {
// otherwise, it it is the same and we don,t allow
// multiple instances of the same item
if (compare == 0 && !allowSameElementMultipleTimes) {
return; // we don't add it
}
// otherwise go the right subtree
x = x.right;
}
}
// after the previous loop has terminated, we have found
// the place where the new node z should be inserted (as a child of y) so
// we will insert it there.
// we set the parent of z as y
z.parent = y;
if (y == null) { // case of an empty tree
root = z; // set z as the root
}// if z is small than y
else if (z.key.compareTo(y.key) < 0) {
// append as left child
y.left = z;
} else {
// otherwise append as right child
y.right = z;
}
// increase the number of elements in the tree
size++;
} |
fd3b38dd-842f-4d7e-90be-b8e748dc9033 | 2 | @Test
public void delMinReturnsCorrectOrderWithRandomInput() {
Random r = new Random();
int[] expected = new int[100];
for (int i = 0; i < 100; i++) {
int randomInteger = r.nextInt(5000);
h.insert(new Vertex(0, randomInteger));
expected[i] = randomInteger;
}
Arrays.sort(expected);
int[] actual = new int[100];
for (int i = 0; i < 100; i++) {
actual[i] = h.delMin().getDistance();
}
assertArrayEquals(expected, actual);
} |
68013397-8c4c-4250-8026-34a19b239a35 | 1 | public void doDelimitedWithPZMapErrors() {
try {
final String mapping = ConsoleMenu.getString("Mapping ", DelimitedWithPZMapErrors.getDefaultMapping());
final String data = ConsoleMenu.getString("Data ", DelimitedWithPZMapErrors.getDefaultDataFile());
DelimitedWithPZMapErrors.call(mapping, data);
} catch (final Exception e) {
e.printStackTrace();
}
} |
61a229a6-3140-4018-b4a9-fc9ba2fdac4e | 5 | @Override
public List<Membre> findAll() {
List<Membre> listM = new ArrayList<Membre>();
Statement st = null;
ResultSet rs = null;
try {
st = this.connect().createStatement();
rs = st.executeQuery("select * from Membre");
System.out.println("recherche général effectuée");
while (rs.next()) {
Membre mbr = new Membre(rs.getInt("id"), rs.getString("nom"), rs.getString("prenom"), rs.getString("mdp"), rs.getString("email"), rs.getString("status"));
listM.add(mbr);
}
} catch (SQLException ex) {
Logger.getLogger(MembreDao.class.getName()).log(Level.SEVERE, "recherche general echoué", ex);
}finally{
try {
if(rs != null)
rs.close();
if(st != null)
st.close();
} catch (SQLException ex) {
Logger.getLogger(MembreDao.class.getName()).log(Level.SEVERE, "liberation statement || resultset echoué", ex);
}
}
return listM;
} |
77294e04-9d16-4502-840c-16fb4af525d8 | 3 | @Override
public List<String> logInBuyer(String name, String passwd) {
loggerMediator.info("Log in buyer " + name);
List<String> serviceList;
stateMgr.setBuyerState();
serviceList = stateMgr.getServiceList(name);
if (serviceList!= null && !serviceList.isEmpty())
if (!logInUser(name, passwd, UserTypes.buyer, serviceList))
return null;
return serviceList;
} |
52cf570b-34f7-457e-9d43-e152d712e358 | 0 | public String getSector() {
return Sector;
} |
a77308d1-016c-43e2-86a4-43ee5e93ad56 | 2 | public boolean execGo(Direction d) {
Command c = new GoCommand(d);
if(c != null && c.execute()) {
saveGameState(c);
return true; //moved
}
return false; //not moved
} |
3a1bc069-b6e9-40f2-8c64-465af57c6809 | 0 | private String getName() {
return "RemoteServerConnection [" + name + ", Port: " + port + "]";
} |
1a8749ac-2a10-4ebc-97ab-8c151366d4c2 | 5 | private void tbListaClientesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbListaClientesKeyReleased
System.out.println("Clicando");
if(evt.getKeyCode() == KeyEvent.VK_SPACE ){
try {
concluido = true;
this.dispose();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "SELECIONE UM CLIENTE!");
}
}
if(evt.getKeyCode() == KeyEvent.VK_F5 ){
int x = modeloTabela.getRowCount();
for(int a = 0; a < x; a++){
modeloTabela.removeRow(0);
}
carregarTabela();
}
if(evt.getKeyCode() == KeyEvent.VK_ESCAPE ){
this.dispose();
}
}//GEN-LAST:event_tbListaClientesKeyReleased |
839657e1-bc63-46e2-9c6a-cbf82781cc29 | 9 | public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {
switch (ruleIndex) {
case 1: return statement_list_sempred((Statement_listContext)_localctx, predIndex);
case 8: return or_expression_sempred((Or_expressionContext)_localctx, predIndex);
case 9: return and_expression_sempred((And_expressionContext)_localctx, predIndex);
case 10: return equality_expression_sempred((Equality_expressionContext)_localctx, predIndex);
case 11: return relational_expression_sempred((Relational_expressionContext)_localctx, predIndex);
case 12: return additive_expression_sempred((Additive_expressionContext)_localctx, predIndex);
case 13: return multiplicative_expression_sempred((Multiplicative_expressionContext)_localctx, predIndex);
case 17: return postfix_expression_sempred((Postfix_expressionContext)_localctx, predIndex);
case 18: return expression_list_sempred((Expression_listContext)_localctx, predIndex);
}
return true;
} |
0655eed5-b202-4758-a841-a5e07197abad | 3 | private void chooseFile(final int whichFile) {
final JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(this);
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
if (whichFile == 1) {
targetBehaviorTxt.setText(fileChooser.getSelectedFile().getAbsolutePath());
} else if(whichFile == 2) {
templatesTxt.setText(fileChooser.getSelectedFile().getAbsolutePath());
} else {
outputFileTxt.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
} |
d778901c-0e97-462d-a24a-55e10466b70a | 6 | private void InitializeComponents()
{
//Window Settings
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Main Panel
pnlLobby = new JPanel(new GridLayout(1, 1));
pnlLobby.setBackground(Color.WHITE);
this.add(pnlLobby);
//List Games
lstGames = new List();
lstGames.setSize(250, 250);
pnlLobby.add(lstGames, BorderLayout.WEST);
//ButtonPanel
pnlButtons = new JPanel();
pnlButtons.setLayout(new BoxLayout(pnlButtons, BoxLayout.Y_AXIS));
pnlLobby.add(pnlButtons, BorderLayout.EAST);
//Button CreateGame / Cancel
btnCreateGame = new JButton("Create Game");
btnCreateGame.setSize(50, 250);
btnCreateGame.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(waitMode) {
try {
player.disconnect();
broadcastServer.stopServer();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
SetGUIMode(true);
}
else {
HostGame();
}
}
});
pnlButtons.add(btnCreateGame, BorderLayout.EAST);
//Button JoinGame
btnJoinGame = new JButton("Join Game");
btnJoinGame.setSize(50, 250);
btnJoinGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int index = lstGames.getSelectedIndex();
if(index<0)
return;
try {
JoinGame(gameList.get(index).getAddress());
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
});
pnlButtons.add(btnJoinGame, BorderLayout.EAST);
// Button Join Game Through IP
btnJoinGameIP = new JButton("Join Game Through IP");
btnJoinGameIP.setSize(50, 250);
btnJoinGameIP.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ip = JOptionPane.showInputDialog("Enter remote IP:");
if (ip != null){
try {
InetAddress adr = InetAddress.getByName(ip);
JoinGame(adr);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
});
pnlButtons.add(btnJoinGameIP, BorderLayout.EAST);
// Button Start Game with AI
btnJoinGameAI = new JButton("Start Game with AI");
btnJoinGameAI.setSize(50, 250);
btnJoinGameAI.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IClient oponent = new AI();
StartGame(oponent);
}
});
pnlButtons.add(btnJoinGameAI, BorderLayout.EAST);
// Button Refresh List
btnRefresh = new JButton("Refresh List using Broadcast");
btnRefresh.setSize(50, 250);
btnRefresh.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PerformBroadcast();
}
});
pnlButtons.add(btnRefresh, BorderLayout.SOUTH);
// Button Refresh List IP
btnRefreshIP = new JButton("Refresh List using IP Test");
btnRefreshIP.setSize(50, 250);
btnRefreshIP.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PerformIPTest();
}
});
pnlButtons.add(btnRefreshIP, BorderLayout.SOUTH);
//Set visibility
setVisible(true);
} |
6c0918e9-e74b-49c9-b7c8-1a17d3f48f27 | 5 | public static void doEverything(int size, float scale, final int initialDelay, final int generationGap, final int redrawGap, final AutomataSheet firstSheet)
{
final CellFrame frame = new CellFrame(firstSheet);
frame.setScale(scale);
frame.setVisible(true);
final Switch isRunning = new Switch(true);
final Thread genThread = new Thread()
{
public void run()
{
AutomataSheet sheet = firstSheet;
justSleep(initialDelay);
while (isRunning.mValue)
{
justSleep(generationGap);
sheet = sheet.getNextGeneration();
frame.setCellSheet(sheet);
}
}
public void justSleep(long time)
{
try
{
sleep(time);
}
catch (InterruptedException e) {}
}
};
genThread.setDaemon(true);
genThread.start();
final Thread drawThread = new Thread()
{
public void run()
{
while (isRunning.mValue)
{
try
{
sleep(redrawGap);
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
frame.repaint();
}
});
}
catch (InterruptedException e) {}
catch (InvocationTargetException e) {}
}
}
};
drawThread.setDaemon(true);
drawThread.start();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
isRunning.mValue = false;
System.exit(0);
}
});
} |
399c45d3-7866-4c68-b142-4814c5e2c309 | 9 | private static void addAlterStatistics(final PrintWriter writer,
final PgTable oldTable, final PgTable newTable,
final SearchPathHelper searchPathHelper) {
@SuppressWarnings("CollectionWithoutInitialCapacity")
final Map<String, Integer> stats = new HashMap<String, Integer>();
for (final PgColumn newColumn : newTable.getColumns()) {
final PgColumn oldColumn = oldTable.getColumn(newColumn.getName());
if (oldColumn != null) {
final Integer oldStat = oldColumn.getStatistics();
final Integer newStat = newColumn.getStatistics();
Integer newStatValue = null;
if (newStat != null && (oldStat == null
|| !newStat.equals(oldStat))) {
newStatValue = newStat;
} else if (oldStat != null && newStat == null) {
newStatValue = Integer.valueOf(-1);
}
if (newStatValue != null) {
stats.put(newColumn.getName(), newStatValue);
}
}
}
for (final Map.Entry<String, Integer> entry : stats.entrySet()) {
searchPathHelper.outputSearchPath(writer);
writer.println();
writer.print("ALTER TABLE ONLY ");
writer.print(PgDiffUtils.getQuotedName(newTable.getName()));
writer.print(" ALTER COLUMN ");
writer.print(PgDiffUtils.getQuotedName(entry.getKey()));
writer.print(" SET STATISTICS ");
writer.print(entry.getValue());
writer.println(';');
}
} |
18e9abec-6c57-4175-a9f6-ec51c3a6f427 | 1 | @Override
public void run() {
for (int i = 0; i < COUNT; i++) {
System.out.println("Loop:" + name + ", iteration:" + i + ".");
}
} |
b05abf91-c29f-4acd-b22c-621decd68e44 | 7 | @RequestMapping(method = RequestMethod.GET)
public String generalTree(ModelMap map) {
if (Feat.getFeats().isEmpty()) {
Feat.loadFromSQL();
}
ArrayList<FeatNode> nodes = new ArrayList<FeatNode>();
int count = 0;
if (FeatNode.getNodes().isEmpty()) {
for (Feat f : Feat.getFeats().values()) {
if (f.getRequiredFeats().isEmpty()) {
System.out.println("Making node for " + f.getName());
if (!FeatNode.getContainedFeats().contains(f.getId())) {
nodes.add(new FeatNode(f.getId()));
count++;
}
}
}
} else {
nodes.addAll(FeatNode.getNodes().values());
}
System.out.println(count + " == " + nodes.size() + " == " + FeatNode.getNodes().values().size());
for (int i = 0; i < nodes.size(); i++) {
if (!nodes.get(i).getParents().isEmpty()) {
System.out.println(Feat.getFeats().get(nodes.get(i).getFeat()).getName());
nodes.remove(i);
}
}
System.out.println(nodes.size());
map.addAttribute("nodeArr", nodes);
return "tree";
} |
a47ef82f-0995-48c5-a9b9-a59119141e12 | 5 | public static boolean selectItem(final int index) {
if (index < 0)
return false;
WidgetChild[] boxes = getList(BOX_LIST);
return getCurrentIndex() == index || index < boxes.length && boxes[index].getTextureId() != -1
&& boxes[index].click(true) && new TimedCondition(1400) {
@Override
public boolean isDone() {
return getCurrentIndex() == index;
}
}.waitStop();
} |
62f04f8a-584e-482b-9477-b1a0b218adbc | 1 | public void updateUI()
{
super.updateUI();
if (titleLabel != null) {
updateHeader();
}
} |
3a47822d-81bb-4a8b-9128-0ab2fe93f164 | 0 | @Test
public void EnsurePathIsParsedCorrectly() {
Path path = new Path("alan/likes/warbyparker");
String patharray[] = path.getPathArray();
assertEquals(3, patharray.length);
assertEquals("alan", patharray[0]);
assertEquals("likes", patharray[1]);
assertEquals("warbyparker", patharray[2]);
} |
87b4a153-a110-4d82-8fb3-173c91c910e2 | 8 | private HashSet<String> getMatchesOutputSet(Vector<String> tagSet, String baseURL) {
HashSet<String> retSet=new HashSet<String>();
Iterator<String> vIter=tagSet.iterator();
while (vIter.hasNext()) {
String thisCheckPiece=vIter.next();
Iterator<Pattern> pIter=patternSet.iterator();
boolean hasAdded=false;
while (!hasAdded && pIter.hasNext()) {
Pattern thisPattern=pIter.next();
Matcher matcher=thisPattern.matcher(thisCheckPiece);
if (matcher.find() && (matcher.groupCount() > 0)) {
String thisMatch=getNormalizedContentURL(baseURL, matcher.group(1));
if (HTTP_START_PATTERN.matcher(thisMatch).matches()) {
if (!retSet.contains(thisMatch) && !baseURL.equals(thisMatch)) {
retSet.add(thisMatch);
hasAdded=true;
} // end if (!retSet.contains(thisMatch))
} // end if (HTTP_START_PATTERN.matcher(thisMatch).matches())
} // end if (matcher.find() && (matcher.groupCount() > 0))
matcher.reset();
} // end while (!hasAdded && pIter.hasNext())
} // end while (vIter.hasNext())
return retSet;
} |
d380f2a1-fb21-48e3-b8c1-eb8a3dc22b5d | 6 | @Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
JButton buton;
switch (action) {
case "enviar":
AudioChatService.escribirMensaje();
break;
case "cambiarNombre":
AudioChatService.cambiarNombre();
break;
case "cambiarNombreCanal":
AudioChatService.cambiarNombreCanal();
break;
case "crearSubCanal":
AudioChatService.crearSubCanal();
break;
case "grabar":
buton = (JButton) e.getSource();
buton.setText("Parar");
buton.setActionCommand("parar");
Grabador.grabar();
break;
case "parar":
buton = (JButton) e.getSource();
buton.setText("Grabar");
buton.setActionCommand("grabar");
AudioChatService.setFile(Grabador.endGrabar());
AudioChatService.enviarAudio();
break;
default:
break;
}
} |
0ac83580-1491-4f1f-ba8f-869c0b4753b7 | 2 | private void setRange(Range newRange) {
if (range != null) {
range.clearDisplay();
}
range = newRange;
if (range != null) {
range.display();
}
} |
c72e236c-0217-42e2-84e7-1d9c92095ca1 | 3 | public int findEstimate(int k) {
for (int i = 0; i < msgs.length; i++) {
if (msgs[i] != null) {
if (msgs[i].getDeltaP()[k] != -1) {
return msgs[i].getDeltaP()[k];
}
}
}
return -1;
} |
bff470cc-fda8-4352-81bb-b2cd86b46090 | 7 | @Override
public void computeFitness() {
this.fitness = 0.0;
AiInterface opponent = MinichessBeatRandCreature.globalRandomAi;
boolean playAsWhite = GPConfig.getRandGen().nextBoolean();
int numOpponents = GPConfig.getTournySize() - 1;
for (int i = 0; i < numOpponents; i++) {
COLOR winner = null;
if (playAsWhite) {
winner = SimplePlay.playGame(this.myMinichessAi, opponent);
}
else {
winner = SimplePlay.playGame(opponent, this.myMinichessAi);
}
if (winner == null)
continue;
else if (playAsWhite && winner==COLOR.WHITE)
fitness+=1.0;
else if (!playAsWhite && winner == COLOR.BLACK)
fitness+=1.0;
else
fitness-=1.0;
}
this.p_isFitnessValid = true;
} |
0b312c27-3dc2-4388-b752-de3422efb051 | 2 | private static String mangle(String nm) {
StringBuilder buf = new StringBuilder();
for(int i = 0; i < nm.length(); i++) {
char c = nm.charAt(i);
if(c == '/')
buf.append("_");
else
buf.append(c);
}
return(buf.toString());
} |
a51b8d71-883f-45c9-9a9a-6e97cdf5a3cd | 2 | private static String getTime(String time) {
time = time.split(" ")[3];
time = (Integer.parseInt(time.split(":")[0]) > 12 ? Integer.parseInt(time.split(":")[0])-12 : time.split(":")[0]) + ":" +time.split(":")[1]
+(Integer.parseInt(time.split(":")[0]) > 12 ? " PM" : " AM");
return time;
} |
e8a0ba54-e989-42d8-94dc-fd3fa70860bf | 6 | private void convertRGBtoHSV() {
float r;
float g;
float b;
float max, min;
float hsv[] = new float[3];
float delta;
for (int i = 0; i < imageSize; i++) {
r = redPixel[i];
g = greenPixel[i];
b = bluePixel[i];
r /= 255.0f;
g /= 255.0f;
b /= 255.0f;
max = Math.max(Math.max(r, g), b);
min = Math.min(Math.min(r, g), b);
delta = max - min;
hsv[2] = max;
hsv[1] = (max == 0.0f) ? 0.0f : delta / max;
if (r == max) {
hsv[0] = 60.0f * (g - b) / delta + (g < b ? 6 : 0);
} else if (g == max) {
hsv[0] = 60.0f * (b - r) / delta + 2;
} else {
hsv[0] = 60.0f * (r - g) / delta + 4;
}
if (hsv[0] < 0.0f) {
hsv[0] += 360.0f;
}
// hsv = Color.RGBtoHSB(Math.round(r), Math.round(g), Math.round(b), hsv);
hsvPixel[i] = Color.getHSBColor(hsv[0], hsv[1], hsv[2]).getRGB();
huePixel[i] = (hsvPixel[i] >> 16) & 0xFF;
saturationPixel[i] = (hsvPixel[i] >> 8) & 0xFF;
brightnessPixel[i] = hsvPixel[i] & 0xFF;
}
} |
f1f93991-a0a6-4175-82b4-9523b734d1ff | 2 | private void setUpLabelImage(JLabel label, String image, int width, int height){
BufferedImage titleImage;
try{
if(bookLayout == 1){
titleImage = ImageIO.read(new File("resources/buttons/"+image));
}
else{
titleImage = ImageIO.read(new File("resources/buttons" +bookLayout + "/"+image));
}
Image scaledButton = titleImage.getScaledInstance(width,height,java.awt.Image.SCALE_SMOOTH);
label.setIcon(new ImageIcon(scaledButton));
}catch (IOException ex){
}
} |
e786c3fe-d86a-43ba-9b0a-d763e8be361a | 8 | private void readExcludedPackages() {
fExcluded= new Vector(10);
for (int i= 0; i < defaultExclusions.length; i++)
fExcluded.addElement(defaultExclusions[i]);
InputStream is= getClass().getResourceAsStream(EXCLUDED_FILE);
if (is == null)
return;
Properties p= new Properties();
try {
p.load(is);
}
catch (IOException e) {
return;
} finally {
try {
is.close();
} catch (IOException e) {
}
}
for (Enumeration e= p.propertyNames(); e.hasMoreElements(); ) {
String key= (String)e.nextElement();
if (key.startsWith("excluded.")) {
String path= p.getProperty(key);
path= path.trim();
if (path.endsWith("*"))
path= path.substring(0, path.length()-1);
if (path.length() > 0)
fExcluded.addElement(path);
}
}
} |
5c60737a-4313-4975-80a5-5510af906cdc | 1 | public
JobMaster (JobType whatToDo, AbstractPage rootPage, int threadsNumber) {
if (threadsNumber <= 0)
threadsNumber = CORETHREADS_NUMBER;
executor = Executors.newFixedThreadPool(threadsNumber);
assert (executor instanceof ThreadPoolExecutor);
submittedPairs = new ConcurrentLinkedQueue<>();
this.whatToDo = whatToDo;
this.rootPage = rootPage;
} |
cfa4b079-8530-4de3-ba63-811d3dbc234c | 0 | public void pidWrite(double output) {
set(output);
} |
5da15ba1-3bf6-4e23-bc77-d65ccc5cb815 | 5 | public void transceive() throws IOException {
String received;
br = new BufferedReader(new InputStreamReader(newSS.getInputStream()));
received = br.readLine();
String[] temp;
PrintWriter pw = new PrintWriter(newSS.getOutputStream(), true);
switch (received.charAt(0)) {
case ('1'):
pw.println(imdb.getAssociatedJournals(doctor, division));
pw.flush();
break;
case ('2'):
temp = received.split("!");
pw.println(imdb.getJournal(temp[1], doctor, division));
pw.flush();
break;
case ('3'):
temp = received.split("!");
pw.println(imdb.appendToText(doctor, temp[1], temp[2]));
pw.flush();
break;
case ('4'):
temp = received.split("!");
String mess = imdb.addJournal(temp[1], doctor, temp[3], division,
temp[2]);
pw.println(mess);
break;
case ('5'):
temp = received.split("!");
pw.println(imdb.deleteJournal(temp[1], doctor));
pw.flush();
break;
}
} |
a6a78332-3344-4980-aa73-ac6e2cf60832 | 3 | protected Resources() {
this.bagFields = new HashSet<Field>();
for (Field f : getClass().getFields()) {
if (Modifier.isPublic(f.getModifiers()) && ResourceBag.class.isAssignableFrom(f.getType())) {
this.bagFields.add(f);
}
}
} |
92e326e4-d770-491d-996e-20d2a96e56c4 | 7 | public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Type gameboard config:");
String input = keyboard.nextLine();
Game game = new Game(input);
System.out.println("Game initialized");
System.out.println();
System.out.println("Use the following keys to move the EMPTY token:");
System.out.println("- 'w' for UP");
System.out.println("- 'a' for LEFT");
System.out.println("- 's' for DOWN");
System.out.println("- 'd' for RIGHT");
System.out.println();
System.out.println("Type 'q' to quit");
System.out.println();
// Loop infinitely
while(true) {
// Print gameboard
game.displayState();
System.out.println(game.getHistory());
System.out.println(game.getMoveHistory());
// Get input
input = keyboard.nextLine();
System.out.println();
try {
// Process input
switch(input) {
case "w":
game.move(Direction.UP);
break;
case "a":
game.move(Direction.LEFT);
break;
case "s":
game.move(Direction.DOWN);
break;
case "d":
game.move(Direction.RIGHT);
break;
case "q":
System.exit(0);
break;
default:
System.out.println("Input not understood.");
}
}
// Catch invalid input
catch(InvalidMoveException e) {
System.out.println("Invalid move! " + e);
}
// Print a blank line
System.out.println();
}
} |
96042a5f-27a8-4b57-b278-bf82ef84d313 | 2 | public Markers randomIntervals(int numIntervals, int maxStart, int maxLength, int numChromo) {
Markers ints = new Markers();
for (int ch = 1; ch <= numChromo; ch++) {
for (int i = 0; i < numIntervals; i++) {
int start = rand.nextInt(maxStart);
int end = Math.min(start + rand.nextInt(maxLength), maxStart - 1);
Marker interval = new Marker(genome.getChromosome("" + ch), start, end, 1, "");
ints.add(interval);
}
}
return ints;
} |
953133e7-2d94-4585-b415-14714525dcfe | 5 | public boolean step()
{
board[knight.y][knight.x] = VISITED;
Point[] possibleMoves = getPossibleMoves(knight.x, knight.y);
Random random = new Random(System.nanoTime());
if (possibleMoves.length > 0)
{
Point nextMove = possibleMoves[0];
int numOfPossibleMoves = getNumberOfPossibleMoves(nextMove.x, nextMove.y);
for (int i = 1, length = possibleMoves.length; i < length; i++)
{
int nextNumOfPossibleMoves = getNumberOfPossibleMoves(possibleMoves[i].x, possibleMoves[i].y);
if (nextNumOfPossibleMoves < numOfPossibleMoves)
{
nextMove = possibleMoves[i];
numOfPossibleMoves = nextNumOfPossibleMoves;
}
else if (nextNumOfPossibleMoves == numOfPossibleMoves)
{
nextMove = random.nextBoolean() ? possibleMoves[i] : nextMove;
random.setSeed(System.nanoTime());
}
}
knight.setLocation(nextMove);
squaresVisited++;
return true;
}
else
return false;
} |
45639509-b1f1-43b2-bbba-3a85541fc3a9 | 2 | private Position getTertiaryPowerFailurePosition(Position secondaryPos, int directionInt) {
// Calculate T1 Position
final Position squareOne = (Direction.values()[directionInt]).newPosition(secondaryPos);
// Calculate T2 Position
final int dirIntTwo = (directionInt - 1 < 0) ? Direction.values().length - 1 : directionInt - 1;
final Position squareTwo = (Direction.values()[dirIntTwo]).newPosition(secondaryPos);
// Calculate T3 Position
final int dirIntThree = (directionInt + 1 > Direction.values().length - 1) ? 0 : directionInt + 1;
final Position squareThree = (Direction.values()[dirIntThree]).newPosition(secondaryPos);
// Put T1, T2 and T3 in Position List
List<Position> common = new ArrayList<Position>();
common.add(squareOne);
common.add(squareTwo);
common.add(squareThree);
// Get Random Position of T1, T2 and T3
final Random random = new Random();
final int randomIndex = random.nextInt(common.size());
// Return the Random Position
return common.get(randomIndex);
} |
273f5792-9325-4d8c-b8ac-d7ce17589fc5 | 4 | public void visitIf(If node, String args){
pp(indent() + (args.compareTo("elsif") == 0 ? "ELSIF " : "IF "), node.getStyle());
node.getCond().accept(this, args);
pp(" THEN\n", node.getStyle());
n++;
node.getIfBlock().accept(this, args);
n--;
if (node.getElseBlock() != null) {
if(node.getElseBlock().getCond() != null) {
node.getElseBlock().accept(this, "elsif");
}
else {
pp(indent() + "ELSE\n", node.getStyle());
n++;
node.getElseBlock().getIfBlock().accept(this, args);
n--;
}
}
if(args.compareTo("elsif") != 0) {
pp(indent() + "END", node.getStyle());
//pp(";");
}
} |
b3bd7655-d483-435e-bdad-89cb0323cfbb | 5 | public static SwagStack stringToSwagStack(String swagString) {
String[] swagPieces = swagString.split(",");
SwagStack swagStack = new SwagStack(Integer.valueOf(swagPieces[0]));
if (!swagPieces[1].equals("0")) {
if (swagPieces[1].contains("-")) {
String[] dmg = swagPieces[1].split("-");
swagStack.setMinDmg(Short.valueOf(dmg[0]));
swagStack.setMaxDmg(Short.valueOf(dmg[1]));
} else {
swagStack.setMinDmg(Short.valueOf(swagPieces[1]));
swagStack.setMaxDmg(Short.valueOf(swagPieces[1]));
}
}
if (swagPieces[2].contains("-")) {
String[] amnt = swagPieces[2].split("-");
swagStack.setMinAmnt(Integer.valueOf(amnt[0]));
swagStack.setMaxAmnt(Integer.valueOf(amnt[1]));
} else {
swagStack.setMinAmnt(Integer.valueOf(swagPieces[2]));
swagStack.setMaxAmnt(Integer.valueOf(swagPieces[2]));
}
if (!swagPieces[3].equals("0")) {
Map<Enchantment, Integer> enchantMap = new HashMap<Enchantment, Integer>();
String[] enchants = swagPieces[3].split("&");
for (String enchant : enchants) {
String[] fullEnchant = enchant.split("#");
enchantMap.put(Enchantment.getById(Integer.valueOf(fullEnchant[0])), Integer.valueOf(fullEnchant[1]));
}
swagStack.setEnchants(enchantMap);
}
return swagStack;
} |
67b9c153-e9f9-46a0-9872-49d018361a76 | 2 | @Override
public void execute() {
long next;
synchronized (this) {
while (frequence.addAndGet(0) <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
next = System.currentTimeMillis() + 1000 / frequence.get();
getSimulateur().actionPerformed(null, 1, maVoie, VoieEnum.ALEAT);
asleep(next - System.currentTimeMillis());
} |
4d1e2624-3afb-44c3-b76f-b5606c3a8c5b | 4 | private void startDialog() {
isRunning = true;
checkFiles(); //Checks if all Data directories exist.
dmPhase = new DMPhase(); //Creates the DMPhase, which loads all data
//Goes through the StartDialog.
do {
phase.setPhaseResult(this);
phase = phase.nextPhase(this);
} while(!userLoggedIn && isRunning);
if (userLoggedIn && isRunning) {
return;
}
else {
isRunning = true;
userLoggedIn = false;
return;
}
} |
c030296a-f828-42a2-9877-ed3d156701b4 | 3 | public void busquedaDesordenada(T x){
Nodo<T> q = this.p;
while(q.getLiga() != null && q.getValor() != x){
q = q.getLiga();
}
if(q == null){
System.out.println("No se encontro el valor");
}else{
System.out.println("Se encontro el valor dentro de la lista");
}
} |
6aca040e-3779-4565-9caa-ab6ded5b5f64 | 8 | @Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if(command.getName().equalsIgnoreCase("fchat")){
Player player = null;
if(sender instanceof Player)
player = (Player) sender;
if(player != null){
if(!plugin.hasPermission(player, "default")){
Util.sendMessageNoPerms(sender);
return true;
}
}
if(player == null){
Util.sendMessageNotPlayer(sender);
return true;
}
//Make sure this isnt null!!! small chance but it could happen
Friend friendPlayer = plugin.friendManager.getFriend(player);
if(args.length == 0){
if(friendPlayer == null) return false;
if(friendPlayer.isInFriendChat())
sender.sendMessage(Util.formatMessage(ChatColor.DARK_AQUA + "You no longer in friends chat."));
else
sender.sendMessage(Util.formatMessage(ChatColor.DARK_AQUA + "You are now in friends chat."));
friendPlayer.setInFriendChat(!friendPlayer.isInFriendChat());
return true;
}
return false;
}
return false;
} |
4fe13945-c3d0-4de7-9009-ce4328fcdb55 | 6 | private void nextTurn() {
// Used to switch turns. Called each time a valid move is made.
if (hasWon(turn)) { // Check to see if the move the current player made was a winning move.
gameOver = true; // If it was, then set gameOver to true;
sendWin(turn); // Also, display a window informing the user(s) of what occured. Also shows scores.
return; // Exit this method. Nothing left to do.
}
if (allFull()) { // If there are no moves left, and the last players move wasn't a winning one...
gameOver = true; // The game is over
sendDraw(); // Call the method that creates a frame informing the user(s) of the draw. Also shows scores.
return; // Exit this method. Nothing left to do.
}
turn = turn.getOpposite(); // Switch turns.
if (aiTurn && AI) {
aiTurn = false;
} else if (!aiTurn && AI) {
aiTurn = true;
GAME_AI.aiMove();
} else {
aiTurn = false;
}
} |
5ef3e096-50a0-4c62-9597-f0180c679894 | 7 | public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String pathName = args[0]; // takes in the path name from the command line
File ipAddresses = new File(pathName);
Scanner input = new Scanner(ipAddresses);
MyCountingLinkedLists<String> list = new MyCountingLinkedLists<String>();
while (input.hasNextLine()) { // Reads in the input
String ipAddress = input.nextLine();
list.add(ipAddress);
}
System.out.println("How would you like the list to be printed?"); //count or percentage
System.out.println("If you would like the count to be printed with percentages, enter 0.");
System.out.println("If you would like the count to be printed with the actual count, enter 1");
Scanner userInput = new Scanner(System.in);
int indicator = userInput.nextInt();
while (indicator != 0 && indicator != 1) {
System.out.println("You didn't enter a valid choice.");
System.out.println("If you would like the count to be printed with percentages, enter 0.");
System.out.println("If you would like the count to be printed with the actual count, enter 1");
indicator = userInput.nextInt();
}
System.out // certain number of elements or all elements
.println("Would you like the whole list to be printed or just a certain number of elements?");
System.out.println("If you would like a certain number to be printed, please enter the number. The number must be greater than zero and less then "+ list.size() + ".");
System.out.println("If you would like the whole list to be printed, please enter "+ list.size() + ".");
int number = userInput.nextInt();
while (number < 1 && number > list.size()) {
System.out.println("You didn't enter a valid number.");
System.out.println("If you would like a certain number to be printed, please enter the number. The number must be greater than zero and less then "+ list.size() + ".");
System.out.println("If you would like the whole list to be printed, please enter "+ list.size() + ".");
number = userInput.nextInt();
}
list.sort(); // SORTS THE LIST USING THE BUBBLE SORT TECHNIQUE, EXTRA CREDIT
list.printList(indicator, number); // prints the list
list.reverseList(); //reverses the list
System.out.println(" ");
System.out.println("The list in revers is: ");
list.printList(indicator, number); // prints out the reversed list
}
catch (IOException e) // tells the user that file inputed is not valid
{
System.out.println("Please try again with a valid file path. Try again.");
}
catch (ArrayIndexOutOfBoundsException e) // tell the user that he hasn't
// given enough information
{
System.out.println("You must give me the file path, and NOTHING else.Try again.");
}
} |
cb342a5c-4e2b-4c74-baec-f9c9cbdf4d86 | 1 | public boolean isEnded() {
if (endedInt == "1") {
return true;
} else {
return false;
}
} |
67224b39-5dd1-4bcf-bc0a-0e9a0f9e0790 | 4 | @Override
public void run() {
while (true) {
try {
UpdChecker checker = new UpdChecker();
Map<String, String> updates = checker.check();
if (updates.size() > 0) {
//SMS sending quantity of new entries at slando.ua
Smsc sms = new Smsc();
//Output to the mobile phone:
// sms.send_sms("380952069486", "You got " + updates.size() + " new ads at slando.ua!", 1, "", "", 0, "", "");
//Output to the screen:
System.out.println("You got " + updates.size() + " new ads at slando.ua!");
}
Thread.sleep(60000);
} catch (IOException ex) {
Logger.getLogger(Notificator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Notificator.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
8e1b5423-7157-45d8-a143-e3f2c83c8cd6 | 0 | public IrcClient(AprilonIrc plugin, String name) { this.Parent = plugin; this.Name = name; } |
06dd8408-d0a0-4f9a-abfc-3cbe161e2a10 | 7 | public boolean insertEntry(String name, String file)
{
System.out.println(this.getClass().toString()+"::insertEntry("+name+","+file+")");
fileName = makeSQLCompatible(file);
// if file already in list, stop
if(getIndexOf(file) != -1)return true;
//System.out.println("In insert: args = " + name + ": " + file);
Mp3File mp3file = null;
try {
mp3file = new Mp3File(file);
if (mp3file.hasId3v1Tag())
{
ID3v1 id3v1 = mp3file.getId3v1Tag();
title = makeSQLCompatible(id3v1.getTitle());
artist = makeSQLCompatible(id3v1.getArtist());
album = makeSQLCompatible(id3v1.getAlbum());
genre = makeSQLCompatible(id3v1.getGenreDescription());
release = makeSQLCompatible(id3v1.getYear());
comment = makeSQLCompatible(id3v1.getComment());
}// end if
else if(mp3file.hasId3v2Tag())
{
ID3v2 id3v2 = mp3file.getId3v2Tag();
title = makeSQLCompatible(id3v2.getTitle());
artist = makeSQLCompatible(id3v2.getArtist());
album = makeSQLCompatible(id3v2.getAlbum());
genre = makeSQLCompatible(id3v2.getGenreDescription());
release = makeSQLCompatible(id3v2.getYear());
comment = makeSQLCompatible(id3v2.getComment());
}//end elseif
duration = mp3file.getLengthInMilliseconds();
duration_str = convertMilliSeconds(duration);
//System.out.println("insert into " + name + " values ('" + title + "','" + artist + "','" + album +"','"+ genre + "'," +duration + ",'" + file + "')");
} catch (UnsupportedTagException e1) {
// tag can't be read
// alert user that song can't be added to playlist
System.out.println("UnsupportedTagException");
return false;
} catch (InvalidDataException e1) {
// unsupported format
// alert user to invalid file
System.out.println("InvalidDataException");
return false;
} catch (IOException e1) {
// file not found
System.out.println("IOException");
return false;
//e1.printStackTrace();
}
try {
stmt = conn.createStatement();
//System.out.println("insert into " + name + " values ('" + title + "','" + artist + "','" + album +"','"+ genre + "',"+"'"+release+"','"+comment+"','"+duration_str+"'," +duration + ",'" + fileName + "')");
//stmt.execute("insert into " + name + " values ('" + title + "','" + artist + "','" + album +"','"+ genre + "'," +duration + ",'" + fileName + "')");
stmt.execute("insert into " + name + " values ('" + title + "','" + artist + "','" + album +"','"+ genre + "',"+"'"+duration_str+"','"+release+"','"+comment+"'," +duration + ",'" + fileName + "')");
//System.out.println("insert into " + name + " values ('" + title + "','" + artist + "','" + album +"','"+ genre + "'," +duration + ",'" + file + "')");
stmt.close();
//updateUI(name);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
return true;
}
fireDataBaseEvent(fileName,"insert");
return true;
} |
1fa3d9d2-eedf-4622-b108-16768c93ea96 | 3 | public Iterator getDictKeys() throws IOException {
if (type == INDIRECT) {
return dereference().getDictKeys();
} else if (type == DICTIONARY || type == STREAM) {
return ((HashMap) value).keySet().iterator();
}
// wrong type
return new ArrayList().iterator();
} |
83305869-1088-4b30-a963-7c54dd937464 | 9 | protected void actionPerformed(GuiButton par1GuiButton)
{
if (!par1GuiButton.enabled)
{
return;
}
if (par1GuiButton.id == 5)
{
if (Minecraft.getOs() == EnumOS.MACOS)
{
try
{
System.out.println(fileLocation);
Runtime.getRuntime().exec(new String[]
{
"/usr/bin/open", fileLocation
});
return;
}
catch (IOException ioexception)
{
ioexception.printStackTrace();
}
}
else if (Minecraft.getOs() == EnumOS.WINDOWS)
{
String s = String.format("cmd.exe /C start \"Open file\" \"%s\"", new Object[]
{
fileLocation
});
try
{
Runtime.getRuntime().exec(s);
return;
}
catch (IOException ioexception1)
{
ioexception1.printStackTrace();
}
}
boolean flag = false;
try
{
Class class1 = Class.forName("java.awt.Desktop");
Object obj = class1.getMethod("getDesktop", new Class[0]).invoke(null, new Object[0]);
class1.getMethod("browse", new Class[]
{
java.net.URI.class
}).invoke(obj, new Object[]
{
(new File(Minecraft.getMinecraftDir(), "texturepacks")).toURI()
});
}
catch (Throwable throwable)
{
throwable.printStackTrace();
flag = true;
}
if (flag)
{
System.out.println("Opening via system class!");
Sys.openURL((new StringBuilder()).append("file://").append(fileLocation).toString());
}
}
else if (par1GuiButton.id == 6)
{
mc.renderEngine.refreshTextures();
mc.displayGuiScreen(guiScreen);
}
else
{
guiTexturePackSlot.actionPerformed(par1GuiButton);
}
} |
10935acb-dc2c-4859-9524-a1e023ec1c11 | 6 | public void handleShading(int intensity, int falloff, int lightX,
int lightY, int lightZ) {
for (int triangle = 0; triangle < triangleCount; triangle++) {
int x = triangleX[triangle];
int y = triangleY[triangle];
int z = triangleZ[triangle];
if (triangleDrawType == null) {
int colour = triangleColours[triangle];
VertexNormal vertexNormal = super.vertexNormals[x];
int lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLA[triangle] = mixLightness(colour, lightness, 0);
vertexNormal = super.vertexNormals[y];
lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLB[triangle] = mixLightness(colour, lightness, 0);
vertexNormal = super.vertexNormals[z];
lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLC[triangle] = mixLightness(colour, lightness, 0);
} else if ((triangleDrawType[triangle] & 1) == 0) {
int colour = triangleColours[triangle];
int drawType = triangleDrawType[triangle];
VertexNormal vertexNormal = super.vertexNormals[x];
int lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLA[triangle] = mixLightness(colour, lightness,
drawType);
vertexNormal = super.vertexNormals[y];
lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLB[triangle] = mixLightness(colour, lightness,
drawType);
vertexNormal = super.vertexNormals[z];
lightness = intensity
+ (lightX * vertexNormal.x + lightY * vertexNormal.y + lightZ
* vertexNormal.z)
/ (falloff * vertexNormal.magnitude);
triangleHSLC[triangle] = mixLightness(colour, lightness,
drawType);
}
}
super.vertexNormals = null;
vertexNormalOffset = null;
vertexSkins = null;
triangleSkins = null;
if (triangleDrawType != null) {
for (int triangle = 0; triangle < triangleCount; triangle++)
if ((triangleDrawType[triangle] & 2) == 2)
return;
}
triangleColours = null;
} |
c6a96b1f-a161-46b3-b890-e6b01bac725a | 5 | public static void maxHeapify(int[] A, int i, int heapSize){
int left = 2 * i + 1;
int right = 2 * i + 2;
//find the largest in A[i],A[left],A[right]
int largest = i;
if(left < heapSize && A[left] > A[largest]){
largest = left;
}
if(right < heapSize && A[right] > A[largest]){
largest = right;
}
if(largest != i){
//exchange A[i] and A[largest]
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
maxHeapify(A,largest,heapSize);
}
} |
4914d8d1-34a0-4955-a7a4-c46745763b1d | 2 | public static void main(String[] args) {
String fullQuanlifiedFileName ="D:\\MyEclipseGen.java";
// "src/com/xin/A.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try {
FileOutputStream err = new FileOutputStream("D:\\err.txt");
int compilationResult = compiler.run(null, null, err, fullQuanlifiedFileName);
if(compilationResult == 0){
System.out.println("Done");
} else {
System.out.println("Fail");
}
} catch (Exception e) {
// TODO: handle exception
}
} |
54b3746a-8469-4a78-ad95-b2e0c823e165 | 4 | private boolean normal(Publish p) {
boolean sent = false;
List<SubscriberParent> list = p.mapping.get(p.message.getClass());
if (list == null) {
return false;
}
for (SubscriberParent sp : list) {
Subscriber<?> s = sp.getSubscriber();
if (!predicateApplies(s, p.message)) {
continue;
}
s.receiveO(p.message);
sent = true;
}
return sent;
} |
a418f980-d66a-458d-a6ab-a5b76eaa6c8b | 0 | private StopRangeComparator()
{
} |
ee03fd4d-fd1e-4ea3-b833-961329754194 | 3 | private boolean simula (int indexIniziale) {
// indica se e' avvenuto un loop infinito:
boolean loop = false;
// cellaCorrente assume il valore della cella da cui deve iniziare la simulazione della macchina
this.indexCorrente = indexIniziale;
while (this.indexCorrente != 0) {
// memorizzo all'interno di hm la cella corrente e lo stato. Se la macchina torna in questo punto significa che si sta ripetendo
hm.put(this.indexCorrente, this.statoCorrente);
int newStato = this.statoReturner(this.cellaReader(this.indexCorrente), this.statoCorrente);
int newShift = this.shiftReturner(this.cellaReader(this.indexCorrente), this.statoCorrente);
this.indexCorrente += newShift;
this.statoCorrente = newStato;
// hm interrompe il ciclo se la macchina si ripete
if (hm.containsKey(indexCorrente)) {
if ((int) hm.get(indexCorrente) == statoCorrente) {
loop = true;
break;
}
}
this.simula(indexCorrente);
}
return !loop;
} |
f3e4a7e7-5575-42a2-8039-9519e4830fab | 4 | public void run() {
while (clientSocket.isConnected()) {
try {
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String message = inputStream.readLine();
System.out
.println("[Server] Message received : " + message);
if (message.equals("dbchanged")) {
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream(), true);
writer.println("updateview");
broadCastUpdateView();
} else if (message.equals("exit")) {
exit = true;
}
} catch (IOException e) {
System.out.println("Client I/O error");
return;
}
}
} |
9ca21063-598d-4966-a42b-e531443079b1 | 6 | public static String escape(String string) {
StringBuilder sb = new StringBuilder(string.length());
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
} |
0ee40779-cad9-49f1-884b-49ef1145d863 | 9 | @RequestMapping(value = "/users.htm", method = RequestMethod.GET)
public ModelAndView setupListForm(
@RequestParam(required = false, value = "tool") String tool,
HttpServletRequest request,
ModelMap model) {
String vue = Consts.INDEX_VUE;
List<User> users = null;
if (tool != null && isLoged(request)) {
if (isSessionUserAdmin(request)) {
vue = "users";
switch (tool) {
case "showall":
users = (List<User>) (List<?>) hUser.selectAll();
model.addAttribute("label", "Utilisateurs");
break;
case "showadmins":
users = (List<User>) (List<?>) hUser.selectAllAdmins();
model.addAttribute("label", "Admins");
break;
case "showproprios":
users = (List<User>) (List<?>) hUser.selectAllProprios();
model.addAttribute("label", "Proprios");
break;
default:
model.addAttribute(Consts.SEARCH_FORM,getSearchForm(request));
vue = Consts.MAIN_PAGE_VUE;
break;
// case pour autre....
// show all admins
// show...
}
model.addAttribute("users", users);
} else {
model.addAttribute(Consts.SEARCH_FORM, getSearchForm(request));
vue = Consts.MAIN_PAGE_VUE;
}
}
return new ModelAndView(vue, Consts.MODEL, model);
} |
0789cf35-6024-4bbb-aead-2cd9b2be83cf | 3 | public void press(String msg, boolean cap){
if(!selected) return;
if(text.length() >= length) return;
if(cap) msg = msg.toUpperCase();
text = text + msg;
wait = 10;
} |
b84437d2-5a84-476e-bcb3-8d4b48b92282 | 7 | private void buy(Player hero) {
System.out.println("What will you buy? Current Gold:" + hero.getGold());
//Prints the inventory of the shop
String inven = "";
for (int i = 0; i < getInventory().length; i++) {
inven += "[" + i + "]" + getInventory()[i].getName() + "(" + getInventory()[i].getGoldWorth() + "g), ";
}
System.out.println(inven + "[" + getInventory().length + "]exit");
//Gets the users input
int chosen = -1;
boolean loop = true;
while (loop) {
try {
System.out.print(">");
chosen = scan.nextInt();
scan.nextLine();
loop = false;
} catch (InputMismatchException e) {
TextRPG.invalidInput();
scan.next();
}
}
//If the input is legal then buy the item, maybe make unsellable items
if (chosen > -1 && chosen < getInventory().length) {
if (getInventory()[chosen].getGoldWorth() <= hero.getGold()) {
hero.getInventory().add(getInventory()[chosen]);
hero.setGold(hero.getGold() - getInventory()[chosen].getGoldWorth());
System.out.println("Bought " + getInventory()[chosen].getName() + ".");
}
else {
System.out.println("Not enough gold!");
}
}
else if (chosen == getInventory().length) {
}//Exits the buying transaction
else {
TextRPG.invalidInput();
}
} |
9f02b73d-3dd4-49f3-8c66-fae5e5bbfb84 | 6 | public void setImageLevel(TransparentImageLevel lev, int index) {
if (index < 0 || index > MAX_IMG_LEVELS) {
throw new IllegalArgumentException("Bad index for setImageLevel:" + index);
}
if (imgLevels[index] == null && lev != null) {
// new one added
numImgLevels++;
imgLevels[index] = lev;
} else if (imgLevels[index] != null && lev == null) {
// old one replaced with null
numImgLevels--;
imgLevels[index] = lev;
} else {
// overwrite existing
imgLevels[index] = lev;
}
} |
923c83f7-1ce5-4ea4-ae58-289235195f55 | 9 | @Inject
public void schedule( Scheduler scheduler )
throws Exception
{
if ( cronExpression == null && trigger == null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' without cron expression",
jobClass.getName() ) );
}
if ( cronExpression != null && trigger != null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' with cron expression " +
"and an associated Trigger at the same time", jobClass.getName() ) );
}
JobKey jobKey = jobKey( DEFAULT.equals( jobName ) ? jobClass.getName() : jobName, jobGroup );
TriggerKey triggerKey = triggerKey( DEFAULT.equals( triggerName ) ? jobClass.getCanonicalName() : triggerName, triggerGroup );
if ( updateExistingTrigger && scheduler.checkExists( triggerKey ) ) {
scheduler.unscheduleJob( triggerKey );
}
scheduler.scheduleJob( newJob( jobClass )
.withIdentity( jobKey )
.requestRecovery( requestRecovery )
.storeDurably( storeDurably ).build(),
( trigger == null ) ?
newTrigger()
.withIdentity( triggerKey )
.withSchedule( cronSchedule( cronExpression )
.inTimeZone( timeZone ) )
.withPriority( priority )
.build()
: trigger);
} |
b41a0f97-a7b0-4edf-812d-965210059ef4 | 7 | public void move(int xa, int ya) {
if (xa != 0 && ya != 0) {
move(xa, 0);
move(0, ya);
return;
}
if (xa > 0) setDir(1);
if (xa < 0) setDir(3);
if (ya > 0) setDir(2);
if (ya < 0) setDir(0);
if (!collision(xa, ya)) {
x += xa;
y += ya;
xL += xa;
yT += ya;
xR += xa;
yB += ya;
}
} |
fb01c10d-0753-42b9-bc42-092b06c2485f | 4 | private ArrayList<String> extractNGrams() {
ArrayList<String> list = new ArrayList<String>();
NGram ngram = new NGram();
for(int i=0;i<text.length();++i) {
ngram.addChar(text.charAt(i));
for(int n=1;n<=NGram.N_GRAM;++n){
String w = ngram.get(n);
if (w!=null && wordLangProbMap.containsKey(w)) list.add(w);
}
}
return list;
} |
e007a7ba-05b4-42c9-8e1f-50ffd29bbd3f | 2 | private Main(int rack_size, Player ai) throws Exception{
Main.rack_size = rack_size;
WIN_HEIGHT = rack_size*Card.height+(rack_size-1)*Board.card_pad+2*Board.border_pad_ver+50;
if (WIN_HEIGHT < 300) WIN_HEIGHT = 400;
player_ai = ai;
player_human = new PlayerGUI(this);
game = Game.create(
new Player[]{player_human, player_ai},
rack_size, 1, false
);
Card.card_count = game.card_count;
game.registerGUI(this);
addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == 's')
spymode_always = board.toggleSpyMode();
}
});
System.out.println("Use s-key to toggle spy mode");
initGUI();
} |
71d96740-4eb4-41c3-ae57-b4ba766ddf7e | 6 | public static Class<? extends TrapEvent> fromString(String s) {
if(s.equalsIgnoreCase("attack"))
return TrapEventAttack.class;
else if(s.equalsIgnoreCase("lpincrease"))
return TrapEventLPIncrease.class;
else if(s.equalsIgnoreCase("lpdecrease"))
return TrapEventLPDecrease.class;
else if(s.equalsIgnoreCase("powerup"))
return TrapEventPowerUp.class;
else if(s.equalsIgnoreCase("activate"))
return TrapEventActivate.class;
return TrapEvent.class;
} |
ec4a7c65-1694-4452-9c01-a6296d3f9c6b | 2 | public long askID() {
System.out.println(ASK_ID);
if (terminal.hasNext(ID_PATTERN)) {// verificamos que sea un id valido
return Long.parseLong(terminal.nextLine());
} else if (terminal.hasNext(ID_PATTERN_SMALL))// para ahorrar tiempo se usan ids de tres digitos
{
return ID_SMALL_MASK + Long.parseLong(terminal.next());
} else {
System.out.println(INVALID_ID);
terminal.nextLine();
}
return askID();
} |
de712829-44b1-4b3a-ac0a-b580a75d7057 | 8 | static Object getAnnotationType(Class clz, ClassPool cp,
AnnotationsAttribute a1, AnnotationsAttribute a2)
throws ClassNotFoundException
{
Annotation[] anno1, anno2;
if (a1 == null)
anno1 = null;
else
anno1 = a1.getAnnotations();
if (a2 == null)
anno2 = null;
else
anno2 = a2.getAnnotations();
String typeName = clz.getName();
if (anno1 != null)
for (int i = 0; i < anno1.length; i++)
if (anno1[i].getTypeName().equals(typeName))
return toAnnoType(anno1[i], cp);
if (anno2 != null)
for (int i = 0; i < anno2.length; i++)
if (anno2[i].getTypeName().equals(typeName))
return toAnnoType(anno2[i], cp);
return null;
} |
b627298c-5f40-431e-8e15-a3e5bb92d272 | 8 | @Test
public void testCancelAllJobs() {
System.out.println("cancelAllJobs");
final Counter counter = new Counter();
c.setAssignmentListener(new AssignmentListener() {
boolean run = true;
@Override
public void receiveTask(Assignment task) {
try {
Object tsk = task.getTask();
if (!(tsk instanceof Integer)) {
fail("Illegal task received");
}
Integer count = (Integer) tsk;
if (!run) {
return;
}
synchronized (task) {
task.wait(count);
}
if (!run) {
return;
}
counter.add(count);
task.submitResult(GenericResponses.OK);
} catch (ConnectionException ex) {
fail("Connection to server failed - " + ex);
} catch (InterruptedException ex) {
fail("Waiting has been interrupted - " + ex);
}
}
@Override
public void cancelTask(Assignment task) {
run = false;
}
});
int val;
Random rnd = new Random();
final int jobCount = rnd.nextInt(5) + 5;
Set<Job> jobs = new HashSet<Job>(jobCount);
for (int i = 0; i < jobCount; i++) {
val = (rnd.nextInt(4) + 1) * 200;
jobs.add(s.submitJob(val));
}
try {
synchronized (this) {
this.wait(100);
}
} catch (InterruptedException ex) {
fail("Waiting for cancelation failed - " + ex);
}
s.getJobManager().stopAllJobs();
for (Job j : jobs) {
assertEquals(null, j.getResult(true));
}
assertEquals(0, counter.getCount());
} |
d67da17c-5336-4900-98bb-571d15124474 | 5 | public SimulationEvent(int eventType, Object eventData)
{
if (eventType != EVENT_SIM_STARTED
&& eventType != EVENT_SIM_DONE
&& eventType != EVENT_SIM_CANCELLED
&& eventType != EVENT_SIM_ERROR
&& eventType != EVENT_SIM_PROGRESS
) {
throw new IllegalArgumentException("Invalid event type");
}
this.eventType = eventType;
this.eventData = eventData;
} |
e8ba81c5-cf6e-4573-9f53-cf16905d1c90 | 9 | public void laufen(int geschwindigkeit, int delta) {
// Macht Bewegung auf Y Ebene möglich
y_Pos += speed_v;
// Hier steht die Bewegung auf horizontaler Ebene.
// Pfeiltaste links
if (steuerung.isKeyDown(Input.KEY_A)) {
x_Pos = x_Pos - geschwindigkeit;
}
// Pfeiltaste rechts
if (steuerung.isKeyDown(Input.KEY_D)) {
x_Pos = x_Pos + geschwindigkeit;
}
// Hier steht die Bewegung auf vertikale Ebene.
// Pfeiltaste oben
if (steuerung.isKeyPressed(Input.KEY_W) && !sprung) {
speed_v = -0.3f * delta;
sprung = true;
}
if (x_Pos <= 0) {
x_Pos = 0;
} else if (x_Pos >= 770) {
x_Pos = 770;
}
if (y_Pos <= 0) {
y_Pos = 0;
} else if (y_Pos >= 395) {
y_Pos = 395;
}
// Sprunggrenze Y
if (y_Pos <= 250) {
sprung = false;
speed_v = +0.3f * delta;
}
hitbox.setLocation(x_Pos, y_Pos);
}; |
7c424c9d-6b3c-4d8a-8629-a3c807734413 | 8 | private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes |
16cddea7-43d0-4d32-80b9-0f01cd0e01b2 | 7 | public void initToNull()
{
for(int j = 0; j < anInt437; j++)
{
for(int k = 0; k < anInt438; k++)
{
for(int i1 = 0; i1 < anInt439; i1++)
groundArray[j][k][i1] = null;
}
}
for(int l = 0; l < anInt472; l++)
{
for(int j1 = 0; j1 < anIntArray473[l]; j1++)
aClass47ArrayArray474[l][j1] = null;
anIntArray473[l] = 0;
}
for(int k1 = 0; k1 < obj5CacheCurrPos; k1++)
obj5Cache[k1] = null;
obj5CacheCurrPos = 0;
for(int l1 = 0; l1 < aClass28Array462.length; l1++)
aClass28Array462[l1] = null;
} |
a2a1a7fe-3c2b-421f-b65f-24f0d2f2efb8 | 0 | public Medicament() {
} |
d74447c1-1119-48ab-ba50-e0d82bb0616c | 1 | public void award_bonus(BigInteger threshold, BigInteger bonus) {
if (getBalance().compareTo(threshold) >= 0)
deposit(bonus);
} |
9a1b16d1-eacc-450d-8fce-7ad6472ac427 | 0 | public void setId(String id) {
questId = Integer.parseInt(id);
} |
e1f9d7cc-3849-4345-8282-bf390cf6f5f4 | 1 | @Test
public void haltInstrInvalidOpcodeTest() {
try {
instr = new HaltInstr(Opcode.LOAD);
}
catch (IllegalStateException e) {
e.getMessage();
}
assertNull(instr); //Instruction should only be instantiated with HALT opcode
} |
e64e3041-1456-4a98-9050-33fb29f2d77b | 3 | public boolean jsFunction_waitStartMoveGob(int gob, int timeout) {
deprecated();
int curr = 0; if(timeout == 0) timeout = 10000;
while(!JSBotUtils.isMoving(gob))
{
if(curr > timeout)
return false;
Sleep(25);
curr += 25;
}
return true;
} |
1a8dd2ca-cfcb-494d-a301-b35873cfa3ab | 7 | public void paint(GC gc, int width, int height) {
if (!example.checkAdvancedGraphics()) return;
Device device = gc.getDevice();
// array of coordinate points of polygon 1 (region 1)
int [] polygon1 = new int [] {10, height/2, 9*width/16, 10, 9*width/16, height-10};
Region region1 = new Region(device);
region1.add(polygon1);
// array of coordinate points of polygon 2 (region 2)
int [] polygon2 = new int [] {
9*width/16, 10,
9*width/16, height/8,
7*width/16, 2*height/8,
9*width/16, 3*height/8,
7*width/16, 4*height/8,
9*width/16, 5*height/8,
7*width/16, 6*height/8,
9*width/16, 7*height/8,
9*width/16, height-10,
width-10, height/2
};
Region region2 = new Region(device);
region2.add(polygon2);
gc.setAlpha(127);
int clippingIndex = clippingCb.getSelectionIndex();
switch (clippingIndex) {
case 0:
// region 1
gc.setClipping(region1);
gc.setBackground(colorGB1.getBgColor1());
gc.fillPolygon(polygon1);
break;
case 1:
// region 2
gc.setClipping(region2);
gc.setBackground(colorGB2.getBgColor1());
gc.fillPolygon(polygon2);
break;
case 2:
// add
region1.add(region2);
break;
case 3:
// sub
region1.subtract(region2);
break;
case 4:
// intersect
region1.intersect(region2);
break;
}
if (clippingIndex > 1) {
gc.setClipping(region1);
gc.setBackground(colorGB1.getBgColor1());
gc.fillPolygon(polygon1);
gc.setBackground(colorGB2.getBgColor1());
gc.fillPolygon(polygon2);
}
region1.dispose();
region2.dispose();
} |
e5127c03-72b8-4897-a04b-def17e37b52f | 7 | public static void processWords(String str) throws FileNotFoundException
{
//String str="<DOC><DOCNO>1</DOCNO><TITLE>experimental investigation of the aerodynamics of awing in a slipstream .</TITLE><AUTHOR>brenckman,m.</AUTHOR><BIBLIO>j. ae. scs. 25, 1958, 324.</BIBLIO><TEXT> an experimental study of a wing in a propeller slipstream was made in order to determine the spanwise distribution of the lift increase due to slipstream at different angles of attack of the wing and at different free stream to slipstream velocity ratios . the results were intended in part as an evaluation basis for different theoretical treatments of this problem . the comparative span loading curves, together with supporting evidence, showed that a substantial part of the lift increment produced by the slipstream was due to a /destalling/ or boundary-layer-control effect . the integrated remaining lift increment, after subtracting this destalling lift, was found to agree well with a potential flow theory . an empirical evaluation of the destalling effects was made for the specific configuration of the experiment . </TEXT> </DOC>";
//String str="<>an experimental study of a wing in a propeller slipstream was</TEXT>";
ArrayList<String> tagValues=getTagValues(str);
for(String s : tagValues)
{
String string=s;
//System.out.println("Test "+string);
string=string.replaceAll("[-+.^:,\\/()]", "");
//str1=str1.replaceAll("[^a-zA-Z0-9]", "");
String[] splited = string.split("\\s+");
for(String word : splited)
{
if(!isNumeric(word))
{
if (!(word.matches(".*[0-9].*")) && word.length()>1)
{
if(word.contains("'"))
{
word=word.substring(0,word.indexOf("'"));
}
word=word.toLowerCase();
//System.out.println(word.toLowerCase());
if(wordMap.containsKey(word))
{
wordMap.put(word, wordMap.get(word)+1);
}else
{
wordMap.put(word, 1);
}
}
}
}
}
} |
9d35dbf7-4263-4c00-8be1-3b53cbe38e1a | 7 | protected BallNode mergeNodes(Vector<TempNode> list, int startIdx, int endIdx)
throws Exception {
for(int i=0; i<list.size(); i++) {
TempNode n = (TempNode) list.get(i);
n.anchor = calcPivot(n.points, new MyIdxList(), m_Instances);
n.radius = calcRadius(n.points, new MyIdxList(), n.anchor, m_Instances);
}
double minRadius, tmpRadius; //tmpVolume, minVolume;
Instance pivot, minPivot=null;
TempNode parent; int min1=-1, min2=-1;
while(list.size() > 1) { //main merging loop
minRadius=Double.POSITIVE_INFINITY;
for(int i=0; i<list.size(); i++) {
TempNode first = (TempNode) list.get(i);
for(int j=i+1; j<list.size(); j++) {
TempNode second = (TempNode) list.get(j);
pivot = calcPivot(first, second, m_Instances);
tmpRadius = calcRadius(first, second); //calcRadius(first.points, second.points, pivot, m_Instances);
if(tmpRadius < minRadius) { //(tmpVolume < minVolume) {
minRadius = tmpRadius; //minVolume = tmpVolume;
minPivot = pivot;
min1=i; min2=j;
//minInstList = tmpInstList;
}
}//end for(j)
}//end for(i)
parent = new TempNode();
parent.left = (TempNode) list.get(min1);
parent.right = (TempNode) list.get(min2);
parent.anchor = minPivot;
parent.radius = calcRadius(parent.left.points, parent.right.points, minPivot, m_Instances); //minRadius;
parent.points = parent.left.points.append(parent.left.points, parent.right.points);
list.remove(min1); list.remove(min2-1);
list.add(parent);
}//end while
TempNode tmpRoot = (TempNode)list.get(list.size()-1);
if((endIdx-startIdx+1)!= tmpRoot.points.length()) {
throw new Exception("Root nodes instance list is of irregular length. " +
"Please check code. Length should " +
"be: " + (endIdx-startIdx+1) +
" whereas it is found to be: "+tmpRoot.points.length());
}
for(int i=0; i<tmpRoot.points.length(); i++) {
m_InstList[startIdx+i] = ((ListNode)tmpRoot.points.get(i)).idx;
}
BallNode node = makeBallTreeNodes(tmpRoot, startIdx, endIdx, 0);
return node;
} |
84a94239-cbb8-44dc-b56c-53bee70783be | 6 | public String disparar() {
String resultado = "";
if(numElementos > 0 ) {
Random rnd = new Random();
int fila = rnd.nextInt(NUM_FILAS);
int columna = rnd.nextInt(NUM_COLUMNAS);
int porcentaje = rnd.nextInt(100);
NaveAlien n1 = listaNavesAliens[fila][columna];
if(n1 != null ) {
if(noHayNavesDebajo(fila, columna) && porcentaje < 50) {
n1.disparar();
resultado = String.format("%1$s;%2$s", n1.getId(),n1.getCreadorDisparoUnico()-1);
}
}
} else {
Random rnd = new Random();
int num = rnd.nextInt(20);
if(num <= 1 && naveNodriza.getY() >= 50) {
naveNodriza.disparar();
resultado = String.format("%1$s;%2$s", naveNodriza.getId(), naveNodriza.getCreadorDisparoUnico()-1);
}
}
return resultado;
} |
2550bc45-d857-40b7-9e3e-296a7405d8a6 | 5 | public AccountServiceError addUser(String login, String password) {
if (isConnectionClosed())
openConnection();
if (isConnectionClosed())
return new AccountServiceError(AccountServiceError.Type.DB_noConnection);
UserDataSetDAO dao = new UserDataSetDAO(dbconn);
UserDataSet user = null;
try {
user = dao.find("login", login);
} catch(SQLException e) {
e.printStackTrace();
}
if (user != null)
return new AccountServiceError(AccountServiceError.Type.Sigiup_userAlreadyExists);
user = new UserDataSet(login, password);
boolean result = dao.save(user);
if (result)
return new AccountServiceError();
return new AccountServiceError(AccountServiceError.Type.Signup_badUserForm);
} |
20078029-36e1-481c-918f-4d7021a695e6 | 3 | public String getEssensrationText()
{
String ration = "";
if ( this.essensration == 1 )
ration = "halb";
if ( this.essensration == 2 )
ration = "voll";
if ( this.essensration == 4 )
ration = "doppelt";
return ration;
} |
5ca74968-8c1c-46dd-ada7-33386a92bb68 | 2 | public static File showOpenFileDialog(Frame parentFrame, String title){
FileDialog fileDialog = new FileDialog(parentFrame, title);
fileDialog.setIconImage(MAIN_ICON.getImage());
fileDialog.setDirectory(HOME_DIRECTORY);
fileDialog.setVisible(true);
String directoryName = fileDialog.getDirectory();
String fileName = fileDialog.getFile();
File file = null;
if (directoryName != null && fileName != null) {
file = new File(directoryName + fileName);
}
return file;
} |
863092f2-d863-48d3-8b7f-feee0db114e6 | 6 | private void writeOutput(List<List<Gate>> layersOfGates) {
BufferedWriter fbw = null;
try {
fbw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile), charset));
int[] intHeaders = circuitParser.getOutputHeader(layersOfGates);
String header = "";
for (int i = 0; i < intHeaders.length; i++){
header += (intHeaders[i] + "");
if (i != intHeaders.length - 1){
header += " ";
}
}
fbw.write(header);
fbw.newLine();
/*
* Write the gates the the file, one layer at a time
*/
for(List<Gate> l: layersOfGates){
// Write the size of the current layer
fbw.write("*" + l.size());
fbw.newLine();
// Write the gates in this layer
for(Gate g: l){
String gateString = layersOfGates.indexOf(l) + " " + g.toString();
fbw.write(gateString);
fbw.newLine();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
43f61318-544d-4986-beb1-38ff72a456e1 | 7 | public Object handle(Message req) throws Exception {
if(server_obj == null) {
log.error(Util.getMessage("NoMethodHandlerIsRegisteredDiscardingRequest"));
return null;
}
if(req == null || req.getLength() == 0) {
log.error(Util.getMessage("MessageOrMessageBufferIsNull"));
return null;
}
MethodCall method_call=methodCallFromBuffer(req.getRawBuffer(), req.getOffset(), req.getLength(), marshaller);
if(log.isTraceEnabled())
log.trace("[sender=%s], method_call: %s", req.getSrc(), method_call);
if(method_call.mode() == MethodCall.ID) {
if(method_lookup == null)
throw new Exception(String.format("MethodCall uses ID=%d, but method_lookup has not been set", method_call.methodId()));
Method m=method_lookup.findMethod(method_call.methodId());
if(m == null)
throw new Exception("no method found for " + method_call.methodId());
method_call.method(m);
}
return method_call.invoke(server_obj);
} |
077d6b29-b0df-4632-a2e9-e5496d33640e | 0 | public String getLibelle() {
return libelle;
} |
a03b5710-3ea0-48b2-9f13-8cacc4f3ae18 | 1 | public HunterPanel(World world) {
this.model = world.getHunterList();
this.setBorder(new TitledBorder("Hunter"));
this.setLayout(new FlowLayout(FlowLayout.LEFT));//new BorderLayout());
this.setPreferredSize(new Dimension(250,350));
this.setBounds(0, 0, 250, 350);
//this.setSize(250,350);
rowData = new String[10][4];
for (int i=0; i<10; i++) {
rowData[i][0] = "";
rowData[i][1] = "";
rowData[i][2] = "";
rowData[i][3] = "";
}
tableModel = new DefaultTableModel(rowData, columnNames);
table = new JTable(tableModel);
table.setPreferredSize(new Dimension(100,100));
table.setRowHeight(20);
table.setRowMargin(4);
table.setShowGrid(false);
scrollpane = new JScrollPane(table);
// scrollpane.setSize(100,100);
// scrollpane.setBounds(50,50,50,50);
scrollpane.setPreferredSize(new Dimension(230,320));
this.add(scrollpane);//, BorderLayout.CENTER);
world.addHunterListListener(new HunterListListener() {
public void hunterListModelChanged(List<Hunter> hunters) {
updateList(hunters);
}
});
} |
2afe8406-1978-4171-8a37-62bd54abfc55 | 6 | public String winner()
{
int blackcount = 0;
int whitecount = 0;
for (int[] row : board)
{
for (int value : row)
{
if(value == B)
blackcount++;
else if(value == W)
whitecount++;
}
}
if (blackcount > whitecount)
return black;
else if(blackcount < whitecount)
return white;
else //(blackcount == whitecount)
return tie;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.