text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void func_48708_d()
{
this.blockRefCount = 0;
this.tickRefCount = 0;
for (int var1 = 0; var1 < 16; ++var1)
{
for (int var2 = 0; var2 < 16; ++var2)
{
for (int var3 = 0; var3 < 16; ++var3)
{
int var4 = this.getExtBlockID(var1, var2, var3);
if (var4 > 0)
{
if (Block.blocksList[var4] == null)
{
this.blockLSBArray[var2 << 8 | var3 << 4 | var1] = 0;
if (this.blockMSBArray != null)
{
this.blockMSBArray.set(var1, var2, var3, 0);
}
}
else
{
++this.blockRefCount;
if (Block.blocksList[var4].getTickRandomly())
{
++this.tickRefCount;
}
}
}
}
}
}
} | 7 |
public static ArrayList<MstxInfo> getMstxRecommend() {
ArrayList<MstxInfo> result = new ArrayList<MstxInfo>();
Connection con = DBUtil.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = con
.prepareStatement("select info_title,info_dis,info_lon,info_lat,a.info_time,a.uid,a.mid from mstx_info as a, mstx_recommend as b where a.mid = b.mid");
rs = pstmt.executeQuery();
while (rs.next()) {
String info_title = rs.getString(1);
String info_dis = rs.getString(2);
String info_lon = rs.getString(3);
String info_lat = rs.getString(4);
Date info_time = rs.getDate(5);
String uid = rs.getString(6);
String mid = rs.getString(7);
MstxInfo mi = new MstxInfo(info_title, info_dis, info_lon, info_lat, info_time, uid, mid);
result.add(mi);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
} | 8 |
public void setFile(String file) {
this.file = file;
this.path = assemblePath(this.path_list);
} | 0 |
public void keyReleased(KeyEvent e){
//
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_LEFT){
acceleration = 0;
stance = Stance.forward;
img = imgForward;
}
if (speed == 0){
stance = Stance.nomove;
img = imgForward;
}
if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN){
dy = 0;
img = imgForward;
stance = Stance.forward;
}
} | 5 |
public GMLTokenMarker() {
super();
schemes.add(new BlockDescriptor(S_DOC_COMMENT, "/\\*(?=\\*)", "\\*/", profile)); //$NON-NLS-1$ //$NON-NLS-2$
schemes.add(new BlockDescriptor(S_BLOCK_COMMENT, "/(?=\\*)", "\\*/", profile)); //$NON-NLS-1$ //$NON-NLS-2$
schemes.add(new BlockDescriptor(S_DOC_LINE_COMMENT, "///", "$", profile)); //$NON-NLS-1$ //$NON-NLS-2$
schemes.add(new BlockDescriptor(S_LINE_COMMENT, "//", "$", profile)); //$NON-NLS-1$ //$NON-NLS-2$
schemes.add(new BlockDescriptor(S_DOUBLEQ_STRING, "\"", "\"", profile)); //$NON-NLS-1$ //$NON-NLS-2$
schemes.add(new BlockDescriptor(S_SINGLEQ_STRING, "'", "'", profile)); //$NON-NLS-1$ //$NON-NLS-2$
functions = addKeywordSet(S_FUNCTIONS, profile);
for (Function f : GMLKeywords.FUNCTIONS) {
Collections.addAll(functions.words, f.getName());
}
constructs = addKeywordSet(S_CONSTRUCTS, profile);
for (Construct c : GMLKeywords.CONSTRUCTS) {
Collections.addAll(constructs.words, c.getName());
}
operators = addKeywordSet(S_OPERATORS, profile);
for (Operator o : GMLKeywords.OPERATORS) {
Collections.addAll(operators.words, o.getName());
}
constants = addKeywordSet(S_CONSTANTS, profile);
for (Constant c : GMLKeywords.CONSTANTS) {
Collections.addAll(constants.words, c.getName());
}
variables = addKeywordSet(S_VARIABLES, profile);
for (Variable v : GMLKeywords.VARIABLES) {
Collections.addAll(variables.words, v.getName());
}
tmKeywords.add(functions);
tmKeywords.add(constructs);
tmKeywords.add(operators);
tmKeywords.add(constants);
tmKeywords.add(variables);
CharSymbolSet css = new CharSymbolSet(S_OPS_AND_SEPS, profile);
char[] ca = "{[()]}!%^&*-/+=?:~<>.,;".toCharArray(); //$NON-NLS-1$
for (int i = 0; i < ca.length; i++) {
css.chars.add(ca[i]);
}
tmChars.add(css);
otherTokens.add(new SimpleToken(S_NUMERIC_LITERAL, "[0-9]+", profile)); //$NON-NLS-1$
otherTokens.add(new SimpleToken(S_HEX_LITERAL, "\\$[0-9A-Fa-f]+", profile)); //$NON-NLS-1$
} | 6 |
public void load(String file) throws UnknownHostException, PersistencyException, FileNotFoundException {
RoutingTable routingTable = new RoutingTable();
PersistencyDelegate bootstrapService = new XMLPersistencyService();
bootstrapService.load(file, routingTable);
context_.setRoutingTable(routingTable);
Host localhost = routingTable.getLocalhost();
CorbaFactory corbaFactory = new CorbaFactory();
ORB orb = corbaFactory.getInstance(
localhost.getAddress().getHostName(), localhost.getPort());
try {
POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootPOA.the_POAManager().activate();
} catch (InvalidName ignored) {
} catch (AdapterInactive ignored) {
}
// shutdown logging
((com.sun.corba.se.spi.orb.ORB) orb).getLogger(CORBALogDomains.RPC).setLevel(Level.OFF);
// Thread orbThread = new Thread(new OrbRunnable(orb));
// orbThread.start();
context_.setOrb(orb);
logger_.info("[init] Localhost instance: {}:{} [path: {}]",
new Object[]{
localhost.getAddress(),
localhost.getPort(),
localhost.getHostPath()});
} | 2 |
public int indexOf(int[] array, int x){
for (int i =0 ; i < array.length ;i++ ) {
if(array[i] == x)
return i;
}
return -1;
} | 2 |
public static void main(String[] args) {
System.out.print("Enter the array's length\n");
int userNumber = sc.nextInt();
int[] array = new int[userNumber];
for (int i = 0; i < userNumber; i++){
array[i] = r.nextInt(100);
}
System.out.println(Arrays.toString(array)+"-before sorting\n");
int userChoice;
do {
userChoice = showMenu();
switch(userChoice){
case 1: MegaSorter sort1 = new MegaSorter(new BubbleSort());
sort1.setDelegate(new BubbleSort());
sort1.sort(array);
System.out.println("Bubble sort is completed");
System.out.println(Arrays.toString(array)+"-after sorting\n");
break;
case 2: MegaSorter sort2 = new MegaSorter(new MergeSort());
sort2.setDelegate(new MergeSort());
sort2.sort(array);
System.out.println("Merge sort is completed");
System.out.println(Arrays.toString(array)+"-after sorting\n");
break;
case 3: MegaSorter sort3 = new MegaSorter(new CountSort());
sort3.setDelegate(new CountSort());
sort3.sort(array);
System.out.println("Count sort is completed");
System.out.println(Arrays.toString(array)+"-after sorting\n");
break;
case 4: MegaSorter sort4 = new MegaSorter(new TreeSort());
sort4.setDelegate(new TreeSort());
sort4.sort(array);
System.out.println("Tree sort is completed");
System.out.println(Arrays.toString(array)+"-after sorting\n");
break;
default: break;
}
} while (userChoice != 0);
} | 6 |
private void setup()
{
try
{
bom = BookingOptionsManager.getInstance();
} catch (IOException ex)
{
Logger.getLogger(OptionsGui.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
options = bom.getAll();
} catch (SQLException ex)
{
Logger.getLogger(OptionsGui.class.getName()).log(Level.SEVERE, null, ex);
}
for(BookingOptions b: options)
{
if(b.getType().equalsIgnoreCase("outdoor"))
{
txtOutdoorPrice.setText(b.getPrice()+"");
txtOutdoorRentalFrom.setText(b.getRentableFromDate());
txtOutdoorRentalTo.setText(b.getRentableToDate());
txtOutdoorRentalTimeFrom.setText(b.getRentableFromTime()/60 + ":" +b.getRentableFromTime()%60);
txtOutdoorRentalTimeTo.setText(b.getRentableToTime()/60 + ":" + b.getRentableToTime()%60);
}
else if(b.getType().equalsIgnoreCase("indoor"))
{
txtIndoorPrice.setText(b.getPrice()+"");
txtIndoorRentalFrom.setText(b.getRentableFromDate());
txtIndoorRentalTo.setText(b.getRentableToDate());
txtIndoorRentalTimeFrom.setText(b.getRentableFromTime()/60 + ":" +b.getRentableFromTime()%60);
txtIndoorRentalTimeTo.setText(b.getRentableToTime()/60 + ":" + b.getRentableToTime()%60);
}
}
} | 5 |
private CubeSerializable getPlayerTeamArea(DodgeballPlayer p) {
if(p.getTeam() == TEAM_1) {
return TEAM_1_AREA;
} else {
return TEAM_2_AREA;
}
} | 1 |
public static void update() {
for (int i = 0; i < NUM_KEYS; i++) {
prevKeyState[i] = keyState[i];
}
} | 1 |
public void clear(int v) {
// Remove v from the list of vertices
if (startVertex == v) {
startVertex = vertices[v];
} else {
int i = startVertex;
while (vertices[i] != v) {
i = vertices[i];
if (i == -1) {
return;
}
}
vertices[i] = vertices[v];
}
vertices[v] = -1;
numVertices--;
// first delete the edges that don't start at you
// Now delete the columns
for (int i = 0; i < domainSize; i++) {
int num = numEdges(i, v);
if (num != 0) {
numEdges -= num;
numMultiEdges -= (num - 1);
setValue(i, v, 0);
}
}
// Now, clear all edges involving v
// first the row This is done long ways as this might be faster as it
// can write an int at a time
long startBit = domainSize * CELL_SIZE * v;
long endBit = domainSize * CELL_SIZE * (v + 1);
int startInt = (int) (startBit / 32);
int endInt = (int) (endBit / 32);
int endIndex = (int) (endBit % 32);
int startIndex = (int) (startBit % 32);
if (startInt == endInt) {
// If the whole row is contain within the current int
int m = 0xFFFFFFFF << (domainSize * CELL_SIZE);
m |= (1 << startIndex) - 1;
edges[startInt] &= m;
} else {
// clear the starting int
if (startIndex != 0) {
// Need to only clear the END of the starting int
int m = (1 << startIndex) - 1;
edges[startInt] &= m;
startInt++;
}
while (startInt < endInt) {
edges[startInt++] = 0;
}
// Clear as much of the last index as needed
if (endIndex != 0) {
int m = 0xFFFFFFFF << endIndex;
edges[endInt] &= m;
}
}
} | 9 |
public static JSONObject JSONObjectOfGenomeFromId(JSONArray organizedJson, int id){
int len = organizedJson.length();
int i,j,k,l;
JSONObject json = new JSONObject();
boolean ok = false;
for(i = 0; i < len && !ok; i++)
{
JSONArray groups = organizedJson.getJSONObject(i).getJSONArray("groups");
int leng = groups.length();
for(j = 0; j < leng && !ok; j++)
{
JSONArray subgroups = groups.getJSONObject(j).getJSONArray("subgroups");
int lens = subgroups.length();
for(k = 0; k < lens && !ok; k++)
{
JSONArray genomes = subgroups.getJSONObject(k).getJSONArray("genomes");
int lenc = genomes.length();
for(l = 0; l < lenc && !ok; l++)
{
JSONObject genome = genomes.getJSONObject(l);
if(genome.getInt("genome_id") == id){
json = genome;
ok = true;
}
}
}
}
}
return json;
} | 9 |
private void comandoSenao() {
//<senao> ::= “senao” “{“ <lista_comandos> “}” “;”
System.out.println("To no Senão");
if (tipoDoToken[1].equals(" senao")) {
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" {")) {
if (!acabouListaTokens()) {
nextToken();
this.listaComandos();
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
System.out.println("não tem mais comandos no senão");
// if (!acabouListaTokens()) {
// //nextToken();
if (tipoDoToken[1].equals(" }")) {
System.out.println("fechei a chave do senão");
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" ;")) {
//FIM DO SENÃO
System.out.println("TENHO COMANDO SENÃO AQUI");
}
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}
// } else {
// errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
// zerarTipoToken();
// }
}
} else {
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição");
zerarTipoToken();
}
}
} | 7 |
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
} | 2 |
public Color(double iR, double iG, double iB) {
R = iR < 0 ? 0 : iR > 1 ? 1 : iR;
G = iG < 0 ? 0 : iG > 1 ? 1 : iG;
B = iB < 0 ? 0 : iB > 1 ? 1 : iB;
} | 6 |
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void handleHangingEntities(HangingBreakByEntityEvent event) {
if (!(event.getRemover() instanceof Player))
return;
Player player = (Player) event.getRemover();
User user = EdgeCoreAPI.userAPI().getUser(player.getName());
if (user == null)
return;
if (event.getEntity() instanceof ItemFrame || event.getEntity() instanceof Vine) {
if (Cuboid.getCuboid(event.getEntity().getLocation()) != null) {
Cuboid c = Cuboid.getCuboid(event.getEntity().getLocation());
if (c.getCuboidType() == CuboidType.Survival.getTypeID())
return;
if (!Flag.hasFlag(c, Flag.BreakBlocks, player.getName())) {
event.setCancelled(true);
player.sendMessage(EdgeCoreAPI.languageAPI().getColoredMessage(user.getLanguage(), "cuboid_nopermission"));
}
}
}
} | 7 |
@Override
public void displayHistory(List<PlayerAction> AllActions, List<PlayerAction> ReleventActions) {
final String newline = "<br>";
String HistoryText = "<html>";
for(PlayerAction Action : ReleventActions){
HistoryText += Action.print() + newline;
}
HistoryText += "</html>";
String CompleteText = "<html>";
for(PlayerAction Action : AllActions){
CompleteText += Action.print() + newline;
}
CompleteText += "</html>";
final JDialog dialog = new JDialog(null, "Quantum Werewolves", Dialog.ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setLocationRelativeTo(null);
JScrollPane ReleventTab = new JScrollPane(new JLabel(HistoryText));
JScrollPane CompleteTab = new JScrollPane(new JLabel(CompleteText));
JTabbedPane TabPane = new JTabbedPane();
TabPane.addTab("Relevent History", ReleventTab);
TabPane.addTab("Complete History", CompleteTab);
JPanel somePanel = new JPanel();
somePanel.setLayout(new BorderLayout());
somePanel.add(new JLabel("These are lists of actions taken during the game, thank you for playing."),BorderLayout.NORTH);
somePanel.add(TabPane, BorderLayout.CENTER);
JButton button = new JButton("Close Game");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dialog.setVisible(false);
}
});
somePanel.add(button, BorderLayout.SOUTH);
dialog.add(somePanel);
dialog.pack();
dialog.setSize(new Dimension(600,300));
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
} | 2 |
public static void main(String[] args) {
// Working with Stacks
Stack<String> pez = new Stack<String>();
pez.push("Candy 1");
pez.push("Candy 2");
pez.push("Candy 3");
pez.push("Candy 4");
String candy4 = pez.pop();
String candy3 = pez.pop();
System.out.println(candy4);
System.out.println(candy3);
System.out.println(pez.peek());
System.out.println(pez.search("Candy 1"));
} | 0 |
private void capture( Unit unit, State state ){
state.setProvLoyalty(unit.getLoyalty());
state.setInCapture(true);
Turn.addEvent(new com.nasser.poulet.conquest.model.Event(1, state.getProductivity() , state, new Callback<State>(){
public void methodCallback(State state) {
if(state.isInCapture()){
state.setInCapture(false);
if(state.getLoyalty() != state.getProvLoyalty() && state.getLoyalty() != Loyalty.EMPTY && state.getLoyalty() != Loyalty.NONE) {
board.getStateArrayList()[state.getLoyalty().ordinal() - 2].remove(state);
}
state.setLoyalty(state.getProvLoyalty());
board.getStateArrayList()[state.getLoyalty().ordinal() - 2].add(state);
state.generateUnitSpawnCallback();
}
}
}));
} | 4 |
@Override
public void onMessage(String channel, String sender, String login,
String hostname, String message)
{
for ( IRCMsgResponse response : mResponses )
{
if ( response.canHandleMessage(sender, message) )
{
response.handleMessage(sender, message);
List<String> replies = response.getReplies();
if ( replies!=null && !replies.isEmpty() )
{
for ( String reply : replies )
{
if ( !replies.isEmpty() )
{
sendMessage(channel, reply);
}
}
}
}
}
} | 6 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
public void DBWrite(String[] insert) {
try {
Date d1 = null;
Date d2 = null;
d1 = form.parse(insert[5]);
d2 = form.parse(insert[4]);
long t = d1.getTime() - d2.getTime();
Date dt = new Date();
dt.setTime(t);
//System.err.println(form.format(dt));
Runnable r = new DBInsert(insert[0].replace(" PeerAddress ", ""), insert[2].replace(" PeerAddress ", ""),
insert[3], insert[4], insert[5], Boolean.valueOf(insert[7]), typeAppel, insert[9]);
Thread ccm = new Thread(r);
ccm.setName("SYSLOG-DBINSERT");
ccm.start();
//System.err.println("Saved To Database");
} catch (Exception ex) {
Logger.getLogger(SyslogServer.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
private boolean promptSaveState() {
DisplayState state = this.constructDisplayState();
if(state.equals(study.getDisplayState()))
// Don't warn if nothing to save.
return true;
//Custom button text
Object[] options = {"Yes",
"No",
"Cancel"};
int n = JOptionPane.showOptionDialog(this,
"Save Display State?",
"MedImage",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if(n == 0) { // "Yes", save display state
study.saveDisplayState(state);
}
// If user clicked yes or no, follow through with action. Otherwise, if
// user clicked cancel or closed dialog, cancel action.
return n != 2 && n != JOptionPane.CLOSED_OPTION;
} | 3 |
public void setMovie(Movie movie) {
if (movie == null) {
throw new NullObjectInsertionException();
}
this.movie = movie;
} | 1 |
public static Map initMap(Map newPopMap){
Map newMap = null;
for(int i=0; i<=newPopMap.populationDensity; i++){
newMap = populateMap(newPopMap);
}
for(int i = 0; i<= newMap.tileMap[0].length-1; i++){
for(int c = 0; c<= newMap.tileMap.length-1; c++){
if(newMap.tileMap[c][i] == null){
newMap.tileMap[c][i] = Game.loadedMapResources.allTiles.get(1);
}
//Fill in any un-populated holes with standard grass
}
}
return newMap;
} | 4 |
private static void findEnemyFlag(Board b) {
int row, col;
row = enemyHQL.getRow();
col = enemyHQL.getCol();
// if it is certain that enemy flag is on the left
if (b.getPiece(row, col).getRank().equals(Rank.Flag) &&
!b.getPiece(row, col).getOurSide()) {
enemyFlag = new Position(row, col);
}
else {
row = enemyHQR.getRow();
col = enemyHQR.getCol();
// if we haven't capture the right side HQ
// then we just assume the flag is on the right side
if (!b.getPiece(row, col).getOurSide() &&
!b.getPiece(row, col).getRank().equals(Rank.Empty) &&
b.getPiece(row, col).getcBeFlag()) {
enemyFlag = new Position(row, col);
}
else {
// this HQ is captured by us, or it is empty now,
// the other HQ must have the flag
row = enemyHQL.getRow();
col = enemyHQL.getCol();
enemyFlag = new Position(row, col);
}
}
} | 5 |
public static int parseTime(String format) { // Parses XhYm format and turns it into seconds
int total = 0;
if (!format.matches("[0-9]*h?[0-9]*m?")) return -1;
if (format.matches("[0-9]+")) return (Integer.parseInt(format)) * 60;
if (format.matches("[0-9]+m")) return (Integer.parseInt(format.split("m")[0])) * 60;
if (format.matches("[0-9]+h")) return (Integer.parseInt(format.split("h")[0])) * 120;
if (format.matches("[0-9]+h[0-9]+m")) {
String[] time = format.split("[mh]");
return (Integer.parseInt(time[0]) * 120) + (Integer.parseInt(time[1])) * 60;
}
return -1;
} | 5 |
private List<SplitCell> detectPotentialSplit(double[][] costs, int[] assigns, SegmentedImage A, SegmentedImage B, double ep){
List<SplitCell> result = new ArrayList<SplitCell>();
for(int i = 0; i < costs.length; i++){
List<ProcessedCell> temp = new ArrayList<ProcessedCell>();
if(assigns[i] == -1) continue;
double weight = costs[i][assigns[i]];
for(int j = 0; i < costs[0].length; j++){
if(weight/costs[i][j] >= ep){
temp.add(B.getCell(j));
}
}
if(temp.size() > 1){
result.add(new SplitCell(A.getCell(i), temp));
}
}
return result;
} | 5 |
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("under50.teleport")) {
sender.sendMessage(ChatColor.RED + "No access");
return true;
}
Player who, toWhom;
if (args.length == 1 && sender instanceof Player) {
who = (Player) sender;
toWhom = Bukkit.getServer().getPlayer(args[0]);
} else if (args.length == 2) {
who = Bukkit.getServer().getPlayer(args[0]);
toWhom = Bukkit.getServer().getPlayer(args[1]);
} else {
sender.sendMessage(ChatColor.RED + "Improper usage.");
return true;
}
if (who == null || toWhom == null) {
sender.sendMessage(ChatColor.RED + "Player not found");
return true;
}
who.teleport(toWhom);
sender.sendMessage(ChatColor.GREEN + "Teleported " + who.getName() + " to " + toWhom.getName());
return true;
} | 6 |
public static final void charSelected(final SeekableLittleEndianAccessor slea, final MapleClient c) {
final int charId = slea.readInt();
final String macs = slea.readMapleAsciiString();
if (loginFailCount(c) || !c.login_Auth(charId)) {
c.getSession().close();
return;
}
c.updateMacs(macs);
if (c.hasBannedMac()) {
c.getSession().close();
return;
}
if (c.getIdleTask() != null) {
c.getIdleTask().cancel(true);
}
//c.getSession().write(LoginPacket.getServerIP(InetAddress.getByName("127.0.0.1"), 7575, charId));
c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION, c.getSessionIPAddress());
String channelServerIP = MapleClient.getChannelServerIPFromSubnet(c.getSessionIPAddress(), c.getChannel());
try {
if (channelServerIP.equals("0.0.0.0")) {
String[] socket = LoginServer.getInstance().getIP(c.getChannel()).split(":");
c.getSession().write(LoginPacket.getServerIP(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1]), charId));
} else {
String[] socket = LoginServer.getInstance().getIP(c.getChannel()).split(":");
c.getSession().write(LoginPacket.getServerIP(InetAddress.getByName(channelServerIP), Integer.parseInt(socket[1]), charId));
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
} | 6 |
public static void print_array (int n, int[] Arr_1, int[] Arr_2) {
if ( n < 6 ) {
for (int i = 0; i<n; i++) {
System.out.println (Arr_1[i] + " " + Arr_2[i]);
}
}
if ( n >= 6 && n != 10) {
for (int i = 0; i<5; i++) {
System.out.println (Arr_1[i] + " " + Arr_2[i]);
}
for (int i = 5; i<n; i++) {
System.out.println (Arr_1[i] + " (niente)");
}
}
if ( n == 10) {
for (int i = 0; i<5; i++) {
System.out.println (Arr_1[i] + " " + Arr_2[i]);
}
for (int i = 5; i<9; i++) {
System.out.println (Arr_1[i] + " (niente)");
}
System.out.println ("(niente) (niente)");
}
} | 9 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return ((Invoice) data.values().toArray()[rowIndex]).getNumber();
case 1:
return ((Invoice) data.values().toArray()[rowIndex]).getClient().getSortKey();
case 2:
String datestring = ((Invoice) data.values().toArray()[rowIndex]).getDate();
Date date = new Date();
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse(datestring);
} catch (ParseException ex) {
Logger.getLogger(InvoiceTableModel.class.getName()).log(Level.SEVERE, null, ex);
}
return date;
case 3:
return ((Invoice) data.values().toArray()[rowIndex]).getPrimaryKeyValue();
default:
return "Error";
}
} | 5 |
private byte[] checkUserPassword(
byte[] userPassword, byte[] firstDocIdValue, int keyBitLength,
int revision, byte[] oValue, byte[] uValue, int pValue,
boolean encryptMetadata)
throws
GeneralSecurityException,
EncryptionUnsupportedByProductException,
PDFParseException {
// Algorithm 3.6: Authenticating the user password
// Step 1: Perform all but the last step of Algorithm 3.4 (Revision 2)
// or Algorithm 3.5 (Revision 3 or greater) using the supplied password
// string
//
// I.e., figure out what the general key would be with the
// given password
// Algorithm 3.4/5,Step1:
// Determine general key based on user password, as per Algorithm 3.2
final byte[] generalKey = calculateGeneralEncryptionKey(
userPassword, firstDocIdValue, keyBitLength,
revision, oValue, pValue, encryptMetadata);
// Algorithm 3.4/5,RemainingSteps:
final byte[] calculatedUValue =
calculateUValue(generalKey, firstDocIdValue, revision);
// Step 2: If the result of step 1 is equal to the value of the
// encryption dictionaryâs U entry (comparing on the first 16 bytes in
// the case of Revision 3 or greater), the password supplied is the
// correct user password. The key obtained in step 1 (that is, in the
// first step of Algorithm 3.4 or 3.5) can be used to decrypt the
// document using Algorithm 3.1 on page 119.
assert calculatedUValue.length == 32;
if (uValue.length != calculatedUValue.length) {
throw new PDFParseException("Improper U entry length; " +
"expected 32, is " + uValue.length);
}
// Only the first 16 bytes are significant if using revision > 2
final int numSignificantBytes = revision == 2 ? 32 : 16;
for (int i = 0; i < numSignificantBytes; ++i) {
if (uValue[i] != calculatedUValue[i]) {
return null;
}
}
return generalKey;
} | 4 |
protected String getStatus() {
StringBuilder buf = new StringBuilder();
buf.append("Turns left: ").append(turns).append("\n");
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
buf.append(map[i][j].toString());
}
buf.append('\n');
}
for (IBomber bomber : bombers) {
buf.append(bomber.toString()).append('\n');
}
for (Bomb b : collectBombs()) {
buf.append(b.toString()).append('\n');
}
buf.append('\n');
buf.append('\n');
return buf.toString();
} | 4 |
public void waitForClientToStart() throws IOException {
while (true) {
String msg = inStream.readLine();
if ("START".equals(msg)) {
break;
}
}
} | 2 |
public void syncDatabase(int syncType, String syncData, HttpServletResponse response)
{
try
{
if(syncType == SyncTypes.SYNC_TRANSACTION)
{
// IF TRANSACTION IS SYNCED THEN RUN THE DATA QUERY IN THE SERVER TABLES
new WriteBase().execute(syncData, new Object[]{});
sendResponse(response, Boolean.TRUE.toString());
}
else if(syncType == SyncTypes.SYNC_MASTER)
{
// IF MASTER IS BEING SYNCED THEN CHECK TABLE FOR LATEST INFO. IF THERE THEN SEND INCREMENTAL UPDATE/INSERT
System.out.println("Syncing Master Table");
String updateQuery = "";
for (SyncTable syncTable : tablesToSync)
{
if(!syncTable.getTableType().equals("Master"))
continue;
String selectQuery = "Select * from " +syncTable.getName();
// String selectQuery = "Select * from " +syncTable.getName() +" WHERE client_version != server_version AND server_version > 0;";
updateQuery = getMasterData(selectQuery, syncTable.getName());
if (!updateQuery.equals(""))
{
sendResponse(response, updateQuery);
}
}
}
else if (syncType == SyncTypes.SYNC_SCHEMA)
{
// IF SCHEMA IS BEING SYNCED CHECK CHANGES TO THE SCHEMA AND DO THE NECESSARY UPDATES
}
}
catch(SQLException se)
{
se.printStackTrace();
try {
sendResponse(response, null);
} catch (IOException e) {
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
} | 9 |
public String getPasswordByUID(Statement statement,String phonenumber)//根据用户名获取密码
{
String result = null;
sql = "select password from Users where phonenumber = '" + phonenumber +"'";
try
{
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
result = rs.getString("password");
}
}
catch (SQLException e)
{
System.out.println("Error! (from src/Fetch/Users.getPasswordByUID())");
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} | 2 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
public void incrementRound(Player roundWinner) throws IOException{
// Round complete, add a score to the winner
clock.stop();
roundWinner.setScore(roundWinner.getScore() + 1);
if(roundWinner.getScore() < maxScore){
// continue playing
roundCount++;
setPlayerRoles();
resetPositions();
}
else{
// Save game and redirect
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
h.addHistory(sdf.format(d), p1.getName(), p2.getName(), p1.getScore() + ":" + p2.getScore(), clock.getTime());
cong.setState(Cong.STATE.FINISHED);
}
} | 1 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Cell) {
Cell<?> other = (Cell<?>) obj;
return getRow() == other.getRow() && getColumn() == other.getColumn()
&& Objects.equal(getValue(), other.getValue());
}
return false;
} | 6 |
@Override
public void run() {
Elevator elevator = null;
while (elevator == null) {
if (this.currentFloor > this.requestedFloor){
elevator = this.building.CallDown(currentFloor);
}
if (this.currentFloor < this.requestedFloor){
elevator = this.building.CallUp(currentFloor);
}
}
synchronized(elevator) {
System.out.println("Rider " + riderID+ " has figured its elevator");
boolean entered = false;
while (!entered) {
entered = elevator.Enter(this);
if (!entered) System.out.println("Denied from elevator");
}
System.out.println("Rider " + riderID+ " has entered");
write("Rider " + riderID + " has entered " + "E" + elevator.elevatorId);
elevator.RequestFloor(this, requestedFloor);
/**
* if the rider doesn't make a request, we force him out of the elevator
*/
if (this.haveRequested = false) {
elevator.Exit(this);
}
}
System.out.println("Rider " + riderID+ " has requested floor " + requestedFloor);
elevator.Exit(this);
/**
* if the rider never exits the elevator, we kill the thread using return statement and decrement the waitCount
*/
if(this.haveExited = false) {
elevator.decrementCounter(elevator.getFloor());
return;
}
System.out.println("Rider " + riderID+ " has exited " + "E" + elevator.elevatorId);
write("Rider " + riderID+ " has exited " + "E" + elevator.elevatorId);
} | 7 |
private static void offerAction() {
println( "Now, choose what to do." );
println( "(d)isplay all urinals, (o)ccupy urinal, (s)hake at urinal, (q)uit game: " );
while( true ) {
print( "Action: " );
String input = scanner.next();
if( input.equalsIgnoreCase( "d" ) ) {
displayAllUrinals();
} else if( input.equalsIgnoreCase( "o" ) ) {
if( !tryToOccupyUrinalAndSurvive() ) {
break;
}
} else if( input.equalsIgnoreCase( "s" ) ) {
shakeAtUrinal();
} else if( input.equalsIgnoreCase( "q" ) ) {
break;
} else{
println( "That's an invalid command. Here they are again:" );
println( "(d)isplay all urinals, (o)ccupy urinal, (s)hake at urinal, (q)uit game: " );
}
}
} | 6 |
private void doSend(final CEMILData f, final KNXnetIPConnection.BlockingMode m,
final boolean positiveConfirmation) throws KNXTimeoutException,
KNXConnectionClosedException
{
l.received = null;
t.send(f, m);
if (m == noblock) {
while (t.getState() == ConnectionBase.ACK_PENDING)
try {
Thread.sleep(10);
}
catch (final InterruptedException e) {}
}
if (m == ack || m == noblock) {
while (t.getState() == ClientConnection.CEMI_CON_PENDING)
try {
Thread.sleep(10);
}
catch (final InterruptedException e) {}
}
assertNotNull(l.received);
final CEMILData fcon = (CEMILData) l.received;
assertEquals(positiveConfirmation, fcon.isPositiveConfirmation());
l.received = null;
} | 7 |
public int getLargestSequence(int[] input) {
int sum = 0;
int maxSum = 0;
for (int i = 0; i < input.length; i++) {
sum += input[i];
if (maxSum < sum) {
maxSum = sum;
}
if (sum < 0) {
sum = 0;
}
}
return maxSum;
} | 3 |
public String getMyUsername()
{
return ClientFinder.getInstance().getUsername();
} | 0 |
private void loadPropFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(pf));
for (String s = ""; (s = br.readLine()) != null;) {
String[] p = s.split(":");
if (p[0].equals("name")) {
name = p[1];
ServerGame.logger.info("Name set to " + name);
} else if (p[0].equals("port")) {
ServerGame.logger.info("Listening to port " + port);
port = Integer.parseInt(p[1]);
} else if (p[0].equals("max_players")) {
ServerGame.logger.info("Maximum players " + maxP);
maxP = Integer.parseInt(p[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
ServerGame.logger.severe("Something went wrong with loading prop.txt file!");
}
} | 5 |
public void init() {
if (inited) {
return;
}
Log.info("Initialising sounds..");
inited = true;
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
AL.create();
soundWorks = true;
sounds = true;
music = true;
Log.info("- Sound works");
} catch (Exception e) {
Log.error("Sound initialisation failure.");
Log.error(e);
soundWorks = false;
sounds = false;
music = false;
}
return null;
}});
if (soundWorks) {
sourceCount = 0;
sources = BufferUtils.createIntBuffer(maxSources);
while (AL10.alGetError() == AL10.AL_NO_ERROR) {
IntBuffer temp = BufferUtils.createIntBuffer(1);
try {
AL10.alGenSources(temp);
if (AL10.alGetError() == AL10.AL_NO_ERROR) {
sourceCount++;
sources.put(temp.get(0));
if (sourceCount > maxSources-1) {
break;
}
}
} catch (OpenALException e) {
// expected at the end
break;
}
}
Log.info("- "+sourceCount+" OpenAL source available");
if (AL10.alGetError() != AL10.AL_NO_ERROR) {
sounds = false;
music = false;
soundWorks = false;
Log.error("- AL init failed");
} else {
FloatBuffer listenerOri = BufferUtils.createFloatBuffer(6).put(
new float[] { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f });
FloatBuffer listenerVel = BufferUtils.createFloatBuffer(3).put(
new float[] { 0.0f, 0.0f, 0.0f });
FloatBuffer listenerPos = BufferUtils.createFloatBuffer(3).put(
new float[] { 0.0f, 0.0f, 0.0f });
listenerPos.flip();
listenerVel.flip();
listenerOri.flip();
AL10.alListener(AL10.AL_POSITION, listenerPos);
AL10.alListener(AL10.AL_VELOCITY, listenerVel);
AL10.alListener(AL10.AL_ORIENTATION, listenerOri);
Log.info("- Sounds source generated");
}
}
} | 8 |
public void setStandardDeviation(int standardDeviation)
{
this.standardDeviation = standardDeviation;
} | 0 |
public static void doSearch(final Environment env, final String outFileName, final long endTime) {
// Create a new search and attempt to do our setup
Search search = new Search(env, endTime);
search.setup();
if (search.getSolveable()) {
// If we haven't already exceeded the time limit...
if (System.currentTimeMillis() < endTime) {
// Begin the hunt!
search.letsSearching();
}
// Either way, we need to report what we've got now
examSchedule.Solution bestSolution = search.getBestSolution();
if (bestSolution != null) {
if (bestSolution.isValidSolution() == false)
System.out.println("solution is invalid");
String output = bestSolution.toString();
System.out.println(search.getBestSolution().toString());
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(outFileName));
writer.write(output);
writer.close();
}
catch (IOException e) {
System.err.println("Failed to write output");
return;
}
} else {
System.out.println("Failed to find anything");
}
} else {
System.out.println("Failed to find anything");
}
} | 5 |
public void setCle(String s){
cle = s.toLowerCase();
for(int i=0 ; i<cle.length() ; i++)
if(((int)cle.charAt(i) < 97 || (int)cle.charAt(i) > 122)
|| (cle.indexOf(cle.charAt(i)) != cle.lastIndexOf(cle.charAt(i)))) cle = "";
if(!s.equals("")){
for(int i=0 ; i<cle.length() ; i++)
referenceCle[i] = cle.charAt(i);
int index = cle.length();
for(int i=0 ; i<26 ; i++){
if(!cle.contains(((char)(i+97))+"")){
referenceCle[index] = (char) (i+97);
index++;
}
}
}
} | 8 |
private JPanel createGeneralSettingsPanel()
{
JPanel jp = new JPanel();
jp.setBorder(default_border);
BoxLayout bl = new BoxLayout(jp, BoxLayout.PAGE_AXIS);
jp.setLayout(bl);
JPanel ip; // inner panel used for layout.
ip = new JPanel();
ip.add(new JLabel("Font Smoothing"));
font_smoothing_selector = new JComboBox();
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR);
font_smoothing_selector.addItem(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB);
ip.add(font_smoothing_selector);
font_smoothing_selector.setSelectedItem(dialog_settings.getFontSmoothingValue());
setItemAlignment(ip);
jp.add(ip);
editor_use_env_checkbox = new JCheckBox(UIStrings.SETTINGS_DIALOG_EDITOR_USE_ENV, !dialog_settings.editor_use_env);
final JButton browse_button = new JButton(folder_icon);
editor_use_env_checkbox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
editor_path_field.setEnabled(!editor_use_env_checkbox.isSelected());
browse_button.setEnabled(!editor_use_env_checkbox.isSelected());
}
});
jp.add(editor_use_env_checkbox);
ip = new JPanel();
ip.add(new JLabel(UIStrings.SETTINGS_DIALOG_EDITOR_PATH_LABEL));
editor_path_field = new JTextField(18);
editor_path_field.setText(dialog_settings.editor_path);
ip.add(editor_path_field);
browse_button.setToolTipText(UIStrings.SETTINGS_DIALOG_EDITOR_BROWSE_TOOLTIP);
browse_button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle(UIStrings.UI_OPEN_EDITOR_LABEL);
fc.setFileFilter(Utility.getExecutableFileFilter());
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
editor_path_field.setText(fc.getSelectedFile().getAbsolutePath());
}
}
});
ip.add(browse_button);
setItemAlignment(ip);
jp.add(ip);
editor_use_env_checkbox.doClick();
return jp;
} | 1 |
@Override
public void commit() {
for(Entity entity: entities.keySet()) {
switch(entity.getState()) {
case Changed:
entities.get(entity).persistUpdate(entity);
break;
case Deleted:
entities.get(entity).persistDelete(entity);
break;
case New:
entities.get(entity).persistAdd(entity);
break;
case Unchanged:
break;
default:
break;
}
}
try {
connection.commit();
entities.clear();
} catch (SQLException e) {
e.printStackTrace();
}
} | 6 |
public static BufferedImage loadSplashImage(String path) {
BufferedImage splashImage = null;
try {
splashImage = ImageIO.read(new File(path));
} catch (IllegalArgumentException e) {
// TODO if no file found
e.printStackTrace();
} catch (IOException e) {
// TODO other problems
e.printStackTrace();
}
return splashImage;
} | 2 |
public String getName() {
return this.name;
} | 0 |
public void setWidth(double width) {
this.width = width;
} | 0 |
public float getCurrentLevel() {
switch (state) {
case ATTACKING:
lerpProgression = (System.currentTimeMillis() - triggerTime) / (float) attackDuration;
if (lerpProgression >= 1) {
state = ADSRStates.DECAYING;
triggerTime = System.currentTimeMillis();
return 1;
}
return lerp(0, 1, lerpProgression);
case DECAYING:
lerpProgression = (System.currentTimeMillis() - triggerTime) / (float) decayDuration;
if (lerpProgression >= 1) {
state = ADSRStates.SUSTAINING;
return sustainLevel;
}
return lerp(1, sustainLevel, lerpProgression);
case SUSTAINING:
return sustainLevel;
case RELEASING:
lerpProgression = (System.currentTimeMillis() - triggerTime) / (float) releaseDuration;
if (lerpProgression >= 1) {
state = ADSRStates.OFF;
return 0;
}
return lerp(releaseLevel, 0, lerpProgression);
default:
return -1;
}
} | 7 |
public static void main(String[] args) throws Exception {
//System.err.println("ARGS:"+Arrays.toString(args));
for (String key : System.getenv().keySet()) {
System.out.println(key + " " + System.getenv(key));
}
Map<String, List<String>> argsMap = prepareArgs(args);
if (argsMap.containsKey("help")) {
printUsage();
System.exit(0);
}
//printAllParameter(argsMap);
// System.out.println(argsMap.get("app").size());
ToolsRunner runningTool = getRunnerTool(argsMap.get("app") == null
|| argsMap.get("app").size() == 0 ? null : argsMap.get("app")
.get(0));
log.info("Starting " + runningTool.getName());
String[] appArgs = new String[argsMap.get("args").size()];
for (int i = 0; i < appArgs.length; i++) {
appArgs[i] = argsMap.get("args").get(i).trim();
}
runningTool.run(appArgs);
} | 5 |
private String resolve(String str) {
if (str != null && str.contains("${")) {
Matcher ma = null;
while ((ma = varPattern.matcher(str)).find()) {
String key = ma.group(1);
String val = get(key);
if (val == null) {
throw new IllegalArgumentException("value substitution failed for " + key);
}
Pattern repl = Pattern.compile("\\$\\{" + key + "\\}");
str = repl.matcher(str).replaceAll(val);
}
}
return str;
} | 4 |
@Override
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
LOG.info(this.toString() + " was interrupted");
}
Integer smallestValue = philosophers.get(0).getMealsAmount();
for (Philosopher p : philosophers) {
if(p.getMealsAmount() < smallestValue) {
smallestValue = p.getMealsAmount();
}
}
for (Philosopher p : philosophers) {
if (smallestValue + difference < p.getMealsAmount()) {
p.banFor(banTime * (p.getMealsAmount() - (smallestValue + difference)));
}
}
}
} | 6 |
@Override
public String toString() {
return "Skill [skillName=" + skillName + ", skillId=" + skillId + "]";
} | 0 |
protected static boolean isOurCanvas(String name) {
return name.equals("draw.Canvas") || name.equals("idraw.Canvas")
|| name.equals("adraw.Canvas") || name.equals("funworld.Canvas")
|| name.equals("impworld.Canvas") || name.equals("appletworld.Canvas")
|| name.equals("javalib.worldcanvas.WorldCanvas")
|| name.equals("javalib.worldcanvas.AppletCanvas")
|| name.equals("impsoundworld.Canvas")
|| name.equals("appletsoundworld.Canvas");
} | 9 |
public int getIdDetalle() {
return idDetalle;
} | 0 |
@Override
public Color[][] getColors(double[][] heightmap, boolean[][] watermap) {
Color[][] c = new Color[calc.length][calc.length];
for (int x = 0; x < heightmap.length; x++)
for (int y = 0; y < heightmap[x].length; y++)
if (watermap[x][y])
if (calc[x][y] <= 0.1)
c[x][y] = Color.cyan;
else if (heightmap[x][y] < 0.25)
c[x][y] = Color.blue.darker();
else
c[x][y] = Color.blue;
else
c[x][y] = Color.green;
return c;
} | 5 |
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
} | 3 |
public static void countRight2(ArrayList<Integer> list, TreeNode node, String s){
if(node == null ) return;
StringBuilder sb = new StringBuilder();
sb.append(s);
while(node != null){
sb.append(String.valueOf(node.val));
if(node.right == null && node.left == null){
list.add(Integer.parseInt(sb.toString()));
}
if(node.left != null){
countLeft2(list, node.left, sb.toString());
}
node = node.right;
}
} | 5 |
private void configureSpawnRequest(GameObjectSpawnRequest spawnRequest) {
int uid = 0;
int id = -1;
int type = 0;
int face = 0;
if (spawnRequest.objectType == 0)
uid = worldController.getWallObjectHash(spawnRequest.x,
spawnRequest.y, spawnRequest.z);
if (spawnRequest.objectType == 1)
uid = worldController.getWallDecorationHash(spawnRequest.x,
spawnRequest.y, spawnRequest.z);
if (spawnRequest.objectType == 2)
uid = worldController.getInteractibleObjectHash(spawnRequest.x,
spawnRequest.y, spawnRequest.z);
if (spawnRequest.objectType == 3)
uid = worldController.getGroundDecorationHash(spawnRequest.x,
spawnRequest.y, spawnRequest.z);
if (uid != 0) {
int config = worldController.getConfig(uid, spawnRequest.x,
spawnRequest.y, spawnRequest.z);
id = uid >> 14 & 0x7fff;
type = config & 0x1f;
face = config >> 6;
}
spawnRequest.id = id;
spawnRequest.type = type;
spawnRequest.face = face;
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Estado other = (Estado) obj;
if (estFinal != other.estFinal)
return false;
if (inicial != other.inicial)
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
} | 8 |
private int wordstart(int from) {
while((from > 0) && !wordchar(line.charAt(from - 1))) from--;
while((from > 0) && wordchar(line.charAt(from - 1))) from--;
return(from);
} | 4 |
boolean contains(float inX, float inY) {
float frontFace;
if (face == FACE_CURVY) frontFace = 2;
else frontFace = 1;
if (orientation == Orientation.X) {
return (inY >= y0 - frontFace && inY <= y0 + 1
&& inX > x0 && inX < x0 + 2 + spineLength);
} else {
return (inX <= x0 + frontFace && inX >= x0 - 1
&& inY > y0 && inY < y0 + 2 + spineLength);
}
} | 8 |
@Override
protected void done() {
NameData[] nd = null;
try {
nd = this.get();
}
catch(Exception e) {
ptm.updateStatus(spContainer, "Data Error!");
}
if(nd != null && nd.length > 0) {
ptm.updateStatus(spContainer, "Ready!");
fc.addResult(nd[0].getMediaName(), nd, crawledData);
}
else {
ptm.updateStatus(spContainer, "No Result Error!");
}
} | 3 |
public static Entry wrapSrampArtifact(BaseArtifactType artifact) throws URISyntaxException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException,
NoSuchMethodException {
// TODO leverage the artifact->entry visitors here
Entry entry = new Entry();
if (artifact.getUuid() != null)
entry.setId(new URI(artifact.getUuid()));
if (artifact.getLastModifiedTimestamp() != null)
entry.setUpdated(artifact.getLastModifiedTimestamp().toGregorianCalendar().getTime());
if (artifact.getName() != null)
entry.setTitle(artifact.getName());
if (artifact.getCreatedTimestamp() != null)
entry.setPublished(artifact.getCreatedTimestamp().toGregorianCalendar().getTime());
if (artifact.getCreatedBy() != null)
entry.getAuthors().add(new Person(artifact.getCreatedBy()));
if (artifact.getDescription() != null)
entry.setSummary(artifact.getDescription());
Artifact srampArty = new Artifact();
Method method = Artifact.class.getMethod("set" + artifact.getClass().getSimpleName(), artifact.getClass()); //$NON-NLS-1$
method.invoke(srampArty, artifact);
entry.setAnyOtherJAXBObject(srampArty);
return entry;
} | 6 |
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
stack[top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
} | 4 |
@Override
public void run() {
++elapseTime;
if (state == EnumStopWatchState.RUNNING) {
++tick;
}
log.info("stopwatch state:" + state + ", elapseTime:" + elapseTime);
if (listener != null) {
if (date == null) {
date = new Date();
}
date.setTime(System.currentTimeMillis());
listener.countdown(date, tick, elapseTime);
}
} | 3 |
public static void printCompanyDataToFile(String file, Company company) {
BufferedWriter output;
FileWriter streamFiles;
try {
streamFiles = new FileWriter(file, true);
output = new BufferedWriter(streamFiles);
if(ReadFromFile.getNumberFromFile(file) < 2) {
for(int i = 0; i < 9; i++) {
if(i!= 8)
output.write("\\" + company.getCompanyData(i) + "\\,");
else
output.write("\\" + company.getCompanyData(i) + "\\");
}
output.close();
}
else {
for(int i = 0; i < 9; i++) {
if(i == 0)
output.write("\n\\" + company.getCompanyData(i) + "\\,");
else if(i != 8)
output.write("\\" + company.getCompanyData(i) + "\\,");
else
output.write("\\" + company.getCompanyData(i) + "\\");
}
output.close();
}
}
catch(IOException i) {}
} | 7 |
public static boolean isSorted(double[] input) {
for (int i = 1; i < input.length; i++) {
if (input[i-1] > input[i]) {
return false;
}
}
return true;
} | 2 |
public List<Seance> getSeances() {
List<Seance> seances = new ArrayList<Seance>();
Seance tempSeance;
int tempIndex;
for (Ticket ticket : tickets) {
tempSeance = ticket.getSeance();
tempIndex = seances.indexOf(tempSeance);
if (tempIndex == -1) {
seances.add(tempSeance);
} else {
// if ( !seances.get(tempIndex).existsTicket(ticket)) {
// seances.get(tempIndex).addTicket(ticket);
// }
}
}
return seances;
} | 2 |
public void printTop(String type)
{
if(type.equals("blank"))
{
System.out.println();
System.out.println("Type 'get help' for help and instructions.");
System.out.println();
}
if(type.equals("help"))
printHelp();
if(type.equals("win"))
{
System.out.println();
System.out.println("You have beaten " + monster.getName() + "!");
System.out.println();
wait(3);
//free from room
}
if(type.equals("lose"))
{
System.out.println();
System.out.println("Sorry! You lose!");
System.out.println();
wait(3);
//restart the whole damn game
}
if(type.equals("description"))
{
System.out.println();
System.out.println(description);
System.out.println();
description = "";
}
} | 5 |
@Override
public void mouseReleased(MouseEvent e)
{
if (graphComponent.isEnabled() && isEnabled())
{
Iterator<mxCellHandler> it = handlers.values().iterator();
while (it.hasNext() && !e.isConsumed())
{
it.next().mouseReleased(e);
}
}
reset();
} | 4 |
public static String matchMovieFromRT(String jsonResponse, Movie movie)
throws JSONException
{
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject resultMovie = jsonArray.getJSONObject(i);
int year = resultMovie.getInt("year");
if (resultMovie.has("alternate_ids"))
{
int id = resultMovie.getJSONObject("alternate_ids").getInt("imdb");
if (id == movie.imdbId)
{
JSONObject links = resultMovie.getJSONObject("links");
return links.getString("self");
}
}
else
{
String title = resultMovie.getString("title");
title = title.trim();
if ((year == movie.year) && title.contains(movie.imdbTitle))
{
JSONObject links = resultMovie.getJSONObject("links");
return links.getString("self");
}
}
}
return null;
} | 5 |
public static boolean isConflict(ConclusionType ct1, ConclusionType ct2) {
if (DEFINITE_PROVABLE.equals(ct1) && DEFINITE_NOT_PROVABLE.equals(ct2)) return true;
if (DEFINITE_NOT_PROVABLE.equals(ct1) && DEFINITE_PROVABLE.equals(ct2)) return true;
if (DEFEASIBLY_PROVABLE.equals(ct1) && DEFEASIBLY_NOT_PROVABLE.equals(ct2)) return true;
if (DEFEASIBLY_NOT_PROVABLE.equals(ct1) && DEFEASIBLY_PROVABLE.equals(ct2)) return true;
return false;
} | 8 |
public Method getBestMethod(Object receiver, String methodName,
Class<?>[] parameterTypes) {
Class<? extends Object> c = receiver.getClass();
while (c != null) {
try {
return c.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
}
c = c.getSuperclass();
}
return null;
} | 5 |
private static double removeCommonDigit(int numerator, int denominator) {
int numDig1 = numerator / 10;
int numDig2 = numerator % 10;
int denDig1 = denominator / 10;
int denDig2 = denominator % 10;
if (numDig2 == 0 && denDig2 == 0)
return -1;
if (numDig1 == denDig1)
return ((double) numDig2) / denDig2;
if (numDig1 == denDig2)
return ((double) numDig2) / denDig1;
if (numDig2 == denDig1)
return ((double) numDig1) / denDig2;
if (numDig2 == denDig2)
return ((double) numDig1) / denDig1;
return -1;
} | 6 |
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
if(!cdb.getText().isEmpty()){
Administrador.Buscar adbc = new Administrador.Buscar();
adbc.setVisible(true);
}
else{
if(!idb.getText().isEmpty()){
Administrador.Buscar adbc = new Administrador.Buscar();
adbc.setVisible(true);
}
else{
proyecto.Error error = new proyecto.Error(this, true);
error.ready("Porfavor, llene al menos un campo.");
error.setVisible(true);
}
}
}//GEN-LAST:event_jButton9ActionPerformed | 2 |
public String poprawOsobe(){
return "dodaj";
} | 0 |
int checkHours(RoomScheme chromo, int code){
int counter=0;
int auxCounter=0;
for(int a=0; a<5; a++){
for(int b=0; b<6; b++){
if(chromo.rooms[a][b].getCode() == code){
auxCounter++;
if(auxCounter > 2){
counter--;
}
}
}
}
return counter;
} | 4 |
public static int getInt(CSProperties p, String key) throws ParseException {
String val = p.get(key).toString();
if (val == null) {
throw new IllegalArgumentException(key);
}
return Integer.parseInt(val);
} | 1 |
public static float[][] getFirstCenter(float[][][] p, int cluster, int min,
int max) {
int k = max - min + 1;
float temp[][] = new float[k][p[0][1].length + 1]; // cluster centroid,the first dimension is index
float dis[][] = new float[p.length][p.length];// distance of samples
float maxdis = 0;// maximum distance of samples
int c1 = 0, c2 = 0; // record the index of farthest sample
for (int i = 0; i < p.length; i++) {
if ((int) p[i][0][0] == cluster) {
for (int j = 0; j < p.length; j++) {
if ((int) p[j][0][0] == cluster) {
dis[i][j] = Calculate.getDataDistance(p[i][1], p[j][1]);
if (dis[i][j] > maxdis) {
maxdis = dis[i][j];
c1 = i;
c2 = j;
}
}
}
}
}
temp[0][0] = min;
for (int m = 1; m < p[c1][1].length + 1; m++) {
temp[0][m] = p[c1][1][m - 1];
}
temp[1][0] = min + 1;
for (int m = 1; m < p[c2][1].length + 1; m++) {
temp[1][m] = p[c2][1][m - 1];
}
return temp;
} | 7 |
private void create(String initialValue, Color bg, String title, boolean addTransparentBtn) {
setPreferredSize(this.preferredDim);
if (title != null) {
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(title),
BorderFactory.createEmptyBorder(5, 0, 0, 0)));
} else {
setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
}
setLayout(new VerticalLayout(5, VerticalLayout.CENTER));
setBackground(bg);
this.path = new JTextField();
this.path.setPreferredSize(PATHFIELD_DIM);
this.path.setEditable(false);
this.path.setFocusable(false);
this.path.setText(initialValue);
this.path.setToolTipText(initialValue);
this.path.setBackground(Color.LIGHT_GRAY.brighter());
this.add(this.path);
JPanel panel = new JPanel();
panel.setBackground(bg);
this.add(panel);
JButton choose = new JButton("...");
choose.setMinimumSize(BUTTON_DIM);
choose.setBackground(bg);
choose.addActionListener(new ActionListener() {
@SuppressWarnings("unused")
@Override
public void actionPerformed(ActionEvent e) {
new FileChooserDialog(Field.strFileChooserTitle, new ImageFileFilter(ImageField.this.fcdFilter), false) {
private static final long serialVersionUID = 1L;
@Override
public void onApprove(File file) {
onFileChosen(file);
}
@Override
public void onCancel() {
;
}
};
}
});
panel.add(choose);
if (addTransparentBtn) {
JButton toggleTransparent = new JButton(Field.strToggleTransparent);
toggleTransparent.setMinimumSize(BUTTON_DIM);
toggleTransparent.setBackground(bg);
toggleTransparent.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onFileChosen(Constants.SKIN_TRANSPARENT_BG.toFile());
}
});
panel.add(toggleTransparent);
}
JButton reset = new JButton(Field.strReset);
reset.setMinimumSize(BUTTON_DIM);
reset.setBackground(bg);
reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onFileChosen(null);
}
});
panel.add(reset);
} | 2 |
public static void main(String[] args) throws JDOMException, IOException {
SAXBuilder saxBuilder = new SAXBuilder();
File file = new File("D:\\Java SE\\src\\xml\\jdom\\file.xml");
Document document = (Document)saxBuilder.build(file);
Element node = document.getRootElement();
List list = node.getChildren("staff");
for(int i =0 ; i < list.size(); i++){
Element element = (Element)list.get(i);
System.out.println(element.getChildText("firstname"));
}
} | 1 |
private static HashMap<Integer, Integer> generateListOfPrimes(Integer NumberofPrimes) {
HashMap<Integer, Integer> HashMapofPrimes = new HashMap<Integer,Integer>();
HashMapofPrimes.put(1,2);
HashMapofPrimes.put(2,3);
for (int i = 4; i < NumberofPrimes; i++) {
setDividibleBySomething(false);
primInteger = i;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
setDividibleBySomething(true);
}
}
if (getDividiblebySomething() == false) {
HashMapofPrimes.put(HashMapofPrimes.size()+1,primInteger);
}
}
return HashMapofPrimes;
} | 4 |
@Override
public int[] sort(int[] target, boolean asc) {
int length = target.length;
int gap = length / 2;
if (asc) {
do {
for (int i = 0; (i + gap) < length; i++) {
int tmp = target[i + gap];
if (target[i] > tmp) {
target[i + gap] = target[i];
target[i] = tmp;
}
}
gap /= 2;
} while (gap > 1);
new Insertion().sort(target, asc);
} else {
do {
for (int i = 0; (i + gap) < length; i++) {
int tmp = target[i + gap];
if (target[i] < tmp) {
target[i + gap] = target[i];
target[i] = tmp;
}
}
gap /= 2;
} while (gap > 1);
new Insertion().sort(target, asc);
}
return target;
} | 7 |
@Override
public void run() {
try {
System.out.println( "Client has connected" );
if( client_num == FIRST_CLIENT ) {
serverLock.lock();
try {
while( suspended ) {
waitingForConnection.await();
}
} catch( InterruptedException e ) {
e.printStackTrace();
} finally {
serverLock.unlock();
}
}
userName = input.nextLine();
while ( true ) {
if ( input.hasNext() ) {
String morse = input.nextLine();
morse = userName + ": " + morse;
if ( input.hasNext() ) {
String message = input.nextLine();
message = userName + ": " + message;
if( client_num == FIRST_CLIENT ) {
clients[ SECOND_CLIENT ].output.println( morse );
clients[ SECOND_CLIENT ].output.println( message );
clients[ SECOND_CLIENT ].output.flush();
}
else {
clients[ FIRST_CLIENT ].output.println( morse );
clients[ FIRST_CLIENT ].output.println( message );
clients[ FIRST_CLIENT ].output.flush();
}
}
}
}
} finally {
try {
connection.close();
}catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
}
} | 8 |
public JView getViewByTitle(String title) {
if (title == null || title.trim().length() == 0) return null;
load();
if (views.size() == 0) return null;
for (JView view : views) {
if (title.trim().equalsIgnoreCase(view.getDisplayName())) return view;
}
return null;
} | 5 |
public void luoKaydytRuudut(JPanel paneeli, Labyrintti l, Pino polku) {
for (int j=0; j<this.koko; ++j) {
for (int i=0; i<this.koko; ++i) {
boolean lahto = false;
boolean maali = false;
boolean kayty = false;
boolean path = false;
boolean este = false;
// Ruutu-oliolle asetetaan tieto siitä, onko se lähtö-, maali,
// tai estesolmu, onko se kuljetulla polulla tai onko
// siellä käyty
if (l.getLahto().getX() == i && l.getLahto().getY() == j) {
lahto = true;
}
else if (l.getMaali().getX() == i && l.getMaali().getY() == j) {
maali = true;
}
else if (l.getSolmu(i, j).onkoEste()) {
este = true;
}
else if (polku.contains(l.getSolmu(i, j))) {
path = true;
}
else if (l.getSolmu(i, j).isVisited() == true) {
kayty = true;
}
Ruutu r = new Ruutu(i, j, lahto, maali, path, kayty, este, this.labyrintti);
paneeli.add(r);
}
}
} | 9 |
public void setDestination(Teleporter destination) {
if (destination == null || destination.position.equals(position))
throw new IllegalArgumentException("The given Teleporter is invalid!");
if (this.destination != null)
throw new IllegalStateException("Destination is already set!");
this.destination = destination;
} | 3 |
public void terminal() {
try {
run();
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isReader);
System.out.print(">> ");
String command = br.readLine();
while (true) {
if (command.startsWith("detect ")) {
String[] cmdLine = command.split(" ");
processDetect(cmdLine[1]);
} else {
if (command.startsWith("disconnect ")) {
String[] cmdLine = command.split(" ");
processDisconnect(Short.parseShort(cmdLine[1]));
} else {
if (command.startsWith("quit")) {
break;
} else {
if (command.startsWith("attach ")) {
if (validPortNum >= 4) {
System.out.println("the router's ports has been full");
} else {
String[] cmdLine = command.split(" ");
processAttach(cmdLine[1], Short.parseShort(cmdLine[2]),
cmdLine[3], Short.parseShort(cmdLine[4]));
}
} else {
if (command.equals("start")) {
//TODO: broadcast the Hello
}
}
}
}
}
System.out.print(">> ");
command = br.readLine();
}
isReader.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public <V> Adapter.Setter<V> makeSetter(String methodName, Class<V> _class) {
try {
final Method method = version.getClass().getMethod(methodName, _class);
return new Adapter.Setter<V>() {
public void call(V value) {
try {
Transaction me = Thread.getTransaction();
Transaction other = null;
Set<Transaction> others = null;
while (true) {
synchronized (Adapter.this) {
other = openWrite(me);
if (other == null) {
method.invoke(version, value);
versionNumber++;
return;
}
}
if (others != null) {
manager.resolveConflict(me, others);
} else if (other != null) {
manager.resolveConflict(me, other);
}
}
} catch (IllegalAccessException e) {
throw new PanicException(e);
} catch (InvocationTargetException e) {
throw new PanicException(e);
}
}};
} catch (NoSuchMethodException e) {
throw new PanicException(e);
}
} | 7 |
public double getValue(double x)
{
if (len.length == 0)
{
return Double.NaN;
}
if (len.length == 1)
{
if (len[0] == x)
{
return pos1D[0];
}
else
{
return Double.NaN;
}
}
int index = Arrays.binarySearch(len, x);
if (index > 0)
{
return pos1D[index];
}
index = - (index + 1) - 1;
//TODO linear interpolation or extrapolation
if (index < 0) {
return pos1D[0];
}
return a[index]
+ b[index] * (x - len[index])
+ c[index] * Math.pow(x - len[index], 2)
+ d[index] * Math.pow(x - len[index], 3);
} | 5 |
private int num(int n){
if(n==1) return 1;
int cnt=0;
int max=n;
for(int i=1;i<max/2;++i){
if(n%i==0){
cnt+=2;
max=n/i;
}
}
return cnt;
} | 3 |
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.