text stringlengths 14 410k | label int32 0 9 |
|---|---|
private boolean sendFile(java.nio.channels.FileChannel fchan, long pos, long lmt, FileWrite fw) throws CM_Stream.BrokenPipeException
{
final java.nio.channels.WritableByteChannel iochan = (java.nio.channels.WritableByteChannel)chanmon.iochan;
final long sendbytes = lmt - pos;
try {
//throws on closed channel (java.io.IOException) or other error, so can't be sure it's closed, but it might as well be
final long nbytes = fchan.transferTo(pos, sendbytes, iochan);
if (nbytes != sendbytes) {
//We didn't write as much as we requested, so we're probably blocked, but it could also be because
//we reached end-of-file.
//NB: This code would also spot any reduction in file size since we started this file-send.
final long maxlmt = fchan.size();
pos += nbytes;
if (lmt > maxlmt) lmt = maxlmt;
if (pos < lmt) {
//Not at end-of-file (or even end-of-send, if we were only sending partial file), so we're blocked
if (fw == null) {
// enqueue the file
if (chanmon.dsptch.logger.isActive(WRBLOCKTRC)) {
chanmon.dsptch.logger.log(WRBLOCKTRC, "IOExec: File-send="+sendbytes+" blocked with "+nbytes+"/"+sendbytes
+" - "+chanmon.getClass().getName()+"/E"+chanmon.getCMID()+"/"+chanmon.iochan);
}
enqueue(fchan, pos, lmt);
} else {
// file was already enqueued, so update its progress
fw.offset = pos;
fw.limit = lmt;
}
return false;
}
}
} catch (Exception ex) {
LEVEL lvl = (ex instanceof RuntimeException ? LEVEL.ERR : LEVEL.TRC3);
String errmsg = "IOExec: file-send="+sendbytes+" failed";
if (chanmon.dsptch.logger.isActive(lvl)) errmsg += " on "+iochan;
chanmon.brokenPipe(lvl, "Broken pipe on file-send", errmsg, ex);
}
return true;
} | 8 |
public String getAppenderName() {
return appenderName;
} | 0 |
@Override
public void addFilter(PropertyFilter filter) {
if (filter != null) {
filters.add(filter);
} else {
throw new IllegalArgumentException("Provided PropertyFilter was null.");
}
} | 1 |
public void run() {
Player player = (Player) sender;
if (arena.isIngame()) {
player.sendMessage(OITG.prefix + ChatColor.RED + "A game is already in progress in that arena, choose another.");
return;
}
if (arena.isClosed()) {
player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is closed, choose another.");
return;
}
if (arena.getPlayerCount() >= arena.getPlayerLimit() && arena.getPlayerLimit() != -1) {
player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is full, choose another.");
return;
}
if (arena.getLobby() == null) {
player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no lobby has been set.");
return;
}
if (arena.getSpawns().length == 0) {
player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no spawn points have been set.");
return;
}
if (OITG.instance.getArenaManager().getArena(player) != null) {
player.sendMessage(OITG.prefix + ChatColor.RED + "You are already in an arena!");
return;
}
arena.addPlayer((Player) sender);
player.teleport(arena.getLobby());
} | 7 |
public void setIcon()
{
try {
ByteBuffer[] icons = new ByteBuffer[2];
icons[0] = loadIcon("Icon_16.png", 16, 16);
icons[1] = loadIcon("Icon_32.png", 32, 32);
Display.setIcon(icons);
} catch (IOException ex) {
ex.printStackTrace();
}
} | 1 |
public List<CartaFianza> buscarCartaFianza(String codCartaFianza, String strProveedor) {
List<CartaFianza> listaResultado = new ArrayList<CartaFianza>();
for (CartaFianza bean : listaCartaFianza) {
if (bean.getCodCartaFianza().equals(codCartaFianza)) {
if (strProveedor == null || strProveedor.equals("")) {
listaResultado.add(bean);
}
if (bean.getStrProveedor().equals(strProveedor)) {
listaResultado.add(bean);
}
}
if (bean.getStrProveedor().equals(strProveedor)) {
if (codCartaFianza == null || codCartaFianza.equals("")) {
listaResultado.add(bean);
}
if (bean.getCodCartaFianza().equals(codCartaFianza)) {
listaResultado.add(bean);
}
}
}
return listaResultado;
} | 9 |
public void mergeList(Integer a[], int start1, int end1, int start2, int end2) {
int temp[] = new int[end1 - start1 + end2 - start2 + 2];
int ptr1 = start1, ptr2 = start2, ptrmain = 0;
while (ptr1 <= end1 && ptr2 <= end2) {
if (a[ptr1] < a[ptr2]) {
temp[ptrmain++] = a[ptr1++];
} else {
temp[ptrmain++] = a[ptr2++];
}
}
while (ptr1 <= end1) {
temp[ptrmain++] = a[ptr1++];
}
while (ptr2 <= end2) {
temp[ptrmain++] = a[ptr2++];
}
ptrmain = 0;
for (int i = start1; i <= end1; i++) {
a[i] = temp[ptrmain++];
}
for (int i = start2; i <= end2; i++) {
a[i] = temp[ptrmain++];
}
} | 7 |
public void doCommand( final Command command ) {
final boolean changed = command.perform();
System.out.println( "CommandControl.doCommand(): " + command.getClass() + " " + changed );
if( changed && command instanceof UndoableCommand ) {
final boolean oldCanUndo = canUndo();
undoStack.add( (UndoableCommand) command );
if( canUndo() != oldCanUndo ) {
informCanUndoRedoListeners();
}
System.out.println( "CommandControl.doCommand(): undoStackSize=" + undoStack.size() );
}
} | 3 |
@Override
public void writeUIFile(UIFileTextVO uifile) throws IOException {
if (uifile == null) {
IllegalArgumentException iae = new IllegalArgumentException("The uiFile must not be null!");
Main.handleUnhandableProblem(iae);
}
UIFileWriter.writeUIFile(uifile, this.uitextfilepath);
} | 1 |
public void setName(String name) {
this.name = name;
} | 0 |
@Override
public Connection getConnection() throws SQLException {
if (this.isClosed()) {
throw new SQLException("Connection pool is closed");
}
// Immediately return if a connection is available
Connection conn = this.waitAndGet(0);
if (conn != null) {
// w00t!!
return conn;
} else {
// Create a new connection iff pool-capacity not exceeded.
conn = this.createAndAdd();
if (conn != null) {
return conn;
} else {
// Wait maxWait seconds for other threads to release a connection
long start = System.currentTimeMillis();
conn = this.waitAndGet(this.props.getMaxWait());
if (conn == null) {
if (System.currentTimeMillis() - start >= this.props.getMaxWait()) {
if (log.isDebugEnabled()) {
log.debug(this.capacityInfo("Timed out.", "\n"));
}
throw new SQLException("Timed out. No available connection after waiting for " + (this.props.getMaxWait()/1000) + " seconds.");
}
}
}
}
// check if pool is closed in the middle of the retrieval
if (this.isClosed()) {
this.disconnect(conn);
throw new SQLException("Connection pool is closed");
} else {
return conn;
}
} | 7 |
private void writeList() {
for ( Column column : table.getColumns() ) {
if ( column.isSearchId() ) {
write( TAB + "public " );
write( "List<" + table.getDomName() + "> getListBy" );
write( toTitleCase( column.getFldName() ) );
write( "( " );
write( column.getFldType() );
write( " key ) throws DaoException;\n" );
}
}
write( "\n" );
} | 2 |
public static List<String> findFile(String inFilepath, Filtro isFiltro) {
List<String> fileFound = new ArrayList();
File directorioInicial = new File(inFilepath);
File[] gdbArray = directorioInicial.listFiles(isFiltro);
for (File archivo : gdbArray) {
if (archivo.isDirectory()) {
fileFound.addAll(findFile(archivo.getAbsolutePath().toString(), isFiltro));
} else {
fileFound.add(archivo.getAbsolutePath().toString());
}
}
return fileFound;
} | 2 |
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// construct the query from the client's QueryString
String picid = request.getQueryString();
String query;
if ( picid.startsWith("thumb") )
query =
"select thumbnail from images where photo_id=" + picid.substring(5);
else
query = "select photo from images where photo_id=" + picid;
ServletOutputStream out = response.getOutputStream();
/*
* to execute the given query
*/
Connection conn = null;
try {
conn = getConnected();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(query);
if ( rset.next() ) {
response.setContentType("image/jpg");
InputStream input = rset.getBinaryStream(1);
int imageByte;
while((imageByte = input.read()) != -1) {
out.write(imageByte);
}
input.close();
}
else
out.println("no picture available");
} catch( Exception ex ) {
out.println(ex.getMessage() );
}
// to close the connection
finally {
try {
conn.close();
} catch ( SQLException ex) {
out.println( ex.getMessage() );
}
}
} | 5 |
public static boolean login(String username, String pass){
Employee bean = new Employee();
bean.setUsername(username);
bean = (Employee)DatabaseProcess.getRow(bean);
//if username cannot be found in the database
if(bean == null){
System.out.println(username+" not found!");
return false;
}
if(bean.getUsername().equals(username)&&bean.getPass().equals(pass)){
Gui.setCurrentUser(bean);
return true;
}
System.out.println("incorrect username and password combination");
return false;
} | 3 |
public static SameAsService createNew() {
return new SameAsServiceImpl();
} | 0 |
public void setPlaymodes(Playmode[] playmodes){
if(playmodes != null){
for (Playmode playmode : playmodes) {
if(gameQueueMap.get(playmode.getPmID()) == null){
Queue<User> gameQueue = new LinkedList<>();
gameQueueMap.put(playmode.getPmID(), gameQueue);
}
}
}
} | 3 |
public int getCreatedDimensions() {
if (opcode == Opcode.MULTIANEWARRAY)
return iterator.byteAt(currentPos + 3);
else
return 1;
} | 1 |
public InstructionDecoder(){
m=new MyMap();
//Labels=new HashMap<String,Integer>();
} | 0 |
@Override
public Object invoke(Object proxy, Method m, Object[] args) {
try {
if (m == null || m.getName() == null) return null;
Class entityClass = Class.forName(ReflectionUtils.getNMSPackageName() + ".Entity");
if (m.getName().equals("a") && args.length == 1 && args[0] != null && classInstance(args[0].getClass(), entityClass)) {
this.onAddEntity();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} | 7 |
private void refreshRec(File parentFile, TreeItem parentItem){
for(File child : parentFile.listFiles()){
if(child.isFile() && !isValidFormat(child.getName())){
continue;
}
FilePathTreeItem item = generateFileItem(child);
parentItem.addChild(item);
if(child.isDirectory()){
if(expandMemorizer.isExpanded(item.getFilePath())){
//refreshRec(child, item);
item.setExpanded(true);
}
}
}
} | 5 |
public void endElement(final String namespaceURI,
final String localName,
final String qName)
throws SAXException {
charValue = charValue.trim();
if (t.findCriteria == C_FIND_ELEMENT_VALUE && t.b_TargetEntity && t.b_TargetNode){
if (t.matchingCriteria == C_VALUE_EXACT ){
if (charValue.equals(t.targetValue)){
t.addEntityToShopList(t.currentID);
}
}else{
//*** Under construction ***
/**
* TODO Implements for these conditions:
* if (matchingCriteria == VALUE_BIGGER )
* if (matchingCriteria == VALUE_EQUAL_OR_BIGGER )
* if (matchingCriteria == VALUE_SMALLER )
* if (matchingCriteria == VALUE_EQUAL_OR_SMALLER )
* */
throw new RuntimeException("ShopSAXParser.endElement() not yet fully implemented for these conditions. ");
}
}else if (t.findCriteria == C_FIND_SORTED && t.b_TargetNode ){
t.shopList_IdValues.addElement(new ShopVO(Integer.parseInt(t.currentID),
Float.parseFloat(charValue)));
}
if (qName.equals(t.shopMainNode)) {
t.b_TargetEntity = false;
b_store = false;//reset
}
charValue = ""; //reset at the end of each tag element
t.b_TargetNode = false;
} | 8 |
public void printGroupDataPK(String fpath) {
try {
FileReader rd = new FileReader(fpath);
BufferedReader br = new BufferedReader(rd);
Map<String, String> typemap = new HashMap<String, String>();
Map<String, String> groupmap = new HashMap<String, String>();
String line;
while ((line = br.readLine()) != null) { // prepare map : pairID -> error type ; group type
String st[] = line.split(",");
typemap.put(st[0], st[1]);
groupmap.put(st[0], st[2]);
}
// read test dataset
Map<String, SenData> senMap = readData("data/test.ser"); // load sentence data
for (Map.Entry<String, SenData> entry : senMap.entrySet()) {
senID = entry.getKey();
currSen = entry.getValue();
boolean print = false;
for (DDIPair pair : currSen.ddiList) {
if (typemap.containsKey(pair.id)) {
if (!print) {
System.out.print(currSen.senID + "\t");
printChunk(currSen.chunks);
print = true;
}
System.out.println(pair + "\t" + typemap.get(pair.id) + "\t" + groupmap.get(pair.id));
}
}
if (print) {
System.out.println("");
}
}
} catch (Exception ex) {
}
} | 7 |
@Override
public void setValueAt(Object value, int row, int col)
{
Physician p = phys.get(row);
int empID = p.getEmployeeId();
System.out.println("row: " + row + " col: " + col);
switch (col)
{
case 0:
p.setFirstName((String)value);
pb.updatePhysician(value, empID, col);
break;
case 1:
p.setLastName((String)value);
pb.updatePhysician(value, empID, col);
break;
case 2:
p.setBirthDate((Date)value);
pb.updatePhysician(value, empID, col);
break;
case 3:
p.setStartDate((Date)value);
pb.updatePhysician(value, empID, col);
break;
case 4:
p.setEndDate((Date)value);
pb.updatePhysician(value, empID, col);
break;
case 5:
p.setAddress((String)value);
pb.updatePhysician(value, empID, col);
break;
case 6:
p.setPhoneNumber((String)value);
pb.updatePhysician(value, empID, col);
break;
}
fireTableCellUpdated(row, col);
} | 7 |
private boolean processPlayerCommand(MapleClient c, MessageCallback mc, String[] splitted) {
DefinitionPlayerCommandPair definitionCommandPair = playercommands.get(splitted[0]);
if (definitionCommandPair != null) {
try {
definitionCommandPair.getCommand().execute(c, mc, splitted);
} catch (IllegalCommandSyntaxException ex) {
mc.dropMessage(ex.getMessage());
dropHelpForPlayerDefinition(mc, definitionCommandPair.getDefinition());
} catch (NumberFormatException nfe) {
mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below.");
dropHelpForPlayerDefinition(mc, definitionCommandPair.getDefinition());
} catch (ArrayIndexOutOfBoundsException ex) {
mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below.");
dropHelpForPlayerDefinition(mc, definitionCommandPair.getDefinition());
} catch (NullPointerException exx) {
mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage());
System.err.println("COMMAND ERROR" + exx);
} catch (Exception exx) {
mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage());
System.err.println("COMMAND ERROR" + exx);
}
return true;
} else {
mc.dropMessage("[The Elite Ninja Gang] Such command does not exist.");
}
return true;
} | 6 |
public void updateProgress() {
setStage(getStage() + 1);
if (getStage() == 1)
player.getInterfaceManager().sendSettings();
else if (getStage() == 2)
player.getPackets().sendConfig(1021, 0); // unflash
else if (getStage() == 5) {
player.getInterfaceManager().sendInventory();
player.getHintIconsManager().removeUnsavedHintIcon();
} else if (getStage() == 6)
player.getPackets().sendConfig(1021, 0); // unflash
else if (getStage() == 7)
player.getHintIconsManager().removeUnsavedHintIcon();
else if (getStage() == 10)
player.getInterfaceManager().sendSkills();
else if (getStage() == 11)
player.getPackets().sendConfig(1021, 0); // unflash
refreshStage();
} | 7 |
@Override
public String toString() {
return "Taso: " + this.tasonNumero;
} | 0 |
public void setPrpPosId(Integer prpPosId) {
this.prpPosId = prpPosId;
} | 0 |
public int threeSumClosest(int[] num, int target) {
int maxDiff = Integer.MAX_VALUE;
int result = 0;
Arrays.sort(num);
for (int i = 0; i < num.length-2; i++) {
int left = i + 1;
int right = num.length - 1;
while (left < right) {
int sum = num[left] + num[right] + num[i];
int diff = sum - target;
int absDiff = Math.abs(diff);
if (absDiff < maxDiff) {
maxDiff = absDiff;
result = sum;
}
if (diff > 0)
right--;
else if (diff < 0)
left++;
else {
return sum;
}
}
}
return result;
} | 5 |
public long skip(long n) throws IOException {
if(n == 0) return 0;
if(n > 0 && n < _bufferSize/2 && _dataInStream != null){
// Es besteht eine gute Wahrscheinlichkeit, dass die Zielposition noch gepuffert ist
int remaining = (int) n;
while(remaining > 0) {
int skipped = getDataInStream().skipBytes(remaining);
if(skipped <= 0) break;
remaining -= skipped;
}
if(remaining == 0){
// Skip Erfolgreich
_position += n;
return n;
}
// Sonst als Fallback position() benutzen und den _dataInStream bei Bedarf neu initialisieren
}
position(position() + n);
return n;
} | 7 |
public final WaiprParser.triggersource_return triggersource() throws RecognitionException {
WaiprParser.triggersource_return retval = new WaiprParser.triggersource_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token char_literal32=null;
ParserRuleReturnScope sender31 =null;
ParserRuleReturnScope trigger33 =null;
CommonTree char_literal32_tree=null;
RewriteRuleTokenStream stream_18=new RewriteRuleTokenStream(adaptor,"token 18");
RewriteRuleSubtreeStream stream_sender=new RewriteRuleSubtreeStream(adaptor,"rule sender");
RewriteRuleSubtreeStream stream_trigger=new RewriteRuleSubtreeStream(adaptor,"rule trigger");
try { dbg.enterRule(getGrammarFileName(), "triggersource");
if ( getRuleLevel()==0 ) {dbg.commence();}
incRuleLevel();
dbg.location(29, 0);
try {
// C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:30:2: ( sender '.' trigger -> ^( sender trigger ) )
dbg.enterAlt(1);
// C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:30:4: sender '.' trigger
{
dbg.location(30,4);
pushFollow(FOLLOW_sender_in_triggersource209);
sender31=sender();
state._fsp--;
stream_sender.add(sender31.getTree());dbg.location(30,11);
char_literal32=(Token)match(input,18,FOLLOW_18_in_triggersource211);
stream_18.add(char_literal32);
dbg.location(30,15);
pushFollow(FOLLOW_trigger_in_triggersource213);
trigger33=trigger();
state._fsp--;
stream_trigger.add(trigger33.getTree());
// AST REWRITE
// elements: sender, trigger
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null);
root_0 = (CommonTree)adaptor.nil();
// 30:23: -> ^( sender trigger )
{
dbg.location(30,26);
// C:\\Users\\Gyula\\Documents\\NetBeansProjects\\waiprProg\\src\\waiprprog\\Waipr.g:30:26: ^( sender trigger )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
dbg.location(30,28);
root_1 = (CommonTree)adaptor.becomeRoot(stream_sender.nextNode(), root_1);
dbg.location(30,35);
adaptor.addChild(root_1, stream_trigger.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
dbg.location(30, 42);
}
finally {
dbg.exitRule(getGrammarFileName(), "triggersource");
decRuleLevel();
if ( getRuleLevel()==0 ) {dbg.terminate();}
}
return retval;
} | 4 |
private void refreshAlarmList() {
List<Alarm> newList = new ArrayList<Alarm>(alarms);
if(selectedRadioButton.isSelected()) {
if(selectedHW != null) {
for(Iterator<Alarm> alarmIter = newList.iterator(); alarmIter.hasNext();) {
Alarm a = alarmIter.next();
if(!a.getTarget().getId().equals(selectedHW.getId())) {
alarmIter.remove();
}
}
}
}
if(alarmTypeComboBox.getSelectedIndex() != 0) {
String alarmType = (String) alarmTypeComboBox.getSelectedItem();
for(Iterator<Alarm> alarmIter = newList.iterator(); alarmIter.hasNext();) {
Alarm a = alarmIter.next();
if(!a.getType().equals(alarmType)) {
alarmIter.remove();
}
}
}
alarmTableModel.setAlarmList(newList);
} | 7 |
public static void main(String[] args) {
new Car().start();
} | 0 |
@Override
public void drawOpenGl() {
this.height = (int) Math.sqrt(RAM.MAX_LENGTH / 2);
this.width = 2 * this.height;
for (int i = 512; i < RAM.MAX_LENGTH; i++)
if (ram.memory_count_read[i] > max_read)
max_read = ram.memory_count_read[i];
for (int i = 512; i < RAM.MAX_LENGTH; i++)
if (ram.memory_count_write[i] > max_read)
max_write = ram.memory_count_write[i];
glViewport(0, 0, getWidth(), getHeight()); // 64*32 is the exact display
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0f, width, 0.0f, height);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
if ((x) + width * (y) == cpu.getRegister(19))
drawPC(x, y);
else
drawWhitePixel(x, y);
}
glPopMatrix();
} | 7 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FragmentIonType)) return false;
FragmentIonType that = (FragmentIonType) o;
return !(label != null ? !label.equals(that.label) : that.label != null) && !(name != null ? !name.equals(that.name) : that.name != null);
} | 5 |
public void getFirstLinks(ArrayList<Integer> theCodes) throws IOException{
boolean linkFound =false;
String temp = null;
String theUrl = "http://e-radio.gr/player/player.asp?sID=";
Document doc;
for(int code : theCodes){
linkFound=false;
theUrl = "http://e-radio.gr/player/player.asp?sID="+code;
doc = parseUrl(theUrl, 0);
if (doc!=null){
Elements media = doc.select("[src]");
print("Fetching %s --> ", theUrl);
for (Element src : media){
if (src.tagName().equals("iframe")==true){
temp = src.attr("abs:src");
if(temp.contains("playerX")==true){
linkFound=true;
temp = temp.replace(" ", "%");
stationLinks1.add(temp);
break;//link found no need to check another src on this url
}
}else if (src.tagName().equals("embed")==true){
linkFound=true;
temp = src.attr("abs:src");
temp = temp.replace(" ", "%");
stationLinks1.add(temp);
break;//link found no need to check another src on this url
}
}//end nested for
if(linkFound==false) {
print("Unprocessed, no iframe - embed tag for url: %s", theUrl);
unProsessedLinks.add(theUrl);
continue;
}
}else{
print("Unprocessed, no connection for url: %s", theUrl);
unProsessedLinks.add(theUrl);
continue;
}
}//end outer for
print("Unprosessed Links: %s", unProsessedLinks.size());
print("Processed Links: %s", stationLinks1.size());
//write all the links to the disk
writeLinksToFile(linksFileName, stationLinks1);
writeLinksToFile(unProcLinksFileName, unProsessedLinks);
}//end method | 7 |
private static int getMinElementInRotArrayHelper(int[] arr, int start,
int end)
{
if (end < start) return arr[0];
if (start == end)
{
return arr[start];
}
int mid = (start + end) / 2;
if (mid < end && arr[mid+1] < arr[mid])
{
return arr[mid+1];
}
if (mid > start && arr[mid] < arr[mid-1])
{
return arr[mid];
}
if (arr[end] > arr[mid])
{
return getMinElementInRotArrayHelper(arr, start, mid-1);
}
return getMinElementInRotArrayHelper(arr, mid + 1, end);
} | 7 |
public PruebaFacade() {
super(Prueba.class);
} | 0 |
public static boolean isDouble(String input)
{
try
{
Double.parseDouble(input);
return true;
}
catch(Exception e)
{
return false;
}
} | 1 |
public void run() {
String msg;
try {
// petla, ktora odczytuje wiadomosci z serwera i wypisuje je
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
System.err.println(e);
}
} | 2 |
static final void method560(Class318_Sub4 class318_sub4, int i) {
try {
anInt8652++;
((Class318_Sub4) class318_sub4).aClass318_Sub1_6410 = null;
int i_11_ = (((Class318_Sub4) class318_sub4)
.aClass318_Sub3Array6414).length;
int i_12_ = 127 / ((i - 82) / 32);
for (int i_13_ = 0; (i_11_ ^ 0xffffffff) < (i_13_ ^ 0xffffffff);
i_13_++)
((Class318_Sub3) (((Class318_Sub4) class318_sub4)
.aClass318_Sub3Array6414
[i_13_])).aBoolean6401
= false;
synchronized (Class318.aClass243Array3974) {
if ((i_11_ ^ 0xffffffff) > (Class318.aClass243Array3974.length
^ 0xffffffff)
&& (Class331.anIntArray4128[i_11_] ^ 0xffffffff) > -201) {
Class318.aClass243Array3974[i_11_]
.method1869(-126, class318_sub4);
Class331.anIntArray4128[i_11_]++;
}
}
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("hha.E("
+ (class318_sub4 != null ? "{...}"
: "null")
+ ',' + i + ')'));
}
} | 5 |
@FXML
void onRepositoryChanged(ActionEvent event) {
// TODO add your handling code here:
try {
String wrkDir = (String)ctrlRepository.getValue();
ResultSet rs = Repo.fetchByNeve(wrkDir);
String branch = new String();
ObservableList<String> branchList = ctrlBranch.getItems();
if (branchList.isEmpty()) {
branchList = FXCollections.observableArrayList();
}
while (rs.next()) {
Repo adat = new Repo(rs);
ctrlIssueId.setText(adat.getIssueId());
ctrlZipFilePrefix.setText(adat.getZipPrefix());
branch = adat.getBranch();
}
GitRepo repo = new GitRepo(wrkDir);
HashMap<ObjectId, String> branches = repo.getBranches();
Iterator it = branches.values().iterator();
while (it.hasNext()) {
String br = (String)it.next();
branchList.add(br);
}
if (branch != null && !branch.isEmpty()) {
ctrlBranch.setValue(branch);
}
ctrlBranch.setItems(branchList);
} catch (SQLException ex) {
Logger.getLogger(GitSnapshotMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GitSnapshotMain.class.getName()).log(Level.SEVERE, null, ex);
}
} | 7 |
private void calculateNextIndices() {
Integer[] nextArr = new Integer[v.size()];
Integer target = 0;
Integer startIndex = target;
Set<Integer> usedIndices = new HashSet<>();
while (notAllFilled(nextArr)) {
Integer nextIndex = null;
Edge curEdge = new Edge(points.get(v.get(startIndex)), points.get(v.get(o.get(startIndex))));
Set<Integer> possibleNextIndices = new HashSet<>();
for (int i = 0; i < v.size(); i++) {
if (v.get(i).equals(v.get(o.get(startIndex))) && !usedIndices.contains(i)) {
possibleNextIndices.add(i);
}
}
double minAngle = Double.MAX_VALUE;
for (Integer j : possibleNextIndices) {
Vector v1 = curEdge.asVec().normalize();
Vector v2 = new Edge(points.get(v.get(j)), points.get(v.get(o.get(j)))).asVec().normalize();
double angleBetween = v1.angleBetween(v2);
if (angleBetween < minAngle) {
minAngle = angleBetween;
nextIndex = j;
}
}
nextArr[startIndex] = nextIndex;
usedIndices.add(nextIndex);
startIndex = nextIndex;
if (nextIndex.equals(target)) {
for (int i = 0; i < nextArr.length; i++) {
if (nextArr[i] != null) continue;
startIndex = i;
target = startIndex;
break;
}
}
}
n = Arrays.asList(nextArr);
} | 9 |
public void askNbJoueur() {
// Création de la fenêtre de choix
WinMenu nbMenu = new WinMenu("Combien de joueurs pour cette partie ?");
nbMenu.newItem("2 joueurs", 2);
nbMenu.newItem("3 joueurs", 3);
nbMenu.newItem("4 joueurs", 4);
// Affiche la fenêtre de choix
int nbJoueur = nbMenu.open();
// Si la fenêtre a été fermée, on termine le processus
if (nbJoueur < 0) {
System.exit(0);
}
// On charge le plateau correspondant au nom de joueur sélectionné
loadPlateau(nbJoueur);
// On crée les joueurs
for (int i = 0; i < nbJoueur; i++) {
String name;
do {
name = Prompt.ask("Choissiez un nom pour le joueur n°" + (i + 1));
} while (name.length() == 0);
Joueur j = new Joueur(name, Partie.DEFAULT_ARGENT);
j.setIndice(i);
partieEnCours.ajouterJoueur(j);
}
} | 3 |
public static void main (String[] args) {
Log.makeLog("Cyc-SOAP-client.log");
CycSOAPClient cycSOAPClient = new CycSOAPClient();
try {
cycSOAPClient.helloWorld();
for (int i = 0; i < 10; i++) {
Log.current.print((i + 1) + ". ");
Log.current.println(cycSOAPClient.remoteSubLInteractor("(isa #$TransportationDevice)"));
}
Log.current.println("categorizeEntity Service");
String entityString = "Osama Bin Laden";
String generalEntityKindString = "PERSON";
Log.current.println("categorizeEntity(\"" + entityString + "\", \"" + generalEntityKindString + "\")");
String response = cycSOAPClient.categorizeEntity(entityString, generalEntityKindString);
Log.current.println("response=" + response);
String ontologyString = "AXISConstant";
Log.current.println("categorizeEntityWithinOntology Service");
Log.current.println("categorizeEntityWithinOntology(\"" + entityString + "\", \"" + generalEntityKindString + "\", \"" + ontologyString + "\")");
response = cycSOAPClient.categorizeEntityWithinOntology(entityString, generalEntityKindString, ontologyString);
Log.current.println("response=" + response);
}
catch( Exception e ) {
Log.current.errorPrintln(e.getMessage());
Log.current.printStackTrace(e);
}
} | 2 |
public static String getJsonFromAssets(String filePath) {
InputStream is;
Writer writer = new StringWriter();
char[] buffer = new char[8 * 1024];
try {
is = new FileInputStream(new File(filePath));
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n = 0;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return writer.toString();
} | 2 |
@Override
public void run() {
Player player = Bukkit.getPlayer(playerName);
if (player == null) {
return;
}
player.setSleepingIgnored(false);
BukkitTask task = plugin.getIgnoreSleepTasks().get(playerName);
if (task != null) {
task.cancel();
}
task = new IgnoreSleepTask(plugin, playerName).runTaskLater(plugin, plugin.getIgnoreSleepTaskDelay());
plugin.getIgnoreSleepTasks().put(playerName, task);
} | 2 |
private void moveIfInBounds(String s) {
if (s == "left") {
animationTimer.stop();
invalidate();
moveView(-movementDistance, 0);
repaint();
animationTimer.start();
} else if (s == "right") {
animationTimer.stop();
invalidate();
moveView(movementDistance, 0);
repaint();
animationTimer.start();
} else if (s == "top") {
animationTimer.stop();
invalidate();
moveView(0, -movementDistance);
repaint();
animationTimer.start();
} else if (s == "bottom") {
animationTimer.stop();
invalidate();
moveView(0, movementDistance);
repaint();
animationTimer.start();
}
} | 4 |
public void updateQuality() {
if (sellIn > 0) {
quality++;
}
if(sellIn <= 10) {
quality++;
}
if(sellIn <= 5) {
quality++;
}
if (quality > 50) {
quality = 50;
}
if (sellIn <= 0) {
quality = 0;
}
sellIn--;
} | 5 |
private void registerRenderer(IXMLElement xml) {
String name=null,description=null, className = null;
IXMLElement params=null;
Enumeration children = xml.enumerateChildren();
while (children.hasMoreElements()){
IXMLElement child = (IXMLElement)children.nextElement();
if (child.getName().equals("name")){
name=child.getContent();
continue;
}
if (child.getName().equals("description")){
description=child.getContent();
continue;
}
if (child.getName().equals("class")){
className=child.getContent();
continue;
}
if (child.getName().equals("parameters")){
params=child;
continue;
}
System.err.println(child);
}
if (name==null || className==null){
System.err.println("Failed to register renderer, because no class name specified");
}
RendererRecord rcd= new RendererRecord(name,description,className,params);
registeredRenderers.add(rcd);
} | 7 |
private static String relativizePath(final String dirStr, final String uriStr) {
// Pfad an Schrägstrichen auftrennen, mehrere aufeinander folgende werden zusammengefasst. (/bla////foo ist gleich /bla/foo)
final String[] dir = dirStr.split("/+", -1);
final String[] uri = uriStr.split("/+", -1);
int commonIndex = 0;
for(int i = 0; i < uri.length && i < dir.length; i++) {
if(!uri[i].equals(dir[i])) {
break;
}
commonIndex++;
}
if(commonIndex <= 1) {
// Nicht bis zum root zurückwandern, das wäre sinnlos. Stattdessen absoluten Pfad zurückgeben.
return uriStr;
}
final StringBuilder result = new StringBuilder(uriStr.length());
// Von dir rückwärts wandern, bis an gemeinsamen Pfad angelangt.
for(int i = dir.length - 1; i > commonIndex; i--) {
result.append("../");
}
// und jetzt in Richtung uri wandern
for(int i = commonIndex; i < uri.length; i++) {
result.append(uri[i]).append('/');
}
if(result.length() == 0) {
return "";
}
result.setLength(result.length() - 1);
return result.toString();
} | 7 |
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
if (json.isJsonNull()) {
return null;
} else if (json.isJsonPrimitive()) {
return handlePrimitive(json.getAsJsonPrimitive());
} else if (json.isJsonArray()) {
return handleArray(json.getAsJsonArray(), context);
} else {
return handleObject(json.getAsJsonObject(), context);
}
} | 3 |
public void startSQL() {
try {
InputStream in = this.getClass().getResourceAsStream("/sols/Util/jdbc.properties");
Properties pp = new Properties();
pp.load(in);
url = pp.getProperty("jdbc.url");
user = pp.getProperty("jdbc.username");
password = pp.getProperty("jdbc.password");
driver = pp.getProperty("jdbc.driver");
} catch (IOException ex) {
Logger.getLogger(SQLHelper.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
private void placeInterpolationParameters() {
interpolationParametersPanel.setLayout(gridBagLayout);
//Create GridBagConstraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.NORTHWEST;
constraints.insets = DEFAULT_INSETS;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(numberOfSpheresLabel, constraints);
constraints.gridx++;
gridBagLayout.setConstraints(numberOfSpheresTextField, constraints);
interpolationParametersPanel.add(numberOfSpheresLabel);
interpolationParametersPanel.add(numberOfSpheresTextField);
} | 0 |
static double[][] multiply(double[][] A, double[][] B){
double[][] AB = new double[A.length][B[0].length];
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B[i].length; j++){
for(int k = 0; k < B.length ; k++){
AB[i][j] += A[i][k]*B[k][j];
}
}
}
return AB;
} | 3 |
public static final void notEquals(Object obj, Object another, String message) {
isTrue((obj == null && another != null) || (obj != null && obj.equals(another)), message);
} | 3 |
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} | 8 |
public void run(){
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(),packet.getAddress(),packet.getPort());
String message = new String(packet.getData()).trim();
//System.out.println("CLIENT [" + packet.getAddress().getHostAddress() + ":" + packet.getPort() + "]> " +message);
if(message.trim().equalsIgnoreCase("ping")){
sendData("pong".trim().getBytes(),packet.getAddress(),packet.getPort());
}
}
} | 3 |
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof VarDescr)) return false;
VarDescr d = (VarDescr) o;
return (this.addr == d.getAddr()) && (this.typ.equals(d.getTyp()));
} | 3 |
@EventHandler
public void onInteract(PlayerInteractEvent evt){
if(evt.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if(evt.getClickedBlock().getType() == Material.SIGN || evt.getClickedBlock().getType() == Material.SIGN_POST || evt.getClickedBlock().getType() == Material.WALL_SIGN){
if(((Sign) evt.getClickedBlock().getState()).getLine(0).contains("Arena-")){
Sign s = (Sign) evt.getClickedBlock().getState();
int arenaNum = Integer.parseInt(s.getLine(0).replaceAll("Arena-", ""));
Arena a = ArenaManager.getManager().getArena(arenaNum);
int maxPlayers = Integer.parseInt(s.getLine(2).replace(a.getSize() + " / ", ""));
if(maxPlayers == a.getSize() + 1){
evt.getPlayer().sendMessage("The arena is full");
} else {
PlayerJoinArenaEvent event = new PlayerJoinArenaEvent(evt.getPlayer() , a);
Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled() == false){
ArenaManager.getManager().addPlayer(evt.getPlayer(), a);
SignUpdate.getCons().updatePlayers(s, a);
}
}
}
}
}
} | 7 |
public static Object getMethodArrayValue(java.lang.reflect.Method _p,
Object _o, int _i[]) {
int n, k;
Object o = null;
n = (_i == null) ? 0 : _i.length;
try {
if (_p.getReturnType().equals(java.lang.Integer.TYPE)) {
o = _p.invoke(_o);
} else if (_p.getReturnType().equals(java.lang.Double.TYPE)) {
o = _p.invoke(_o);
} else {
o = _p.invoke(_o);
for (k = 0; k < n && o != null && o.getClass().isArray(); k++) {
if (o.getClass() == (double[].class)) {
o = new Double(((double[]) o)[_i[k]]);
} else if (o.getClass() == (int[].class)) {
o = new Integer(((int[]) o)[_i[k]]);
} else {
o = (((Object[]) o)[_i[k]]);
}
}
}
} catch (Exception ex) {
System.out.println(_p.getReturnType().getComponentType().getName()
+ "\t" + _p.getName() + "\t" + _o.getClass().getName()
+ "\t" + Integer.toString(n));
}
return o;
} | 9 |
public void feedTable(Object[] list) {
Object[][] data = { { "No Results Found!" } };
String[] columnNames = { "Error!" };
if (null != list && list.length > 0) {
// get fields from the first object in array, one object required to
// get columns,
// unless class is added as a parameter? might look better when
// displaying empty results.
Field[] fieldNames = list[0].getClass().getDeclaredFields();
columnNames = new String[fieldNames.length];
columnNames = filterColumns(fieldNames);
// specify output size, object count x column count
data = new Object[list.length][fieldNames.length];
// iterate over field names getting their values.
for (int i = 0; i < list.length; i++) {
// the object
Object c = list[i];
for (int j = 0; j < columnNames.length; j++) {
try {
// the field, "column"
Field field = c.getClass().getDeclaredField(
columnNames[j]);
field.setAccessible(true);
Object value = field.get(c);
if (null != value) {
//System.out.println(value.toString());
data[i][j] = value.toString().replace("[", "")
.replace("]", "");
} else
data[i][j] = "";
field.setAccessible(false);
} catch (NoSuchFieldException | SecurityException
| IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
// remove old
scrollPane.remove(table);
contentPane.remove(scrollPane);
// add new
table = new JTable(data, columnNames);
scrollPane = new JScrollPane(table);
contentPane.add(scrollPane);
// resize columns, setting minWidth to length of every column
// loops through every row.
int[] minWidthColumn = new int[table.getColumnCount()];
for (int i = 0; i < table.getColumnCount(); i++) {
for (int j = 0; j < table.getRowCount(); j++) {
String text = table.getValueAt(j, i).toString();
int columnWidth = table.getFontMetrics(table.getFont())
.stringWidth(text);
if (columnWidth > minWidthColumn[i]) {
minWidthColumn[i] = columnWidth;
table.getColumnModel().getColumn(i)
.setMinWidth(columnWidth + 6);
}
}
}
updateView();
} | 9 |
private void handleInferenceAnswerResult(CycList data) {
if (data.size() != 2) {
throw new RuntimeException("Got wrong number of arguments " + "from inference result (expected 2): " + data);
}
Object newAnswers = data.get(1);
if ((newAnswers == null) || (!(newAnswers instanceof CycList))) {
throw new RuntimeException("Got bad inference answers list: " + newAnswers);
}
answers.addAll((List) newAnswers);
Object[] curListeners = getInferenceListeners();
List<Exception> errors = new ArrayList<Exception>();
for (int i = curListeners.length - 1; i >= 0; i -= 1) {
try {
((InferenceWorkerListener) curListeners[i]).notifyInferenceAnswersAvailable(this, (List) newAnswers);
} catch (Exception e) {
errors.add(e);
}
}
if (errors.size() > 0) {
throw new RuntimeException(errors.get(0)); // @hack
}
} | 6 |
public void toggleContainerHUD(HUD h) {
HUD hud = null;
boolean isOpen = false;
//see if the hud is currently open
for (int i = (huds.size() - 1); i >= 0; i--) {
hud = huds.get(i);
if (hud == h) {
isOpen = hud.getShouldRender();
break;
}
}
if (isOpen) {
hud.setShouldRender(false);
} else {
//make sure all the other huds are closed and show the container
for (int i = (huds.size() - 1); i >= 0; i--) {
hud = huds.get(i);
if (hud.getIsContainer()) {
if (hud == h) {
hud.setShouldRender(true);
} else {
hud.setShouldRender(false);
}
}
}
}
checkRestoreCuror();
} | 6 |
public float retrieveSupplierAmount(String supName) throws SQLException{
float getAmount = 0;
try{
databaseConnector=myConnector.getConnection();
stmnt=(Statement) databaseConnector.createStatement();
SQLQuery="SELECT Amount FROM familydoctor.supplier WHERE Name="+"'"+supName+"'";
dataSet=stmnt.executeQuery(SQLQuery);
while(dataSet.next()){
getAmount=dataSet.getFloat("Amount");
}
}
catch(SQLException e){
System.out.println(e.getMessage());
}
finally{
if(stmnt!=null)
stmnt.close();
if(databaseConnector!=null)
databaseConnector.close();
}
return getAmount;
} | 4 |
public Element parseElement(CharSequence content) {
Map<String,String> styles = new HashMap<String, String>();
Matcher matcher = META.matcher(content);
if(matcher.find()) {
parseStyles(styles, matcher.group(2));
content = matcher.replaceFirst("");
}
Matcher noteMatcher = NOTE.matcher(content);
if(noteMatcher.matches()) {
return new NoteElement(noteMatcher.group(1).trim()).usingStyles(styles);
}
else {
String[] parts = PARTS.split(content);
List<String> attributes = splitValuesOrEmpty(parts, 1);
List<String> methods = splitValuesOrEmpty(parts, 2);
return new ClassElement(parts[0], attributes, methods).usingStyles(styles);
}
} | 2 |
public void paint(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(0,0,canvas_width,canvas_height);
g.setColor(Color.BLACK);
int count = 0;
while(count < grid_lines+1){
g.setColor(Color.BLACK);
g.drawLine(0,grid_size_y*count,canvas_height,grid_size_y*count);
g.drawLine(grid_size*count,0,grid_size*count,canvas_height);
count++;
}
Square[][] boardSquares = board.getBoardArray();
int countY = 0;
while(countY<boardSquares.length){
int countX = 0;
while(countX<boardSquares[0].length){
//System.out.println("Drawing a:"+squares[countY][countX].getID()+"in square"+countY+":"+countX);
int sqx = countX*grid_size;
int sqy = countY*grid_size_y;
Color currentColor = getBoardSqColor(boardSquares[countY][countX]);
if(currentColor!=null){
g.setColor(currentColor);
g.fillRect(sqx,sqy,grid_size,grid_size_y);
}
if(boardSquares[countY][countX].getOccupied()!=null){
g.setColor(getPColor(boardSquares[countY][countX].getOccupied()));
g.fillOval(sqx,sqy,piece_size,piece_size);
g.setColor(Color.black);
g.drawOval(sqx,sqy,piece_size,piece_size);
g.drawOval(sqx+5,sqy+5,piece_size-10,piece_size-10);
g.drawOval(sqx+8,sqy+8,piece_size-16,piece_size-16);
}
countX++;
}
countY++;
}
((Graphics2D)g).setStroke(new BasicStroke(2f));
g.setColor(Color.black);
g.drawRect(0, 0,canvas_width-1,canvas_height-1);
} | 5 |
public void addPatient(PatientCL newPatient){
if (this.nextPatient == patientListStart){
this.nextPatient = newPatient;
} else {
this.nextPatient.addPatient(newPatient);
}
} | 1 |
public void clearView(Class[] classesToIgnore) {
YIComponent view = controller.getView();
ArrayList comps = YUIToolkit.getViewComponents(view);
Iterator it = comps.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof YIModelComponent) {
YIModelComponent comp = (YIModelComponent) obj;
boolean ignore=false;
for (int i=0; i < classesToIgnore.length; i++) {
if (classesToIgnore[i].isAssignableFrom(obj.getClass())) {
ignore = true;
}
}
if (!ignore) {
try {
comp.setModelValue(null);
} catch (Exception ex) {
// unexpected exception, this should never happen:
controller.handleException(ex);
}
}
}
}
controller.copyToModel(null);
} | 6 |
public String nextValue() throws IOException {
if (tokenCache == null){
tokenCache = lexer.getNextToken();
lineCache = lexer.getLineNumber();
}
lastLine = lineCache;
String result = tokenCache;
tokenCache = null;
return result;
} | 1 |
@Override
public int flush(String path, Object fh) throws FuseException {
FileHandle handle = (FileHandle)fh;
if (handle == null)
return Errno.EBADSLT;
if (handle.hasClosed)
return Errno.EBADSLT;
//well... shouldn't happen, but it does happen...
if (!handle.write)
return 0;
//return Errno.EACCES;
try {
fileSystem.flush(handle);
} catch (DriveFullException e) {
return Errno.ENOSPC;
}
return 0;
} | 4 |
public ConnectionLogger get_logger()
{
return logger;
} | 0 |
public Cell getCell(int[] cell) {
if ((cell[0] < height && cell[1] < width) && (cell[0] >= 0 && cell[1] >= 0)) {
return cells[cell[0]][cell[1]];
} else {
return null;
}
} | 4 |
public void broundMsg(Client sockector, Response msg) throws IOException{
byte[] msgs = CoderUtils.toByte(msg.getBody());
ClustersMessage messageFrame = sockector.getRequestWithFile().<ClustersMessage>getMessageHeader(msg.getRequestIndex());
if(messageFrame == null){
messageFrame = new ClustersMessage();
}
messageFrame.setDateLength(msgs.length);
byte[] headers = new byte[2];
// todo list
headers[0] = ClustersMessage.FIN;// 需要调整
headers[0] |= messageFrame.getRsv1() | messageFrame.getRsv2() | messageFrame.getRsv3() | ClustersMessage.TXT;
headers[1] = 0;
//headers[1] |= messageFrame.getMask() | messageFrame.getPayloadLen();
headers[1] |= 0x00 | messageFrame.getPayloadLen();
msg.appendBytes(headers);// 头部控制信息
if (messageFrame.getPayloadLen() == ClustersMessage.HAS_EXTEND_DATA) {// 处理数据长度为126位的情况
msg.appendBytes(CoderUtils.shortToByte(messageFrame.getPayloadLenExtended()));
} else if (messageFrame.getPayloadLen() == ClustersMessage.HAS_EXTEND_DATA_CONTINUE) {// 处理数据长度为127位的情况
msg.appendBytes(CoderUtils.longToByte(messageFrame.getPayloadLenExtendedContinued()));
}
/*if(messageFrame.isMask()){// 做了掩码处理的,需要传递掩码的key
byte[] keys = messageFrame.getMaskingKey();
msg.appendBytes(messageFrame.getMaskingKey());
for(int i = 0; i < msgs.length; ++i){// 进行掩码处理
msgs[i] ^= keys[i % 4];
}
}*/
msg.appendBytes(msgs);
sockector.getRequestWithFile().clearMessageHeader(msg.getRequestIndex());// 清理每次连接交互的数据
} | 3 |
private static void Trigger(){
if(_cmd.getArgs().length == 0){
return;
}
if(_cmd.getArg(0).equalsIgnoreCase("reload")){
if(_cmd.isPlayer()){
if(!_cmd.getPlayer().hasPermission(_Permission + ".reload")){
if(!_cmd.getPlayer().isOp()){
sendMessage("You do not have permission to run this command");
return;
}
}
}
sendMessage("Reloading");
mcs._plugin.reloadConfig();
mcs._plugin.reload();
sendMessage("Finished Reloading");
}
} | 5 |
public void update(long dt)
{
if (Config.use_wasd) {
Coord newWASD = APXUtils.updateWASD();
if (!newWASD.equals(lastWASD)) {
lastWASD = newWASD;
map_click_ntf(lastWASD.x, lastWASD.y, 1, 0);
}
}
Gob pl = glob.oc.getgob(playergob);
Coord myCurrentCoord = null;
if(pl != null)
{
myCurrentCoord = pl.position();
if(myCurrentCoord != null && myLastCoord != null)
if(myCurrentCoord.dist(myLastCoord) > 30*11 && cam != null) {
cam.reset();
}
}
myLastCoord = myCurrentCoord;
update_pf_moving();
} | 7 |
boolean readMessage(ObjectInputStream ips) {
Message receive = null;
String name = nickname;
try {
Object fromServ = ips.readObject();
if (fromServ instanceof Message) receive = (Message) fromServ;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (receive instanceof ChangeNickMessage) {
name = ((ChangeNickMessage)receive).name;
multiQueue.put(new StatusMessage(nickname+" is now known as "+name+"."));
nickname = name;
}
if (receive instanceof ChatMessage) {
RelayMessage m = new RelayMessage(nickname, (ChatMessage) receive);
multiQueue.put(m);
try {
database.addMessage(m);
} catch (SQLException e) {
e.printStackTrace();
}
}
return true;
} | 5 |
public LoginWindow(final MasterModel masterModel) {
super("MyCMS Login");
// this.intro = intro;
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
dispose();
masterModel.intro.rebirthIntro();
}
});
// Changed to DISPOSE_ON_CLOSE so that this window will not exit the
// whole program on exit
// setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(335, 120);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - getWidth()) / 2);
int y = (int) ((dimension.getHeight() - getHeight()) / 2);
setLocation(x, y);
JPanel center = new JPanel();
setLayout(new GridLayout(1, 3));
Font font = new Font("SansSerif", Font.BOLD, 14);
userLabel = new JLabel("UserName");
userLabel.setFont(font);
center.add(userLabel);
userField = new JTextField("", 16);
userField.setFont(font);
center.add(userField);
passwordLabel = new JLabel(" Password");
passwordLabel.setFont(font);
center.add(passwordLabel);
passwordField = new JPasswordField("", 16);
passwordField.setFont(font);
center.add(passwordField);
login = new JButton("Login");
login.setFont(font);
center.add(login);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String username = "";
String password = "";
username = String.format(userField.getText());
password = String.format(passwordField.getText());
boolean[] flag = { false, false };
try {
flag = ench.logincheck(username, password, masterModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (flag[0]) {// checks if login was correct
dispose();
if (flag[1]) {
JOptionPane.showMessageDialog(login,
"ADMIN Login Successful");
} else
JOptionPane
.showMessageDialog(login, "Login Successful");
try {
database = new CustomerController(masterModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MainWindow(username, database, flag[1], masterModel); // open
// our
// main
// program
} else
// login was incorrect
JOptionPane.showMessageDialog(login,
"username and password is incorrect");
}
});
passwordField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String username = "";
String password = "";
username = String.format(userField.getText());
password = String.format(passwordField.getText());
boolean[] flag = { false, false };
try {
flag = ench.logincheck(username, password, masterModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (event.getSource() == passwordField) {
// this needs to get replaced with the ench.logincheck
// method for now we leave in for testing
if (flag[0]) {// checks if login was correct
dispose();
if (flag[1]) {
JOptionPane.showMessageDialog(null,
"ADMIN Login Successful");
} else
JOptionPane.showMessageDialog(null,
"Login Successful");
try {
database = new CustomerController(masterModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MainWindow(username, database, flag[1], masterModel); // open
// our
// main
// program
} else
// login was incorrect
JOptionPane.showMessageDialog(null,
"username and password is incorrect");
}
}
});
add(center, BorderLayout.CENTER);
setResizable(false);
setVisible(true);
} | 9 |
public static void main(String [] args) {
//Create a starting time
double startTime = System.currentTimeMillis();
String bigNum = "73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450";
int max = 0;
for( int i = 0; i < bigNum.length()-5; i++) {
int product = 1;
for( int j = i; j < 5 + i; j++) {
int num = Character.getNumericValue(bigNum.charAt(j));
product *= num;
}
if( product > max) {
max = product;
}
}
System.out.println("The max is: " + max);
//Create an end time
double endTime = System.currentTimeMillis();
//Calculate total time
double totalTime = endTime - startTime;
//Print out the time
System.out.println("Time: " + totalTime);
} | 3 |
@Override
public void run(Request r) {
if (!isStarted()) {
return;
}
WebServer.logDebug("Site's Run Called on RequestID: " + r.getRequestID() + " For site " + getName());
boolean found = false;
for (String defaultDocument : getDefaultDocuments()) {
if (getSettings().get("DOCUMENT_ROOT") != null) {
String uri = Utils.stripQueryString(r.getVariables().get("REQUEST_URI"));
String path = getSettings().get("DOCUMENT_ROOT") + Utils.cPath(uri + defaultDocument);
WebServer.logDebug("Testing for Document " + path);
System.out.println("Reading: " + path);
// String file = Utils.readFile(path);
byte[] file = Utils.readBytes(path);
System.out.println("Read: " + path);
if (file == null) {
continue;
}
MIME mime = MIME.getMIME(path);
if (mime.getTypes() != null) {
try {
r.getClient().getOutputStream()
.write(("Content-Type: " + StringUtils.join(mime.getTypes(), '/')).getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
WebServer.logDebug("Found a File (" + path + ") for RequestID: " + r.getRequestID());
// r.out.println("Content-Type: text/html");
try {
r.getClient().getOutputStream().write(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// r.out.write(file);
WebServer.logDebug("Returned " + r.getPath());
found = true;
break;
} else {
WebServer.triggerInternalError("[DOCUMENT_ROOT] is not defined for site " + getName());
}
}
if (!found) {
triggerHTTPError(r, 404);
}
r.close();
} | 8 |
public int getStartStop() {
return this._startStop;
} | 0 |
private void setMarketPathToScale() {
graphInterval = (frameW - 2 * SIDE_BUFFER)
/ (marketComparison.size() - 1);
gridLines.clear();
float minimumPt = findMinimum(marketComparison.values());
float maximumPt = findMaximum(marketComparison.values());
// System.out.println("range: "+minimumPt+" --- "+maximumPt);
float range = maximumPt - minimumPt;
float localScale = (frameH - 2 * SIDE_BUFFER) / range;
GeneralPath graph = new GeneralPath();
int i = 0;
for (float f : marketComparison.values()) {
float xpt = SIDE_BUFFER + graphInterval * i;
float ypt = frameH - (SIDE_BUFFER + localScale * (f - minimumPt));
// System.out.println("POINTS IN PATH: "+xpt+" --- "+ypt);
GeneralPath gridL = new GeneralPath();
gridL.moveTo(xpt, 0);
gridL.lineTo(xpt, frameH);
gridLines.add(gridL);
if (i == 0) {
graph.moveTo(xpt, ypt);
} else {
graph.lineTo(xpt, ypt);
}
i++;
}
viewMarket = (graph);
} | 2 |
public static String getJmeterVersion() {
String version = JMeterUtils.getJMeterVersion();
int hyphenIndex = version.indexOf("-");
int spaceIndex = version.indexOf(" ");
return (hyphenIndex != -1 & spaceIndex == -1) ?
version.substring(0, hyphenIndex) :
version.substring(0, spaceIndex);
} | 1 |
public double getHeight() {
return height;
} | 0 |
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
DoTurn(pw);
pw.FinishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
}
} | 4 |
private void setRandomColor() {
Random estrattore = new Random();
int estratto = estrattore.nextInt(7);
switch (estratto) {
case 0:
jLabel4.setForeground(Color.BLACK);
break;
case 1:
jLabel4.setForeground(Color.BLUE);
break;
case 2:
jLabel4.setForeground(Color.GRAY);
break;
case 3:
jLabel4.setForeground(Color.MAGENTA);
break;
case 4:
jLabel4.setForeground(Color.ORANGE);
break;
case 5:
jLabel4.setForeground(Color.PINK);
break;
case 6:
jLabel4.setForeground(Color.RED);
break;
}
} | 7 |
@Override
public Model getRotatedModel() {
Model model = animation.getModel();
if (model == null)
return null;
int frame = animation.sequences.frame2Ids[elapsedFrames];
Model animatedModel = new Model(true, Animation.isNullFrame(frame),
false, model);
if (!transformationCompleted) {
animatedModel.createBones();
animatedModel.applyTransformation(frame);
animatedModel.triangleSkin = null;
animatedModel.vertexSkin = null;
}
if (animation.scaleXY != 128 || animation.scaleZ != 128)
animatedModel.scaleT(animation.scaleXY, animation.scaleXY,
animation.scaleZ);
if (animation.rotation != 0) {
if (animation.rotation == 90)
animatedModel.rotate90Degrees();
if (animation.rotation == 180) {
animatedModel.rotate90Degrees();
animatedModel.rotate90Degrees();
}
if (animation.rotation == 270) {
animatedModel.rotate90Degrees();
animatedModel.rotate90Degrees();
animatedModel.rotate90Degrees();
}
}
animatedModel.applyLighting(64 + animation.modelLightFalloff,
850 + animation.modelLightAmbient, -30, -50, -30, true);
return animatedModel;
} | 8 |
protected void genDeity(MOB mob, MOB M, int showNumber, int showFlag)
throws IOException
{
if((showFlag<=0)||(showFlag==showNumber))
{
mob.tell(L("@x1. Deity (ID): '@x2'.",""+showNumber,M.getWorshipCharID()));
if((showFlag==showNumber)||(showFlag<=-999))
{
final String newName=mob.session().prompt(L("Enter a new one (null)\n\r:"),"");
if(newName.equalsIgnoreCase("null"))
M.setWorshipCharID("");
else
if(newName.length()>0)
{
if(CMLib.map().getDeity(newName)==null)
mob.tell(L("That deity does not exist."));
else
M.setWorshipCharID(CMLib.map().getDeity(newName).Name());
}
else
mob.tell(L("(no change)"));
}
}
} | 7 |
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
showHelp(sender);
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("list")) {
sender.sendMessage(StringUtils.join(Effect.values(), ", "));
return true;
}
if (args.length > 0) {
try {
parseCommand(sender, args);
} catch (EntityEffectError e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
return false;
} | 6 |
public static void garbageDisposal() {
for (ArrayList orgs : organisms) {
for (int i = 0; i < orgs.size(); i++) {
Organism g = (Organism) orgs.get(i);
if (g.life.isDead()) {
g.life.kill();
orgs.remove(g);
i--;
}
}
}
} | 3 |
private void consoleCommands(String cmd){
if(cmd.equals("night"))
GameTime = 18000;
else if(cmd.equals("day"))
GameTime = 0;
else if(cmd.startsWith("need")){
String [] split = cmd.split("\\s+") ;
if(split.length == 3){
Item item = Items.getItemFromUIN(split[1]);
if(item != null){
ItemStack stack = new ItemStack(item, Integer.valueOf(split[2]));
player.setStackInNextAvailableSlot(stack);
}
}
}
consolePrint = "";
isConsoleDisplayed = false;
} | 5 |
public Parser(String in, Library lib) {
// init TOKENIZER
this.in = in;
read();
// init PARSER
this.lib=lib;
paramOPs=new Stack<OP>();
xchgOP=new Stack<OP>();
// initialize DV names accumulator
if (lib.resolver!=null)
accDV=new StringBuffer();
}; | 1 |
public String toCSV(){
return id+";"+date+";"+taille;
} | 0 |
public static void _drawHalfSphere(float r, int scalex, int scaley)
{
int i, j;
float[][] v = new float[scalex * scaley][3];
for (i = 0; i < scalex; ++i)
{
for (j = 0; j < scaley; ++j)
{
v[i * scaley + j][0] = r * (float) cos(j * 2 * PI / scaley) * (float) cos(i * PI / (2 * scalex));
v[i * scaley + j][1] = r * (float) sin(i * PI / (2 * scalex));
v[i * scaley + j][2] = r * (float) sin(j * 2 * PI / scaley) * (float) cos(i * PI / (2 * scalex));
}
}
gl.glBegin(GL2.GL_QUADS);
for (i = 0; i < scalex - 1; ++i)
{
for (j = 0; j < scaley; ++j)
{
gl.glNormal3fv(v[i * scaley + j], 0);
gl.glVertex3fv(v[i * scaley + j], 0);
gl.glNormal3fv(v[i * scaley + (j + 1) % scaley], 0);
gl.glVertex3fv(v[i * scaley + (j + 1) % scaley], 0);
gl.glNormal3fv(v[(i + 1) * scaley + (j + 1) % scaley], 0);
gl.glVertex3fv(v[(i + 1) * scaley + (j + 1) % scaley], 0);
gl.glNormal3fv(v[(i + 1) * scaley + j], 0);
gl.glVertex3fv(v[(i + 1) * scaley + j], 0);
}
}
gl.glEnd();
} | 4 |
@Override
public void handle(MouseEvent event) {
if (isSelected()) {
if (event.getButton() == MouseButton.PRIMARY) {
if (getGraphic() == null) {
for (ButtonEventHandler buttonEvent : buttonEventList) {
buttonEvent.onLeftClick(xPos, yPos);
buttonEvent.onFirstClick();
}
} else {
setSelected(false);
}
}
} else if (event.getButton() == MouseButton.SECONDARY) {
for (ButtonEventHandler buttonEvent : buttonEventList) {
buttonEvent.onRightClick(xPos, yPos);
}
} else if (event.getButton() != MouseButton.MIDDLE) {
setSelected(true);
}
event.consume();
} | 7 |
public static void incrementProgress(int progress) {
if (GlobalDialogs.progressDialogStatusBar != null) {
if (progress > 100 || GlobalDialogs.progressDialogStatusBar.getValue() + progress > 100) {
GlobalDialogs.progressDialogStatusBar.setValue(100);
} else {
GlobalDialogs.progressDialogStatusBar.setValue(GlobalDialogs.progressDialogStatusBar.getValue() + progress);
}
}
} | 3 |
public boolean getBoolean(int index) throws JSONException {
Object object = get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} | 6 |
public static void Close(Connection a,Statement b){
if(b != null){
try{
b.close();
}catch(SQLException e){}
}
if( a!= null){
try{
a.close();
}catch(SQLException e){}
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Card))
return false;
Card cobj = (Card) obj;
return card == cobj.card && x == cobj.x && y == cobj.y;
} | 3 |
@EventHandler(priority = EventPriority.HIGHEST)
public void chatEvent(final AsyncPlayerChatEvent event) {
// Don't care about event if it is cancelled
if(event.isCancelled() || event.getPlayer() == null) {
return;
}
if(event.getMessage().charAt(0) == '#') {
// Ignore, as we handled it earlier
return;
}
// Grab player
final Player player = event.getPlayer();
if(event.getPlayer().getWorld() == null) {
return;
}
// Get world name
final String worldName = event.getPlayer().getWorld().getName();
// Grab world specific config
final WorldConfig config = configHandler.getWorldConfig(worldName);
Channel channel = null;
ChannelManager manager = plugin.getModuleForClass(ChannelManager.class);
if(manager.getCurrentChannelId(player.getName()) != null) {
channel = manager.getChannel(manager.getCurrentChannelId(player
.getName()));
}
if(channel == null) {
// Grab default of the world
channel = config.getDefaultChannel();
}
handleChatEvent(event, config, channel);
} | 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.