text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void process() {
int taskNum = 0;
List<PWMWithThreshold> thresholds = collectThreshold();
Collections.sort(thresholds, new Comparator<PWMWithThreshold>() {
@Override
public int compare(PWMWithThreshold o1, PWMWithThreshold o2) {
return o1.pwm.getName().compareTo(o2.pwm.getName());
}
});
System.out.print("Motif name"+ "\t");
for(PWMWithThreshold second: thresholds) {
System.out.print(second.pwm.getName() + "\t");
}
System.out.println();
for(PWMWithThreshold first: thresholds) {
System.out.print(first.pwm.getName() + "\t");
for(PWMWithThreshold second: thresholds) {
if (taskNum % numOfThreads == numThread % numOfThreads) {
// so that numThread in range 0..(n-1) was equal to 1..n
int cmp = first.pwm.getName().compareTo(second.pwm.getName());
if (cmp == 0) {
System.out.print("0.0\t");
} else if (cmp < 0) {
System.out.print("x\t");
} else {
double distance = calculateDistance(first, second);
System.out.print(distance + "\t");
}
} else {
System.out.print("x\t");
}
taskNum += 1;
}
System.out.println();
System.err.print(".");
}
} | 6 |
private void makePrefab(){
prefab = new Prefab(x1, y1, x2, y2);
boolean found = true;
int filenumber = 0;
String pathTag = "HousePrefab";
String path = "";
do {
path = "data/" + pathTag + String.valueOf(filenumber) + ".pfb";
File f = new File(path);
if (!f.isFile()){
found = false;
} else {
filenumber++;
}
} while (found);
try {
prefab.save(path);
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
private static void selectDB() throws Exception {
int menuChoice;
do {
System.out
.println("*** Willkommen zu " + NAME + " " + VERSION + " ***\n\n"
+ "Welche Datenbankzugriffsart möchten sie nutzen? \n\n"
+ "1 SQL-Datenbank der Hochschule Mannheim (über JDBC) \n"
+ "2 SQL-Datenbank der Hochschule Mannheim (über Hibernate) \n"
+ "3 eigene SQL-Datenbank (über JDBC) \n"
+ "4 eigene SQL-Datenbank (über Hibernate) \n"
+ "5 eigene DB4O-Datenbank (Servermode; vorher startDb4oServer.bat starten) \n"
+ "6 lokale DB4O-Datenbank \n\n"
+ "9 Credits \n\n"
+ "0 Programm beenden");
menuChoice = getMenuChoice();
switch (menuChoice) {
case 1:
db = new JdbcAccess();
menu();
break;
case 2:
System.out.println("Noch nicht unterstützt.");
break;
case 3:
db = new JdbcAccess("firmenwelt", "firmenwelt10");
menu();
break;
case 4:
db = new HibernateDBAccess();
menu();
break;
case 5:
db = new Db4oAccess("localhost", 8732, "firmenwelt",
"firmenwelt10");
menu();
break;
case 6:
db = new Db4oAccess("firmenwelt.yap");
menu();
break;
case 9:
credits();
pressAnyKey();
break;
case 0:
System.out.println("Programm wird beendet.");
break;
// Invalide Eingabe:
default:
System.out.println(INVALID_INPUT);
break;
}
} while (menuChoice != 0);
} | 9 |
private int swim(int i)
{
Key t = pq[i]; // Save key for later restoring
while (i > 1 && less(pq[i / 2], pq[i]))
{
// exch(pq, i / 2, i);
pq[i] = pq[i / 2]; // half exchanges
i = i / 2;
}
pq[i] = t; // restore key
return i;
} | 2 |
public Geometry<T> add(T elements)
{
coordinates.add(elements);
return this;
} | 0 |
public static void main(String[] args) {
String q = "howdy";
System.out.println(q); // howdy
String qq = upcase(q);
System.out.println(qq); // HOWDY
System.out.println(q); // howdy
} | 0 |
public void messageBroadcasted(final Blackboard.BlackboardMessage message)
{
if (message instanceof MatrixPatch)
{
final MatrixPatch patch = (MatrixPatch)message;
synchronized (queuedPatches)
{
queuedPatches.offerLast(patch);
queuedPatches.notifyAll();
}
}
else if (message instanceof LocalPlayer)
{
this.player = ((LocalPlayer)message).player;
}
else if (message instanceof PlayerPause)
{
if (((PlayerPause)message).player == this.player)
{
this.paused = ((PlayerPause)message).paused;
this.repaint();
}
}
else if (message instanceof FullUpdate)
{
final FullUpdate fullUpdate = (FullUpdate)message;
if (fullUpdate.isGathering() == false)
{
final Board board = ((EngineData)(fullUpdate.data.get(Engine.class))).board;
final Shape shape = ((EngineData)(fullUpdate.data.get(Engine.class))).fallingShape;
if (board == null)
return;
final Block[][] matrix = board.getMatrix();
final boolean[][] erase = new boolean[20][10];
for (int y = 0; y < 20; y++)
for (int x = 0; x < 10; x++)
erase[y][x] = true;
update(erase, matrix, 0, 0);
final Block[][] blocks = shape.getBlockMatrix();
update(null, blocks, shape.getX(), shape.getY());
}
}
} | 9 |
public static boolean heuristicAcronymP(String itemstring) {
{ boolean letterfoundP = false;
boolean numberfoundP = false;
{ char c = Stella.NULL_CHARACTER;
String vector000 = itemstring;
int index000 = 0;
int length000 = vector000.length();
for (;index000 < length000; index000 = index000 + 1) {
c = vector000.charAt(index000);
if (Stella.$CHARACTER_TYPE_TABLE$[(int) c] == Stella.KWD_DIGIT) {
numberfoundP = true;
}
else if (Stella.lowerCaseCharacterP(c) ||
Stella.upperCaseCharacterP(c)) {
letterfoundP = true;
}
else if (Stella.getQuotedTree("((#\\. #\\- #\\/) \"/STELLA\")", "/STELLA").memberP(CharacterWrapper.wrapCharacter(c))) {
numberfoundP = true;
}
else {
return (false);
}
}
}
return (numberfoundP &&
(letterfoundP &&
(!Stella.ordinalNumberStringP(itemstring))));
}
} | 7 |
public void setZeroes(int[][] matrix) {
int[] rows = new int[matrix.length];
int[] cols = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
rows[i] = 1;
cols[j] = 1;
}
}
}
for (int i = 0; i < rows.length; i++) {
if (rows[i] == 1) {
// clear row i
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
for (int i = 0; i < cols.length; i++) {
if (cols[i] == 1) {
// clear col i
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
}
} | 9 |
private void solve() {
if (isAllOnes()) {
minimisedExpression = "1";
} else {
if (isAllZero())
minimisedExpression = "0";
else {
arrayList = new ArrayList<KarnaughNode>();
for (int i = 0; i < kmap.getRow(); i++) {
for (int j = 0; j < kmap.getColumn(); j++) {
if (kmap.getCellValue(i, j)) {
KarnaughNode n = new KarnaughNode();
n.flag = false;
n.numberOfItems = 1;
n.nodes = binaryCode(kmap.getCellAdress(i, j),
nombreVars);
n.addCellAdress(n.nodes);
arrayList.add(n);
}
}
}
regroupe();
deleteUnneededNodes();
minimisedExpression();
}
}
} | 5 |
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
} | 0 |
@Override
public void writeTo(WordWriter out)
throws IOException {
WordReader in = new WordReader(new FileInputStream(file), littleEndian);
int wordsWritten = 0;
try {
int word;
while(true) {
word = in.readWord();
if(word == -1)
break;
out.writeWord(word);
wordsWritten++;
}
} finally {
in.close();
}
if(wordsWritten != wordsize) {
throw new IOException("File size of "+file+" changed unexpectedly");
}
} | 3 |
private Chunk getChunk(int x, int z)
{
for(int i = chunks.size() - 1; i > 0; i--)
if(chunks.get(i).getX() == x && chunks.get(i).getZ() == z)
if(i < chunks.size() && i >= 0)
return chunks.get(i);
return null;
} | 5 |
public List[] getReplacements(String symbol) {
List[] toReturn = (List[]) symbolToReplacements.get(symbol);
return toReturn == null ? EMPTY_LIST : toReturn;
} | 1 |
public static void main(String[] args) {
String text;
int k = 0;
if (args.length == 1) {
k = Integer.parseInt(args[0]);
}
System.out.print("Enter string: ");
Scanner s = new Scanner(System.in);
text = s.nextLine();
MyHashMap<String, Markov> hash = new MyHashMap<String, Markov>();
int distinct = 0;
for (int i=0; i<=text.length()-k; i++) {
String sub = text.substring(i,i+k);
Character suffix = null;
if (((i+k) <= (text.length()-1)))
suffix = text.charAt(i+k);
if (hash.containsKey(sub)) {
Markov temp = hash.get(sub);
if (!(suffix == null)) {
temp.add(suffix);
hash.put(sub, temp);
}
}
else {
Markov m;
if (!(suffix == null)) {
m = new Markov(sub, suffix);
hash.put(sub, m);
distinct++;
}
}
}
System.out.println(distinct+" distinct keys");
Iterator<String> keys = hash.keys();
while (keys.hasNext()) {
String hashKey = keys.next();
Markov hashValue = hash.get(hashKey);
System.out.print(hashValue.count()+" "+hashKey+":");
for (Entry<Character, Integer> entry : hashValue.getMap().entrySet()) {
char suffix = entry.getKey();
int frequencyCount = entry.getValue();
System.out.print(" "+frequencyCount+" "+suffix);
}
System.out.println();
}
} | 8 |
static public void statisticMonth(){
Statement stmt = null;
ResultSet rs = null;
for(int month = 1; month <=12; month ++)
try {
String monthStr = "" + month;
if(month < 10) monthStr = "0" + monthStr;
stmt = conn.createStatement();
String sqlTxt = "select count(*) as cnt from tweet_2011_" + monthStr;
//System.out.println(sqlTxt);
if (stmt.execute(sqlTxt)) {
rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt("cnt"));
}
}
//out.close();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) {
} // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) {
} // ignore
stmt = null;
}
}
} | 9 |
static String escapeStringForASCII(String s) {
String out = "";
char[] cArray = s.toCharArray();
for (int i = 0; i < cArray.length; i++) {
char c = cArray[i];
if (c > 127) {
//non-ASCII Unicode
out += "\\U";
String hex = Integer.toHexString(c);
while (hex.length() < 4)
hex = "0" + hex;
out += hex;
} else if (c == '\\') {
out += "\\\\";
} else if (c == '\"') {
out += "\\\"";
} else if (c == '\b') {
out += "\\b";
} else if (c == '\n') {
out += "\\n";
} else if (c == '\r') {
out += "\\r";
} else if (c == '\t') {
out += "\\t";
} else {
out += c;
}
}
return out;
} | 9 |
private static ConfigurableConnectionText goodLocation( PathedGraphConnection connection, float j ) {
if( j == 0 ) {
ConfigurableConnectionText text = new ConfigurableConnectionText( connection );
text.setText( "Source" );
text.setPosition( TextStrategyFactory.positionNearSource() );
text.setAngle( TextStrategyFactory.angleParallel() );
text.setShift( TextStrategyFactory.shiftInvardsByPosition() );
text.setDistance( TextStrategyFactory.distanceDownwards( TextStrategyFactory.distanceBaselineFloating() ) );
return text;
} else if( j == 1 ) {
ConfigurableConnectionText text = new ConfigurableConnectionText( connection );
text.setText( "Target" );
text.setPosition( TextStrategyFactory.positionNearTarget() );
text.setAngle( TextStrategyFactory.angleParallel() );
text.setShift( TextStrategyFactory.shiftInvardsByPosition() );
text.setDistance( TextStrategyFactory.distanceDownwards( TextStrategyFactory.distanceBaselineFloating() ) );
return text;
} else {
return null;
}
} | 2 |
public void caretUpdate(CaretEvent e) {
boolean boldFound = false;
boolean italicFound = false;
boolean underlineFound = false;
int dot = e.getDot();
int mark = e.getMark();
if (dot == mark) {
wordProcessor.copy.setEnabled(false);
wordProcessor.cut.setEnabled(false);
boldFound = checkStyleAtIndex(StyleConstants.Bold, dot - 1, wordProcessor.lockButtonBold);
italicFound = checkStyleAtIndex(StyleConstants.Italic, dot - 1, wordProcessor.lockButtonItalic);
underlineFound = checkStyleAtIndex(StyleConstants.Underline, dot - 1, wordProcessor.lockButtonUnderline);
}
else {
wordProcessor.copy.setEnabled(true);
wordProcessor.cut.setEnabled(true);
for (int i = Math.min(dot, mark); i < Math.max(dot, mark); i++) {
boldFound = checkStyleAtIndex(StyleConstants.Bold, i);
italicFound = checkStyleAtIndex(StyleConstants.Italic, i);
underlineFound = checkStyleAtIndex(StyleConstants.Underline, i);
if (boldFound || italicFound || underlineFound) {
break;
}
}
}
selectButton(wordProcessor.bold, boldFound);
selectButton(wordProcessor.italic, italicFound);
selectButton(wordProcessor.underline, underlineFound);
} | 5 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TDatsriPK other = (TDatsriPK) obj;
if (!Objects.equals(this.transNo, other.transNo)) {
return false;
}
if (!Objects.equals(this.itemCode, other.itemCode)) {
return false;
}
return true;
} | 4 |
private void drawEdges(Graphics2D g2, List<Edge> edges, boolean drawBorder, int zoomLevelToDrawName, BasicStroke roadStroke, BasicStroke borderStroke, Color roadColor, Color borderColor)
{
for (Edge edge : edges)
{
double x1 = edge.getFromNode().getxCoord();
double y1 = edge.getFromNode().getyCoord();
double x2 = edge.getToNode().getxCoord();
double y2 = edge.getToNode().getyCoord();
if (drawBorder)
{
g2.setColor(borderColor);
g2.setStroke(borderStroke);
g2.drawLine((int) (((x1 - xVArea) / xlength) * componentWidth), (int) (componentHeight - ((y1 - yVArea) / ylength) * componentHeight), (int) (((x2 - xVArea) / xlength) * componentWidth), (int) (componentHeight - ((y2 - yVArea) / ylength) * componentHeight));
}
g2.setColor(roadColor);
if (searchedRoad.equals(edge.getRoadName()))
{
g2.setColor(Color.blue);
}
g2.setStroke(roadStroke);
g2.drawLine((int) (((x1 - xVArea) / xlength) * componentWidth), (int) (componentHeight - ((y1 - yVArea) / ylength) * componentHeight), (int) (((x2 - xVArea) / xlength) * componentWidth), (int) (componentHeight - ((y2 - yVArea) / ylength) * componentHeight));
if (zoomLevelToDrawName > 0 && xlength <= (quadTreeToDraw.getQuadTreeLength() / zoomLevelToDrawName))
{
if (!roadNamesDisplayed.contains(edge.getRoadName()))
{
drawRotatedString(g2, edge);
roadNamesDisplayed.add(edge.getRoadName());
}
}
}
} | 6 |
public static Forme I() {
ArrayList<Vecteur> liste = new ArrayList<>();
liste.add(new Vecteur(0, 0));
liste.add(new Vecteur(0, 1));
liste.add(new Vecteur(0, 2));
liste.add(new Vecteur(0, 3));
Vecteur<Integer> _centre = new Vecteur(0, 1);
return new Forme("I", liste, _centre);
} | 0 |
public String[][] fileReadIn(String fileDirectory) throws IOException{
ToolBag tool = new ToolBag();
BufferedReader fileReader = null;
try {
fileReader = new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream(fileDirectory)));
} catch (NullPointerException propertiesReaderNPE) {
try {
fileReader = new BufferedReader(
new InputStreamReader(new FileInputStream(fileDirectory)));
} catch (NullPointerException propertiesReaderNPE2) {
System.err.print("\nThe directory: " + fileDirectory + " failed to load.\n\n");
propertiesReaderNPE2.printStackTrace();
}
}
String[][] data = new String[tool.fileLines(fileDirectory, "*")][2];
String dataNameToAdd = null,
dataToAdd = null,
readIn = null;
for(int x = 0; x < data.length; x++){
try {
readIn = fileReader.readLine();
if(readIn.equals(null)){
break;
}
} catch (NullPointerException fileReaderNPE) {
break;
}
if(readIn.startsWith("*")){
continue;
}else if(readIn.contains("\"")){
StringTokenizer readInTokens = new StringTokenizer(readIn);
dataNameToAdd =readInTokens.nextToken("\"");
dataNameToAdd = dataNameToAdd.trim();
dataToAdd = readInTokens.nextToken("\"");
data[x][0] = dataNameToAdd;
data[x][1] = dataToAdd;
}
}
return data;
} | 7 |
public static void close(){
clearCache();
for(String id : staticClips.keySet()){
stop(id);
staticClips.get(id).close();
}
staticClips.clear();
} | 1 |
public String getDesignacao() {
return designacao;
} | 0 |
public void open() {
Display display = Display.getDefault();
createContents();
shlPoliciesList.open();
shlPoliciesList.layout();
while (!shlPoliciesList.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} | 2 |
public static void makeNextWhiteMoves(){
boolean incorrectOption = true;
while(incorrectOption)
{
Move move = UserInteractions.getNextMove(Player.white);
if (CheckValidMoveForWhiteHuman(move.initialRow, move.initialCol,
move.finalRow, move.finalCol))
{
incorrectOption = false;
}
}
} | 2 |
@Test
public void TestCustomConnectionParameters() {
RequestConfig reqC = RequestConfig.custom()
.setSocketTimeout(10) // 1/100 of a second in miliseconds
.setConnectTimeout(10) // 1/100 of a second in miliseconds
.build();
HttpClient client = HttpClients.custom()
.setDefaultRequestConfig(reqC)
.build();
Gateway beanstream = new Gateway("v1", 300200578,
"4BaD82D9197b4cc4b70a221911eE9f70", // payments API passcode
"D97D3BE1EE964A6193D17A571D9FBC80", // profiles API passcode
"4e6Ff318bee64EA391609de89aD4CF5d");// reporting API passcode
beanstream.setCustomHttpsClient(client);
// this should time out
CardPaymentRequest req = new CardPaymentRequest();
req.setAmount(100.00)
.setOrderNumber(getRandomOrderId("test"));
req.getCard()
.setName("John Doe")
.setNumber("5100000010001004")
.setExpiryMonth("12")
.setExpiryYear("18")
.setCvd("123");
boolean timedOut = false;
try {
PaymentResponse response = beanstream.payments().makePayment(req);
} catch (BeanstreamApiException ex) {
if ("Connection error".equalsIgnoreCase( ex.getMessage()) )
timedOut = true;
}
} | 2 |
private void findMinimalDistances(Vertex node) {
List<Vertex> adjacentNodes = getNeighbors(node);
Vertex lasttarget = null;
for (Vertex target : adjacentNodes) {
System.out.println("target.toString() " + target.toString());
if (getShortestDistance(target) > getShortestDistance(node)
+ getDistance(node, target)) {
distance.put(target, getShortestDistance(node)
+ getDistance(node, target));
predecessors.put(target, node);
unSettledNodes.add(target);
}
for (int i = 0; i < ds.notoknumber.length - 1; i++) {
if (predecessors.get(target) != null) {
if (ds.notoknumber[i + 1] == Integer.parseInt(predecessors.get(target).getId()) && ds.notoknumber[i] == Integer.parseInt(target.getId())) {
predecessors.remove(target);
predecessors.remove(lasttarget);
distance.remove(target);
distance.remove(lasttarget);
}
}
}
lasttarget = target;
//System.out.println("predecessors.get(target) " + predecessors.get(target));
//System.out.println("predecessors.get(predecessors.get(target) " + predecessors.get(predecessors.get(target)));
//System.out.println("predecessors.get(predecessors.get(predecessors.get(target))) " + predecessors.get(predecessors.get(predecessors.get(target))) + "\n");
}
} | 6 |
public OptionFileMenu(final boolean ouvrir) {
setPreferredSize(new java.awt.Dimension(600,400));
final JFileChooser arbre = new JFileChooser();
if(ouvrir) {
setTitle("Ouvrir...");
} else {
setTitle("Enregistrer...");
arbre.setApproveButtonText("Sauvegarder");
}
getContentPane().add(arbre);
arbre.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)) {
dispose();
}else if(arg0.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
if(ouvrir) {
MainFrame.getCurrentDessin().open(arbre.getSelectedFile());
} else {
if(arbre.getSelectedFile() != null) {
MainFrame.getCurrentDessin().saveAs(arbre.getSelectedFile());
} else {
MainFrame.getCurrentDessin().saveAs(new File(arbre.getName()));
}
}
dispose();
}
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
} | 5 |
@Override
public void act() {
if (canMove()) {
if (head.getSteps() == 0) {
oldDirection = direction;
direction = head.getDirection();
}
switch (direction) {
case NORTH:
this.animation = upAnimation;
this.y--;
break;
case EAST:
this.animation = rightAnimation;
this.x++;
break;
case SOUTH:
this.animation = downAnimation;
this.y++;
break;
case WEST:
this.animation = leftAnimation;
this.x--;
break;
}
}
if (head.canMove() && time > 0) {
time--;
}
if (time == 0) {
move = true;
direction=head.getDirection();
time = -1;
}
} | 9 |
public Shape addItem(Shape item) {
if (item == null) {
return null;
}
items.add(item);
repaint();
return item;
} | 1 |
private void getTimerPage(HttpServletResponse response, UserSession session, Map<String, Object> pageVariables) throws ServletException, IOException {
Long userId = (session != null) ? session.getId() : null;
if (userId != null) {
pageVariables.put("time", new Date().toString());
pageVariables.put("userId", userId);
pageVariables.put("refreshPeriod", "1000");
sendResponse(response, Templates.TIMER_TPL, pageVariables);
} else {
response.sendRedirect(Pages.MAIN_PAGE);
}
} | 2 |
private int getLevenshteinDistance(String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Can not deal with null strings");
}
if (s.length() == 0) return t.length();
if (t.length() == 0) return s.length();
int n = s.length();
int m = t.length();
int d[][] = new int[n + 1][m + 1];
int cost;
// matrix initialization
for (int i = 0; i <= n; i++) d[i][0] = i;
for (int j = 0; j <= m; j++) d[0][j] = j;
for (int i = 1; i <= n; i++) {
char v = s.charAt(i - 1);
for (int j = 1; j <= m; j++) {
char w = t.charAt(j - 1);
if (v == w) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + cost);
}
}
return d[n][m];
} | 9 |
public Piece(TorrentByteStorage bucket, int index, int offset, int length,
byte[] hash) {
this.bucket = bucket;
this.index = index;
this.offset = offset;
this.length = length;
this.hash = hash;
// Piece is considered invalid until first check.
this.valid = false;
// Piece start unseen
this.seen = 0;
this.data = null;
} | 0 |
public void setLocationManually(Point point) {
moving = true;
myAutoPoint = point;
if(myView != null){
setLocation(myView.transformFromAutomatonToView(point));
}
} | 1 |
public void Init()
{
Decoder.InitBitModels(Models);
} | 0 |
@EventHandler
public void onPlace(BlockPlaceEvent e) {
Player player = e.getPlayer();
Location loc = e.getBlockAgainst().getLocation();
if (e.getBlockAgainst().getType() == Material.SIGN
|| e.getBlockAgainst().getType() == Material.SIGN_POST
|| e.getBlockAgainst().getType() == Material.WALL_SIGN) {
Sign sign = (Sign) e.getBlockAgainst().getState();
World world = player.getWorld();
int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
if (MainClass.ports.contains("Signs.Port." + world.getName()
+ "/" + x + "/" + y + "/" + z)) {
if (MainClass.warps.contains("Warps."
+ ChatColor.stripColor(sign.getLine(2)))) {
destx = MainClass.warps.getInt("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".x");
desty = MainClass.warps.getInt("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".y");
destz = MainClass.warps.getInt("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".z");
destyaw = MainClass.warps.getInt("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".yaw");
destpitch = MainClass.warps.getInt("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".pitch");
final World finalWorld = Bukkit
.getWorld(MainClass.warps.getString("Warps."
+ ChatColor.stripColor(sign.getLine(2))
.toString() + ".world"));
dest = new Location(finalWorld, destx, desty, destz,
destyaw, destpitch);
player.teleport(dest);
e.setCancelled(true);
}
}
}
} | 5 |
public ListNode reverseKGroup(ListNode head, int k) {
if (k <= 1 || head == null) {
return head;
}
ListNode lastTail = null;
ListNode tail = head;
int count = 0;
Stack<ListNode> stack = new Stack<ListNode>();
while (tail != null) {
stack.push(tail);
tail = tail.next;
count++;
if (count >= k) {
while (!stack.isEmpty()) {
ListNode tmp = stack.pop();
if (lastTail != null) {
lastTail.next = tmp;
} else {
head = tmp;
}
lastTail = tmp;
}
lastTail.next = tail;
count = 0;
}
}
return head;
} | 6 |
boolean detectNegation() {
for (int i = 0; i < elements.length; i++) {
//termes permettant de valider une négation
if (Pattern.matches("ne|pas|jamais|rien|aucun|aucune|n|impossible|moins|peu", elements[i])) {
// expression regulière
return true;
}
else {
//particularité pour "loin d'être"
if (i < elements.length - 2) {
if (Pattern.matches("loin", elements[i])
&& Pattern.matches("d", elements[i + 1])
&& Pattern.matches("être", elements[i + 2])) {
return true;
}
}
}
}
return false;
} | 6 |
@Override
public TKey getKey() {
return _key;
} | 0 |
public static UnitTag getName(char tag) {
if (mapping == null) {
mapping = new HashMap<Character, UnitTag>();
for (UnitTag ut : values()) {
mapping.put(ut.tag, ut);
}
}
return mapping.get(tag);
} | 2 |
public boolean addStudent(Student stu) {
String insert = "INSERT INTO STUDENT VALUES(?,?,?,?,?,?,?)";
int n = 0;
try {
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, stu.no);
ps.setString(2, stu.name);
ps.setString(3, stu.sex);
ps.setDate(4, stu.birthday);
ps.setString(5, stu.address);
ps.setString(6, stu.tel);
ps.setString(7, stu.email);
n = ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
return n == 1;
} | 1 |
public Command getCommand(int commandCode) throws Exception
{
Class<? extends Command> cls = dictCodeToClass.get(commandCode);
if(cls == null )
throw new UnknownCommandException();
return cls.newInstance();
} | 2 |
public static void main(String[] args) {
// -------------------------Initialize Job Information------------------------------------
String startJobId = "job_201301181454_0001";
//String startJobId = "job_201212172252_0001";
//String jobName = "uservisits_aggre-pig-256MB";
//String jobName = "SampleWordCountWiki";
//String jobName = "BuildCompIndex-m36-r18";
//String jobName = "Wiki-m36-r18";
//String jobName = "BigTwitterInDegreeCount";
//String jobName = "big-uservisits_aggre-pig-256MB";
//String jobName = "BigTwitterBiDirectEdgeCount";
//String jobName = "BigTeraSort";
//String jobName = "SampleTeraSort-1G";
String jobName = "Big-uservisits_aggre-pig-50G";
//String jobName = "Big-uservisits_aggre-pig-50G";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments2/";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments3/";
//String baseDir = "/home/xulijie/MR-MEM/NewExperiments3/";
//String baseDir = "/home/xulijie/MR-MEM/SampleExperiments/";
String baseDir = "/home/xulijie/MR-MEM/BigExperiments/";
int reduceBase = 9;
boolean onlineEstimate = false;
String hostname = "master";
int iterateNum = 192;
int[] splitMBs = {64, 128, 256};
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/Wiki-m36-r18-256MB/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/uservisits_aggre-pig-256MB/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments/TeraSort-256MB-m36-r18/estimatedJvmCost/";
//String outputDir = "/home/xulijie/MR-MEM/NewExperiments2/BuildCompIndex-m36-r18-256MB/estimatedJvmCost/";
String outputDir = baseDir + jobName + "/estimatedJvmCost/";
boolean needMetrics = true; //going to analyze task counters/metrics/jvm?
int sampleMapperNum = 0; // only analyze the first sampleMapperNum mappers (0 means all the mappers)
int sampleReducerNum = 0; // only analyze the first sampleReducerNum reducers (0 means all the reducers)
boolean useRuntimeMaxJvmHeap = false; //since reducers' actual JVM heap is less than mapred.child.java.opts,
//this parameter determines whether to use the actual JVM heap to estimate
//--------------------------Setting ends------------------------------------
DecimalFormat nf = new DecimalFormat("0000");
for(int i = 0; i < iterateNum; i++) {
String prefix = startJobId.substring(0, startJobId.length() - 4);
int suffix = Integer.parseInt(startJobId.substring(startJobId.length() - 4));
String jobId = prefix + nf.format(suffix + i);
//--------------------------Profiling the run job-----------------------------
AllBatchJobMemoryEstimator je = new AllBatchJobMemoryEstimator();
boolean successful;
if(onlineEstimate == true)
successful = je.profile(hostname, jobId, needMetrics, sampleMapperNum, sampleReducerNum);
else
successful = je.profile(baseDir, jobName, "serialJob", jobId);
//--------------------------Profiling ends-----------------------------
if(splitMap.isEmpty())
computeSplitMap(splitMBs, je.job.getJobConfiguration());
//--------------------------Estimating Data Flow and Memory-----------------------------
if(successful == false) {
System.err.println("[" + jobId + "] is a failed job");
continue;
}
try {
je.batchEstimateDataAndMemory(useRuntimeMaxJvmHeap, outputDir + jobId, reduceBase);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//--------------------------Estimating ends-----------------------------
System.out.println("Finish estimating " + jobId);
}
} | 5 |
public static StationDAO getInstance(Connection conn){
if(instance == null)
instance = new StationDAO(conn);
return instance;
} | 1 |
public boolean equals(Object obj) {
if (obj == this) { // simple case
return true;
}
// now try to reject equality...
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof XYDrawableAnnotation)) {
return false;
}
XYDrawableAnnotation that = (XYDrawableAnnotation) obj;
if (this.x != that.x) {
return false;
}
if (this.y != that.y) {
return false;
}
if (this.width != that.width) {
return false;
}
if (this.height != that.height) {
return false;
}
if (!ObjectUtilities.equal(this.drawable, that.drawable)) {
return false;
}
// seem to be the same...
return true;
} | 8 |
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics graphic = bs.getDrawGraphics();
graphic.setColor(Color.black);
graphic.fillRect(0, 0, getWidth(), getHeight());
obejectHandler.render(graphic);
graphic.dispose();
bs.show();
} | 1 |
private byte[] encrypt(EncryptableObject o, Key key) throws Exception{
String Algrithem;
if(key instanceof PublicKey){Algrithem = "RSA";}
else{Algrithem = "AES";}
ByteArrayInputStream i = new ByteArrayInputStream(o.toByteArray());
Cipher cipher = Cipher.getInstance(Algrithem);
cipher.init(Cipher.ENCRYPT_MODE, key);
ByteArrayOutputStream out = new ByteArrayOutputStream();
CipherOutputStream ciph = new CipherOutputStream(out, cipher);
byte[] buf = new byte[2048];
int read;
while((read=i.read(buf))!=-1){//reading data
ciph.write(buf,0,read); //writing encrypted data
ciph.flush();
}
out.close();
ciph.close();
i.close();
return out.toByteArray();
} | 2 |
public Games()
{
super(new BorderLayout());
addGame(Zombies.class);
addGame(Testing.class);
addGame(Monsters.class);
addGame(AsteroidMission.class);
addGame(PolyCreator.class);
setBackground(Save.PLAYER_COLOR);
final JPanel topRow = new JPanel();
topRow.setBackground(Save.PLAYER_COLOR);
topRow.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Save.PLAYER_COLOR.darker().darker()));
final JPanel bottomRow = new JPanel();
bottomRow.setBackground(Save.PLAYER_COLOR);
bottomRow.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Save.PLAYER_COLOR.darker().darker()));
for (ModContainer mc : Loader.getContainerList())
{
mc.initMethod(State.POST_INIT);
}
Loader.addEventToAll(new GameEvent(this));
options = new GameButton("Options", this);
options.setToolTipText("Options, Adjust Gameplay");
options.setVisible(true);
final Font small = new Font("Helvetica", Font.BOLD | Font.ITALIC, 24);
title = new JLabel("Games", SwingConstants.CENTER);
title.setVisible(true);
title.setFont(small);
title.setForeground(Save.PLAYER_COLOR.darker().darker());
title.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Save.PLAYER_COLOR.darker().darker()));
add(title, BorderLayout.NORTH);
add(topRow, BorderLayout.CENTER);
add(bottomRow, BorderLayout.SOUTH);
topRow.add(options);
for (int i = 0; i < Games.customTopButtons.size(); i++)
{
topRow.add(Games.customTopButtons.get(i));
}
for (int i = 0; i < Games.customBottomButtons.size(); i++)
{
bottomRow.add(Games.customBottomButtons.get(i), BorderLayout.NORTH);
}
if (Games.thirdRow.size() > 0)
{
for (int i = 0; i < Games.thirdRow.size(); i++)
{
bottomRow.add(Games.thirdRow.get(i), BorderLayout.SOUTH);
}
}
} | 5 |
public static int reverseBits(int n) {
for (int i = 0; i < 16; i++) {
int j = 31 - i;
int a = n & (1 << i);
int b = n & (1 << j);
if ((0 == a && 0 == b) || (0 != a && 0 != b)) continue;
n = n ^ (1 << i);
n = n ^ (1 << j);
}
return n;
} | 5 |
public void report_error(String message, Object info)
{
System.err.print(message);
System.err.flush();
if (info instanceof Symbol)
if (((Symbol)info).left != -1)
System.err.println(" at character " + ((Symbol)info).left +
" of input");
else System.err.println("");
else System.err.println("");
} | 2 |
protected void fireClientConnectEvent(ConnectOnServerEvent evt) {
if (clientConnectListenerList != null) {
Object[] listeners = clientConnectListenerList.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==ConnectOnServerListener.class) {
((ConnectOnServerListener)listeners[i+1]).OnClientConnectEvent(evt);
}
}
}
} | 3 |
public void alignBottom(ArrayList<Element> selectedElements) {
/* Most lowest */
int minBottom = Integer.MIN_VALUE;
int currentBottom = 0;
for (Element e : selectedElements) {
if (e instanceof AbsPlace) {
AbsPlace a = (AbsPlace) e;
currentBottom = a.getY() + a.getHeight();
}
if (e instanceof Node) {
Node n = (Node) e;
currentBottom = n.getY() + n.getHeight();
}
if (e instanceof Transition) {
Transition t = (Transition) e;
currentBottom = t.getY() + t.getHeight();
}
if (currentBottom > minBottom) {
minBottom = currentBottom;
}
// Arc is nothing //
}
for (Element e : selectedElements) {
if (e instanceof AbsPlace) {
AbsPlace a = (AbsPlace) e;
a.setY(minBottom - a.getHeight());
}
if (e instanceof Node) {
Node n = (Node) e;
n.setY(minBottom - n.getHeight());
}
if (e instanceof Transition) {
Transition t = (Transition) e;
t.setY(minBottom - t.getHeight());
}
// Arc is nothing //
}
} | 9 |
public String toString ()
{
StringBuffer buf = new StringBuffer (20);
buf.append ("usb");
buf.append ('-');
buf.append (busId);
if (port.length != 0) {
buf.append ('-');
for (int i = 0; i < port.length; i++) {
if (i != 0)
buf.append ('.');
// workaround for kjc 1.0.6 bug where
// port[i] was handled as char not int
buf.append (Integer.toString (port [i]));
}
}
return buf.toString ();
} | 3 |
public static ActionStatusEnumeration fromString(String v) {
if (v != null) {
for (ActionStatusEnumeration c : ActionStatusEnumeration.values()) {
if (v.equalsIgnoreCase(c.toString())) {
return c;
}
}
}
throw new IllegalArgumentException(v);
} | 3 |
public void opRel(){
int op = stop.pop();
switch (op) {
case EGAL : iegal();
break;
case DIFFERENT : idiff();
break;
case INF : iinf();
break;
case INFOUEG : iinfegal();
break;
case SUP : isup();
break;
case SUPOUEG : isupegal();
break;
default : System.out.println("erreur dans opREL YVM");
}
} | 6 |
@Override
public void run() {
String data = this.plugin.getFileMan().read(this.plugin.chatFile());
JSONArray jArray;
try {
jArray = (JSONArray) new JSONParser().parse(data);
for(int i=0;i<jArray.size();i++){
JSONObject json = (JSONObject) jArray.get(i);
String time = (String) json.get("time");
try {
Date date = this.fmt.parse(time);
if(date.getTime()<new Date().getTime()-this.plugin.historyChat()){
jArray.remove(i);
}
} catch (ParseException e) {
this.plugin.logMessage("Invalid date format: "+e.getMessage());
}
}
this.plugin.getFileMan().write(this.plugin.chatFile(), jArray);
} catch (org.json.simple.parser.ParseException ex) {
if(ex.getMessage()!=null){
this.plugin.logMessage("Error while parsing JSON: "+ex.getMessage());
}
}
} | 5 |
public BSplaynForm (ArrayList<Excel> allEx)
{
allex = allEx;
setColoredExes();
} | 0 |
public Command(String command, ClientCluster c){
try{
System.out.println("["+c.getID()+"] "+c.getClient().getUsername()+") " + command);
command = command.replaceFirst("Command ", "");
if(ClientHandler.getDataQueuer().isRealUser(c.getClient())){
if(ClientHandler.getDataQueuer().getUserConfig(c.getClient()).hasPermission("Console.Commands")){
if(ClientHandler.getDataQueuer().getUserConfig(c.getClient()).canUseCommand(rawCommand(command))||ClientHandler.getDataQueuer().getUserConfig(c.getClient()).canUseCommand("all")){
Bukkit.dispatchCommand(Bukkit.getServer().getConsoleSender(), command);
}else{
c.getDataTransfer().sendMessage("Sorry but you don't have permissions for doing that command!");
}
}else{
c.getDataTransfer().sendMessage("Sorry but you don't have permissions for doing commands!");
}
}
}catch(Exception e){
try{
c.getDataTransfer().sendMessage("Failed to do your command!");
}catch(Exception ex){}
}
} | 6 |
public void visitInnerClassType(final String name) {
if (state != CLASS_TYPE) {
throw new IllegalStateException();
}
CheckMethodAdapter.checkIdentifier(name, "inner class name");
if (sv != null) {
sv.visitInnerClassType(name);
}
} | 2 |
private void startGetSchemaElement(String name, Attributes attrs) {
if (name.equals("slideshow")) {
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getQName(i).equals("xsi:noNamespaceSchemaLocation")) {
// get the schema path
String path = attrs.getValue(i);
// ensure unix type file path
path = path.replace('\\', '/');
if (path.substring(0, 5).equals("http:")) {
try {
schemaPath = RemoteFileRetriever.downloadFile(path);
} catch (MalformedURLException e) {
System.out
.println("Could not download remote schema"
+ e.getMessage());
}
} else if (path.charAt(1) == ':')
// absolute path
schemaPath = path;
else if (path.charAt(0) == '/')
// relative to SafetyNet directory
schemaPath = path;
else if (!path.contains("/")) {
// get path of xml and remove xml file name, append
// schema path
int directoryPathEnd = xmlPath.lastIndexOf('/');
String directoryPath = xmlPath.substring(0,
directoryPathEnd + 1);
schemaPath = directoryPath + path;
}
}
}
}
} | 8 |
final public void GrammarComponent(GrammarSection section, Scope scope) throws ParseException {
ParsedElementAnnotation e;
Annotations a;
a = Annotations();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Definition(section, scope, a);
break;
case 7:
Include(section, scope, a);
break;
case 6:
Div(section, scope, a);
break;
default:
jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_14:
while (true) {
if (jj_2_4(2)) {
;
} else {
break label_14;
}
e = AnnotationElementNotKeyword();
section.topLevelAnnotation(e);
}
} | 8 |
public void keyPressed(KeyEvent e) {
char keychar = e.getKeyChar();
int keycode = e.getKeyCode();
if (keycode>=0 && keycode < 256) {
keymap[keycode]=true;
lastkey=keycode;
lastkeychar=keychar;
if (wakeup_key==-1 || wakeup_key==keycode) {
if (!eng.isRunning()) {
eng.start();
// key is cleared when it is used as wakeup key
keymap[keycode]=false;
}
}
}
/* shift escape = exit */
if (e.isShiftDown ()
&& e.getKeyCode () == KeyEvent.VK_ESCAPE
&& !eng.isApplet()) {
System.exit(0);
}
//System.out.println(e+" keychar"+e.getKeyChar());
} | 8 |
@Override
public void setCell(int x, int y, boolean live) {
if (y<0 || y>=getHeight()) return;
if (x<0 || x>=getWidth()) return;
if (live)
world[y][x] = 0;
} | 5 |
public static JGSystem getInstance() {
if (instance == null) {
instance = new JGSystem();
}
return instance;
} | 1 |
public static Symbol destructureMethodNameTree(Stella_Object nametree, Object [] MV_returnarray) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(nametree);
if (testValue000 == Stella.SGT_STELLA_CONS) {
{ Cons nametree000 = ((Cons)(nametree));
if (!Stella_Object.symbolP(nametree000.value)) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Illegal method name: `" + Stella_Object.deUglifyParseTree(nametree000) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
{ Symbol _return_temp = null;
MV_returnarray[0] = null;
return (_return_temp);
}
}
if (nametree000.rest.value == Stella.SYM_STELLA_SETTER) {
{ Symbol _return_temp = Symbol.yieldSetterMethodName(((Symbol)(nametree000.value)));
MV_returnarray[0] = Stella.NIL;
return (_return_temp);
}
}
else {
{ Symbol _return_temp = ((Symbol)(nametree000.value));
MV_returnarray[0] = nametree000.rest;
return (_return_temp);
}
}
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol nametree000 = ((Symbol)(nametree));
{ Symbol _return_temp = nametree000;
MV_returnarray[0] = Stella.NIL;
return (_return_temp);
}
}
}
else {
{ Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Illegal method name: `" + Stella_Object.deUglifyParseTree(nametree) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001);
}
}
{ Symbol _return_temp = null;
MV_returnarray[0] = null;
return (_return_temp);
}
}
}
} | 6 |
public static Boolean canUnowned(PermissionFlag flag) {
if (flag.equals(ChunkyPermissions.BUILD))
return getBoolean(UNOWNED_BUILD);
if (flag.equals(ChunkyPermissions.DESTROY))
return getBoolean(UNOWNED_DESTROY);
if (flag.equals(ChunkyPermissions.ITEM_USE))
return getBoolean(UNOWNED_SWITCH);
if (flag.equals(ChunkyPermissions.SWITCH))
return getBoolean(UNOWNED_SWITCH);
return null;
} | 4 |
public boolean exist(ValueType value) {
if (!this.isEmpty()) {
SetElement<ValueType> help = head;
while (help != tail.getNext()) {
if (help.getValue() == value) {
return true;
}
help = help.getNext();
}
return false;
} else {
return false;
}
} | 3 |
public String[] getInput() {
Scanner inFile = new Scanner(System.in);
System.out.println("\n\t________________________________________________________________________");
System.out.println("\n\t You must enter names for two players before starting a two player game.");
System.out.println("\n\t________________________________________________________________________");
int playerIndex = 0;
boolean listComplete = false;
while (playerIndex < 2 && !listComplete) {
System.out.println("\n\t Please Enter a name for this player, or \'Q\' to quit.");
String playerName;
playerName = inFile.nextLine();
playerName = playerName.trim();
if (playerName.length() < 1) {
new MemoryGameError().displayError("\n\t A name must be at least "
+ "one character long. Try again or \'Q\' to quit.");
continue;
}
if (playerName.equals("computer")) {
new MemoryGameError().displayError(
"\n\t Memory, is a mind training game, you cannot play against a computer."
+ " please enter another name, or \'Q\' to quit.");
continue;
}
if (alreadyListed(playerNameList, playerName)) {
new MemoryGameError().displayError(
"\n\t That name has already been entered. Please enter another"
+ " name, or \'Q\' to quit.");
continue;
}
if (playerName.toUpperCase().equals("Q")) { // quit?
listComplete = true;
break;
}
this.playerNameList[playerIndex] = playerName;
playerIndex++;
}
String[] newNameList = new String[playerIndex];
for (int i = 0; i < playerIndex; i++) {
newNameList[i] = this.playerNameList[i];
}
newNameList = this.sortList(newNameList);
this.displayNameList(newNameList); // display the list of names
return newNameList;
} | 7 |
public void insert(int bno)
{
Node temp, fNode, parent;
temp = new Node(bno);
try
{
if(root == null)
root = temp;
else
{
fNode = root;
while(true)
{
parent = fNode;
if(bno < fNode.getbno())
{
fNode = fNode.getLeft();
if(fNode==null)
{
parent.setLeft(temp);
return;
}
}
else
{
fNode = fNode.getRight();
if(fNode==null)
{
parent.setRight(temp);
return;
}
}
}
}
}
catch(Exception e)
{
System.out.println("Exception occured: "+e.getMessage());
System.exit(0);
}
} | 6 |
public void mouseDragged(MouseEvent e)
{
if(e.getX()>x && e.getX()<x+width)
{
if(e.getY()>y && e.getY()<y+height)
{
selected=true;
}
}
if(selected)
{
mouseX=e.getX();
mouseY=e.getY();
}
} | 5 |
@Override
public void run() {
while (isRunning) {
if (direction == 'u') {
moveCol(-1);
}
if (direction == 'd') {
moveCol(1);
}
if (direction == 'l') {
moveRow(-1);
}
if (direction == 'r') {
moveRow(1);
}
eatPellet(pacmanCol, pacmanRow);
maze.checkCollision();
maze.repaint();
try {
Thread.sleep(150);
} catch (InterruptedException e) {
System.err.println(e);
}
}
} | 6 |
public void printAllInterleavingsRecurr(String str1, String str2, String interleaving, int m, int n) {
/* If we used all characters from str1 and there are some left in str2 */
if (m == str1.length() && n < str2.length()) {
System.out.println(interleaving + str2.substring(n));
return;
}
/* If we used all characters from str2 and there are some left in str1 */
if (n == str2.length() && m < str1.length()) {
System.out.println(interleaving + str1.substring(m));
return;
}
/* If we used all characters from both strings */
if (m == str1.length() && n == str2.length()) {
System.out.println(interleaving);
}
/* Case: interleaving "continues" with a character from str1 */
printAllInterleavingsRecurr(str1, str2, interleaving + str1.charAt(m), m + 1, n);
/* Case: interleaving "continues" with a character from str2 */
printAllInterleavingsRecurr(str1, str2, interleaving + str2.charAt(n), m, n + 1);
} | 6 |
private Type simplePeek(Frame frame) {
Type type = frame.peek();
return (type == Type.TOP) ? frame.getStack(frame.getTopIndex() - 1) : type;
} | 1 |
private void debugPrintMoveList() {
for(int move : moveList) {
switch(move) {
case Move.RIGHT:
System.out.println("right");
break;
case Move.DOWN:
System.out.println("down");
break;
case Move.UP:
System.out.println("up");
break;
case Move.LEFT:
System.out.println("left");
break;
case Move.START:
System.out.println("start");
break;
case Move.SELECT:
System.out.println("select");
break;
case Move.A:
System.out.println("a");
break;
}
}
System.out.println();
} | 8 |
public void Clear(){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
this.block[i][j] = 0;
}
}
} | 2 |
public static long inverseModulo(long a, long m) {
if (a <= 1 || m <= 1 || Num2.euclideEtendu(a, m)[0] != 1) throw new IllegalArgumentException();
long x0 = Num2.euclideEtendu(a, m)[1];
while (x0 < 0) {
x0 += m;
}
return x0;
} | 4 |
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(Frm_Permissoes.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_Permissoes.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_Permissoes.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_Permissoes.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new Frm_Permissoes().setVisible(true);
}
});
} | 6 |
@Override
public double getVariance() throws VarianceException {
if (alpha > 2) {
return Math.pow(beta / (alpha - 1), 2) / (alpha - 2);
} else {
throw new VarianceException("InverseGamma variance alpha > 2.");
}
} | 1 |
public String getDescription() {
return description;
} | 0 |
public void sendReply_cgibin_zoomin_cgi(MyHTTPServer socket, List<HTTPRequestData> getData, String cookie) throws Exception
{
List<String> reply = new ArrayList<String>();
addHTTP200(reply, cookie);
addPageHeader(reply, "");
int width = 920;
int height = 150;
String host = null;
HTTPRequestData hostData = MyHTTPServer.findRecord(getData, "host");
if (hostData != null && hostData.getData() != null)
host = URLDecoder.decode(hostData.getData(), defaultCharset);
String service = null;
HTTPRequestData serviceData = MyHTTPServer.findRecord(getData, "service");
if (serviceData != null && serviceData.getData() != null)
service = URLDecoder.decode(serviceData.getData(), defaultCharset);
String dataSource = null;
HTTPRequestData dataSourceData = MyHTTPServer.findRecord(getData, "dataSource");
if (dataSourceData != null && dataSourceData.getData() != null)
dataSource = URLDecoder.decode(dataSourceData.getData(), defaultCharset);
String heading = host;
if (service != null)
heading += " | " + service;
if (dataSource != null)
heading += " | " + dataSource;
reply.add("<H1>" + heading + "</H1>");
reply.add("<IMG SRC=\"" + sparkLineUrl(host, service, dataSource, width, height, true) + "\" BORDER=\"1\"><BR>");
addPageTail(reply, true);
socket.sendReply(reply);
} | 8 |
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
} | 1 |
private void createProperties(){
Properties prop = new Properties();
OutputStream output = null;
String fileName = System.getProperty("user.dir") + "/config/config.properties";
File file = new File(fileName);
//if ( !(file.exists())) {
//Create properties file
File directory = new File(file.getParentFile().getAbsolutePath());
try {
directory.mkdirs();
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
//Write to properties file
try {
output = new FileOutputStream("config/config.properties");
// set the properties value
prop.setProperty("Sync", "SYES");
prop.setProperty("Sync_Start", "SYBE");
prop.setProperty("Sync_End", "SYEN");
prop.setProperty("Life", "LIFE");
prop.setProperty("Stat_Req", "SYSR");
prop.setProperty("Stat_Msg", "STAT");
prop.setProperty("Handshake_Request", "A");
prop.setProperty("Handshake_Confirm", "B");
prop.setProperty("Telegram_length", "128");
prop.setProperty("Tele_Warehouse_task", "WT");
prop.setProperty("Tele_Confirm_warehouse_task", "WTCO");
prop.setProperty("Name_EWM", "EWM");
prop.setProperty("Name_PLC", "CONV1");
prop.setProperty("Tele_Wtcc", "WTCC");
prop.setProperty("Tele_Sp", "SP");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}//end of try
//}//end of if
}//end of method | 4 |
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("students.xml"));
Element root = doc.getDocumentElement();
recursionElement(root);
} | 0 |
private boolean jj_3_49() {
if (jj_3R_68()) return true;
if (jj_3R_66()) return true;
return false;
} | 2 |
private Row[] getViewToModel()
{
if (viewToModel == null)
{
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++)
{
viewToModel[row] = new Row(row);
}
if (isSorting())
{
Arrays.sort(viewToModel);
}
}
return viewToModel;
} | 3 |
void updateSizes( direction d )
{
edge f;
switch( d )
{
case UP:
f = head.leftEdge;
if ( null != f )
f.updateSizes( direction.UP );
f = head.rightEdge;
if ( null != f )
f.updateSizes(direction.UP);
topsize++;
break;
case DOWN:
f = siblingEdge();
if (null != f)
f.updateSizes(direction.UP);
f = tail.parentEdge;
if ( null != f )
f.updateSizes( direction.DOWN );
bottomsize++;
break;
}
} | 6 |
public void pop(String function, boolean result)
{
Integer start = startStack.pop();
callStack.pop();
if (traceOn)
{
System.out.println(
"<- " + level-- +
": " + function +
"(" + (result ? "true" : "false") +
",s=" + start +
",l=" + (index - start) +
",e=" + errorIndex + ")");
}
if (!result)
{
if (index > errorIndex)
{
errorIndex = index;
errorStack = new Stack<String>();
errorStack.addAll(callStack);
}
else if (index == errorIndex && errorStack.isEmpty())
{
errorStack = new Stack<String>();
errorStack.addAll(callStack);
}
}
else
{
if (index > errorIndex) errorIndex = 0;
}
} | 7 |
private int handleCH(String value,
DoubleMetaphoneResult result,
int index) {
if (index > 0 && contains(value, index, 4, "CHAE")) { // Michael
result.append('K', 'X');
return index + 2;
} else if (conditionCH0(value, index)) {
//-- Greek roots ("chemistry", "chorus", etc.) --//
result.append('K');
return index + 2;
} else if (conditionCH1(value, index)) {
//-- Germanic, Greek, or otherwise 'ch' for 'kh' sound --//
result.append('K');
return index + 2;
} else {
if (index > 0) {
if (contains(value, 0, 2, "MC")) {
result.append('K');
} else {
result.append('X', 'K');
}
} else {
result.append('X');
}
return index + 2;
}
} | 6 |
public static void main(String[] args) {
make_translate();
String delimiter = "\t";
String infile = "C:\\Users\\kbaas.000\\Documents\\autoredistrict_data\\vtd_data.txt";
String outfile = "C:\\Users\\kbaas.000\\Documents\\autoredistrict_data\\vtd_data_out.txt";
Vector<String[]> records = readDelimited(new File(infile),delimiter,"\n");
int source_col = 0;
int geoid_col = 0;
String[] hss = records.get(0);
for( int i = 0; i < hss.length; i++) {
if( hss[i].equals("SLDL_2010")) {
source_col = i;
break;
}
}
for( int i = 0; i < hss.length; i++) {
if( hss[i].equals("GEOID10")) {
geoid_col = i;
break;
}
}
String[] hss2 = new String[hss.length+5];
for( int i = 0; i < hss.length; i++) {
hss2[i] = hss[i].trim();
}
hss2[hss.length+0] = "SLDL10_1";
hss2[hss.length+1] = "SLDL10_2";
hss2[hss.length+2] = "SLDL10_4";
hss2[hss.length+3] = "SLDL10_8";
hss2[hss.length+4] = "SLDL10_16";
records.set(0,hss2);
for( int j = 1; j < records.size(); j++) {
String[] ss = records.get(j);
String[] ss2 = new String[ss.length+5];
for( int i = 0; i < ss.length; i++) {
ss2[i] = ss[i].trim();
}
int n1 = Integer.parseInt(ss[source_col]);
int n2 = translation_lookup[n1];
int n4 = (n2 + n2 % 2)/2;
int n8 = (n4 + n4 % 2)/2;
int n16 = (n8 + n8 % 2)/2;
ss2[ss.length+0] = ""+n1;
ss2[ss.length+1] = ""+n2;
ss2[ss.length+2] = ""+n4;
ss2[ss.length+3] = ""+n8;
ss2[ss.length+4] = ""+n16;
if( fix_geoid) {
ss2[geoid_col] = "0"+ss2[geoid_col];
}
records.set(j, ss2);
}
writeDelimited(new File(outfile),delimiter,"\n",records);
} | 8 |
public JButton getConnect4Button() {
boolean test = false;
if (test || m_test) {
System.out.println("GameSelecter :: getConnect4Button() BEGIN");
}
if (test || m_test) {
System.out.println("GameSelecter :: getConnect4Button() END");
}
return m_connect4;
} | 4 |
final void s(int i) {
anInt5445++;
if (aClass290_5520 != null)
((Class290) aClass290_5520).aBoolean3709
= Class264.method2015(i, anInt5472, 7);
if (aClass290_5460 != null)
((Class290) aClass290_5460).aBoolean3709
= Class183.method1379(4, anInt5472, i);
if (aClass290_5482 != null)
((Class290) aClass290_5482).aBoolean3709
= Class348_Sub42_Sub8_Sub2.method3200(i, anInt5472, (byte) 73);
if (aClass290_5424 != null)
((Class290) aClass290_5424).aBoolean3709
= Class126.method1113(i, anInt5472, -10);
anInt5463 = i;
aBoolean5402 = true;
if (aClass151_5503 != null
&& (anInt5463 & 0x10000 ^ 0xffffffff) == -1) {
aShortArray5438 = ((Class151) aClass151_5503).aShortArray2060;
aShortArray5436 = ((Class151) aClass151_5503).aShortArray2058;
aShortArray5493 = ((Class151) aClass151_5503).aShortArray2067;
aByteArray5499 = ((Class151) aClass151_5503).aByteArray2069;
aClass151_5503 = null;
}
method663(262144);
} | 6 |
public void executeSQL(String sql) {
if (conn == null)
return;
try {
Statement stmt = null;
if (sql.contains("?") && handler != null) {
PreparedStatement pstmt = conn.prepareStatement(sql);
handlerCall(pstmt);
stmt = pstmt;
} else {
stmt = conn.createStatement();
}
if (stmt instanceof PreparedStatement) {
PreparedStatement pstmt = (PreparedStatement) stmt;
pstmt.execute();
} else {
stmt.execute(sql);
}
if (handler != null) {
ResultSet resultSet = stmt.getResultSet();
int updateCount = stmt.getUpdateCount();
DBResult result = new DBResult(updateCount, resultSet);
handlerCall(result);
}
if (!conn.getAutoCommit()) {
conn.commit();
}
} catch (SQLException e) {
try {
if (!conn.getAutoCommit()) {
conn.rollback();
}
} catch (SQLException e1) {
exceptionHandler.handle(e1);
}
exceptionHandler.handle(e);
}
} | 9 |
public Villager makeBaby(){
if(village.getPopulation() <= village.getMAX_POP()){ //there is room
if(!dude){ //girl
if(kids <= MAX_BABIES){ //if less than the maximum amount of babies
if(health > 18 && health < 60){ //18 - 60
if(babyCoolDown == 0){ //wants kids
if(village.getPopulation() > 2){ //people in town
int x = 0 + (int) (Math.random() * (100 - 0));
if(x > 75){ //25% chance making baby
Villager baby = new Villager(village, Random.randBool());
baby.mom = this;
baby.health = 0;
kids++;
babyCoolDown = 0 + (int) (Math.random() * (15 - 0));
return baby;
}
}
}
}
}
}
}
return null;
} | 8 |
public static boolean doLauncherUpdate(Stack<String> updateQueue, JSONObject versionsConfig) {
Logger.info("Updater.doLauncherUpdate", "Starting update...");
//Show progress
GlobalDialogs.showProgressDialog();
GlobalDialogs.setProgressCaption("Cleaning...");
GlobalDialogs.setProgressIndeterminate(true);
//Clean patch directory
Logger.info("Updater.doLauncherUpdate", "Cleaning patch directory...");
try {
if (new File("./update/launcherpatch").isDirectory()) {
FileUtils.deleteDirectory(new File("./update/launcherpatch"));
}
} catch (IOException ex) {
Logger.error("Updater.doLauncherUpdate", "Failed to clean the patch directory!", false, ex);
GlobalDialogs.hideProgressDialog();
GlobalDialogs.showNotification("Failed to clean the patch directory!");
return false;
}
//Download and extract patches
while (!updateQueue.empty()) {
//Load update from JSON
String updateName = updateQueue.pop();
JSONObject update = getVersionByName(updateName, "moddle", versionsConfig);
//Update status
GlobalDialogs.setProgressCaption("Getting patch '" + updateName + "'...");
//Download version patch
Logger.info("Updater.doLauncherUpdate", "Downloading patch '" + updateName + "'...");
try {
FileUtils.copyURLToFile(new URL(update.get("patch").toString()), new File("./update/moddle-" + updateName + "-patch.zip"));
} catch (IOException ex) {
Logger.error("Updater.doLauncherUpdate", "Failed to download patch!", false, ex);
GlobalDialogs.hideProgressDialog();
GlobalDialogs.showNotification("Failed to download patch '" + updateName + "'!");
return false;
}
//Extract version patch
Logger.info("Updater.doLauncherUpdate", "Extracting patch '" + updateName + "'...");
try {
Util.decompressZipfile("./update/moddle-" + updateName + "-patch.zip", "./update/launcherpatch");
} catch (ZipException ex) {
Logger.error("Updater.doLauncherUpdate", "Failed to extract patch!", false, ex);
GlobalDialogs.hideProgressDialog();
GlobalDialogs.showNotification("Failed to extract patch '" + updateName + "'!");
return false;
}
}
//Update status
GlobalDialogs.setProgressCaption("Restarting...");
//Start MUpdate
ProcessBuilder updater = new ProcessBuilder(new String[] { "javaw.exe", "-jar", "\"" + Util.getFullPath("./update/MUpdate.jar") + "\"", "--version=" + versionsConfig.get("latestmoddle").toString() });
updater.directory(new File("./update"));
try {
updater.start();
} catch (Exception ex) {
Logger.error("Updater.doLauncherUpdate", "Failed to start MUpdate!", false, ex);
GlobalDialogs.hideProgressDialog();
GlobalDialogs.showNotification("Could not start MUpdate!");
return false;
}
//Exit Moddle
GlobalDialogs.hideProgressDialog();
System.exit(0);
return true;
} | 6 |
public TextResourceFile(String filename) {
is = ClassLoader.getSystemResourceAsStream(filename);
if (is == null)
throw new MissingResourceException(filename, null, null);
} | 1 |
public void processLeft(Stack<XPathContext> contextStack, Stack state) throws XPathException {
XPathContext context = contextStack.peek();
final Controller controller = context.getController();
XPathContext c2 = context.newMinorContext();
c2.setOrigin(this);
Result result;
OutputURIResolver resolver = (href == null ? null : controller.getOutputURIResolver());
if (href == null) {
result = controller.getPrincipalResult();
} else {
try {
String base;
if (resolveAgainstStaticBase) {
base = baseURI;
} else {
base = controller.getCookedBaseOutputURI();
}
String hrefValue = EscapeURI.iriToUri(href.evaluateAsString(context)).toString();
try {
result = resolver.resolve(hrefValue, base);
//System.err.println("Resolver returned " + result);
} catch (Exception err) {
throw new XPathException("Exception thrown by OutputURIResolver", err);
}
if (result == null) {
resolver = StandardOutputResolver.getInstance();
result = resolver.resolve(hrefValue, base);
}
} catch (TransformerException e) {
throw XPathException.makeXPathException(e);
}
}
checkAcceptableUri(context, result);
traceDestination(context, result);
Properties computedLocalProps = gatherOutputProperties(context);
String nextInChain = computedLocalProps.getProperty(SaxonOutputKeys.NEXT_IN_CHAIN);
if (nextInChain != null && nextInChain.length() > 0) {
try {
result = controller.prepareNextStylesheet(nextInChain, baseURI, result);
} catch (TransformerException e) {
throw XPathException.makeXPathException(e);
}
}
// TODO: cache the serializer and reuse it if the serialization properties are fixed at
// compile time (that is, if serializationAttributes.isEmpty). Need to save the serializer
// in a form where the final output destination can be changed.
SerializerFactory sf = c2.getConfiguration().getSerializerFactory();
PipelineConfiguration pipe = controller.makePipelineConfiguration();
pipe.setHostLanguage(Configuration.XSLT);
Receiver receiver = sf.getReceiver(result, pipe, computedLocalProps);
c2.changeOutputDestination(receiver,
true,
validationAction,
schemaType);
SequenceReceiver out = c2.getReceiver();
out.open();
state.push(out);
state.push(resolver);
state.push(result);
contextStack.push(c2);
} | 9 |
private void setGeneratorsToPopulation() {
if (mapAdders != null) {
for (int i = 0; i < mapAdders.length; i++) {
mapAdders[i].stopAdding();
}
}
List<GeneratorIndividual<T>> individuals = gaPop.getIndividuals();
mapAdders = new CloudMapThread[generators.size()];
for (int i = 0; i < generators.size(); i++) {
generators.get(i).setGenerator((individuals
.get(i)).getGenerator());
generators.get(i).clear();
mapAdders[i] = new CloudMapThread(generators.get(i));
mapAdders[i].setPriority(Thread.MIN_PRIORITY);
mapAdders[i].start();
}
} | 3 |
public String getMethodAccessor(String name, String desc, String accDesc,
MethodInfo orig)
throws CompileError
{
String key = name + ":" + desc;
String accName = (String)accessors.get(key);
if (accName != null)
return accName; // already exists.
ClassFile cf = clazz.getClassFile(); // turn on the modified flag.
accName = findAccessorName(cf);
try {
ConstPool cp = cf.getConstPool();
ClassPool pool = clazz.getClassPool();
MethodInfo minfo
= new MethodInfo(cp, accName, accDesc);
minfo.setAccessFlags(AccessFlag.STATIC);
minfo.addAttribute(new SyntheticAttribute(cp));
ExceptionsAttribute ea = orig.getExceptionsAttribute();
if (ea != null)
minfo.addAttribute(ea.copy(cp, null));
CtClass[] params = Descriptor.getParameterTypes(accDesc, pool);
int regno = 0;
Bytecode code = new Bytecode(cp);
for (int i = 0; i < params.length; ++i)
regno += code.addLoad(regno, params[i]);
code.setMaxLocals(regno);
if (desc == accDesc)
code.addInvokestatic(clazz, name, desc);
else
code.addInvokevirtual(clazz, name, desc);
code.addReturn(Descriptor.getReturnType(desc, pool));
minfo.setCodeAttribute(code.toCodeAttribute());
cf.addMethod(minfo);
}
catch (CannotCompileException e) {
throw new CompileError(e);
}
catch (NotFoundException e) {
throw new CompileError(e);
}
accessors.put(key, accName);
return accName;
} | 6 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.