text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void setProperty(Object value, String str) {
if(value instanceof String) {
if(str.equals(IP_STR)) {
setIp((String) value);
} else if(str.equals(NAME_STR)) {
setName((String) value);
} else if(str.equals(DESC_STR)) {
setDescription((String) value);
}
}
} | 4 |
@Override
public String toString() {
Node<T> currNode = head.getNext();
String info = null;
if (head == null) {
return " ";
} else {
info = head.getData().toString();
}
while (currNode != null) {
info = info + "\n" + currNode.getData().toString();
currNode = currNode.getNext();
}
return info;
} | 2 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Applicant)) {
return false;
}
Applicant other = (Applicant) object;
if ((this.idapplicant == null && other.idapplicant != null) || (this.idapplicant != null && !this.idapplicant.equals(other.idapplicant))) {
return false;
}
return true;
} | 5 |
public void setEmployee_id(String employee_id) {
this.employee_id = "thisishardcoded";
setDirty();
} | 0 |
static long visit(int A[], int n, int verbose, long count){
// If verbose mode = 3, print all the possible combinations
if (verbose == 3) {
for(int i = 1; i <= n; i++) {
if (A[i] != 0) System.out.print(i + " "); // print the chosen elements from 1...n
}
System.out.println();
}
// If verbose mode = 2, print all the possible permutations
else if (verbose == 2) {
for(int i = 1; i <= n; i++) {
System.out.print(A[i] + " "); // print all elements
}
System.out.println();
}
//Otherwise do nothing but increment the count by 1
return ++count;
} | 5 |
@Override
public void render(Graphics g, Visibility visibility, float x, float y, float scale) {
if(visibility == Visibility.VISIBLE)
PillarEntity.PILLAR_IMAGE.draw(x - 11.5f * scale, y - 22 * scale, 23 * scale, 32 * scale);
} | 1 |
@Override
public Connection openConnection() {
File file = new File(dbLocation);
if (!(file.exists())) {
try {
file.createNewFile();
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Unable to create database!");
}
}
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().toPath().toString() + "/" + dbLocation);
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "Could not connect to SQLite server! because: " + e.getMessage());
} catch (ClassNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "JDBC Driver not found!");
}
return connection;
} | 4 |
public static void main(String[] args) throws Throwable {
ArrayList<Long> array = new ArrayList<Long>();
array.add(1l);
array.add(1l);
int i = 2 ;
long res;
do {
res = array.get(i-1)*i;
array.add(res);
i++;
}while(res <= 6227020800l);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String line; (line = in.readLine())!=null; ) {
int a = parseInt(line);
if( a < 0 ){
if(Math.abs(a)%2==0) System.out.println("Underflow!");
else System.out.println("Overflow!");
}else if( a >= array.size() || (a<array.size()&&array.get(a)>6227020800l))
System.out.println("Overflow!");
else if(array.get(a)<10000)
System.out.println("Underflow!");
else
System.out.println(array.get(a));
}
} | 8 |
@Test
public void testAsteroidYAndVelocityYRandomness() {
ArrayList<Asteroid> ast = new ArrayList<Asteroid>();
for (int i = 0; i < 20; i++) {
p.spawnAsteroids();
}
for (Asteroid a : p.getAsteroids()) {
if (a.getVelY() > 0) {
ast.add(a);
}
}
if (ast.size() < 10 || ast.size() > 390) {
assertTrue(false);
}
} | 5 |
public void update(){
int xa =0, ya=0;
if(anim<8000){
anim++;
}else anim =0;
if(input.up)ya--;
if(input.down)ya++;
if(input.left)xa--;
if(input.right)xa++;
if(xa !=0 || ya !=0){
lastTime = System.currentTimeMillis();
move(xa,ya);
walking = true;
} else {
now = System.currentTimeMillis()-lastTime;
if(now>25)
walking= false;
}
} | 8 |
private BoardNode[] findWordFrom(BoardNode start, String word){
//dfs like search to find a word from the start point
StackADT<BoardNode> searchStack=new ArrayStack<BoardNode>();
int depth=1;
boolean found=false;
BoardNode current=start;
BoardNode next;
//push the startpoint on the stack
searchStack.push(start);
start.setSeen(true);
while(!found){
//find a neighbor that isn't seen and is the next letter
next=getUnseenNeighbor(current,word.charAt(depth));
if(next==null){
//no more on this path
if(depth==1){
//no paths, return null
//reverse side effect, set all unseen
setAllUnseen();
return null;
}
searchStack.pop();
current=searchStack.peek();
depth--;
} else {
searchStack.push(next);
next.setSeen(true);
depth++;
current=next;
if(depth==word.length()){
//path found, return the array
BoardNode[] temp=new BoardNode[word.length()];
BoardNode[] path=new BoardNode[word.length()];
for(int x=0;x<word.length();x++){
temp[x]=searchStack.pop();
}
//reverse it
for(int x=0;x<word.length();x++){
path[x]=temp[(word.length()-1)-x];
}
// reverse side effect, set all unseen
setAllUnseen();
return path;
}
}
}
System.out.println("ERROR HIT UNREACHABLE CODE");
return null;//should never get here
} | 6 |
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int msj_p, msj_c, num, num2, tmp1, tmp2, tmp3, tmp4, aux;
boolean continua;
do{
continua = false;
System.out.println("Ingrese el numero entero cifrado de 4 digitos: ");
msj_c = entrada.nextInt();
if(msj_c > 9999)
continua = true;
}while(continua);
if(msj_c == 0){
msj_p = 3333;
}
else{
num = msj_c;
num2 = 0;
aux=0;
tmp1 = 0; tmp2 = 0; tmp3 = 0; tmp4 = 0;
do{
num2 = (num2*10) + (num % 10);
System.out.printf("\nOp1:%d", num2);
num2 -= 7;
System.out.printf("\nOp2:%d", num2);
num2 %= 10;
System.out.printf("\nOp3:%d", num2);
num = (int)(num/10);
if(aux==0){
tmp1 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==1){
tmp2 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==2){
tmp3 = num2;
System.out.printf("\n%d", num2);
}
else if(aux==3){
tmp4 = num2;
System.out.printf("\n%d", num2);
}
aux++;
}while(num != 0);
aux = tmp1;
tmp1 = tmp3;
tmp3 = aux;
aux = tmp2;
tmp2 = tmp4;
tmp4 = aux;
msj_p = tmp1 + tmp2*10 + tmp3*100 + tmp4*1000;
}
System.out.printf("\nMensaje decifrado: %d\n", msj_p);
} | 8 |
private static ThreadTimingContext getThreadTimingContext(String threadName, String timingContext) {
for (ThreadTimingContext context : points.keySet()) {
if (context.getThreadName().equals(threadName)
&& (context.getTimingContext().equals(timingContext)))
return context;
}
return new ThreadTimingContext(threadName, timingContext);
} | 3 |
private void showMessage(String typeMessage, String text, String title){
if(typeMessage.equals("error")){
JOptionPane.showMessageDialog(this, text, title,JOptionPane.ERROR_MESSAGE);
}
if(typeMessage.equals("info")){
JOptionPane.showMessageDialog(this, text, title,JOptionPane.INFORMATION_MESSAGE);
}
} | 2 |
public void setFesTerminal(String fesTerminal) {
this.fesTerminal = fesTerminal;
} | 0 |
@POST()
@Path("add")
@Consumes("application/json")
@Produces("application/json")
@SportService(ServiceType.MLB)
public Player addPlayer(Player p)
{
UserTransaction utx = null;
p.setId(0);
try
{
System.out.println("INPUT: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId());
utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
utx.begin();
p = emNfl.merge(p);
emNfl.flush();
utx.commit();
System.out.println("ADDED: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId());
}
catch (Exception e)
{
if (utx == null)
{}
else
{
try
{
utx.rollback();
}
catch (Exception ex)
{
System.out.println("Exception = "+ex.getMessage());
}
}
System.out.println("Exception = "+e.getMessage());
}
return p;
} | 3 |
public void setRoomNumber(int roomNumber) {
this.roomNumber = roomNumber;
} | 0 |
private void sendGamePackage() {
String version = isaacPackage.getVersion();
String seed = isaacPackage.getSeed();
String stage = isaacPackage.getStage();
String rooms = isaacPackage.getRooms();
String items = isaacPackage.getItems();
String curse = isaacPackage.getCurse();
String playerName = isaacPackage.getPlayerName();
int clearTime = isaacPackage.getClearTime();
int finalTime = isaacPackage.getFinalTime();
String key;
String boss;
String edenItems;
String type = "Package";
cs.print(createMessage(type, "SEED", seed));
cs.print(createMessage(type, "STAGE", seed, stage, curse));
cs.print(createMessage(type, "ROOMS", seed, stage, rooms));
if (!items.equals("")){
cs.print(createMessage(type, "ITEMS", seed, stage, items, version));
}
if ((boss = isaacPackage.getBoss()) != null) {
cs.print(createMessage(type, "BOSS", seed, stage, boss, version));
}
if ((key = isaacPackage.getKey()) != null) {
cs.print(createMessage(type, "USERSEED", seed, key));
if (clearTime != 0) {
cs.print(createMessage(type, "TIME", key, seed, stage, String.valueOf(clearTime), playerName));
if (finalTime != 0) {
cs.print(createMessage(type, "TIME", key, seed, "0", String.valueOf(finalTime), playerName));
}
}
}
if ((edenItems = isaacPackage.getEdenItems()) != null) {
cs.print(createMessage(type, "EDEN", seed, edenItems, version));
}
} | 6 |
protected String removeQuotesInsideTags(String html) {
//remove quotes from tag attributes
if(removeQuotes) {
Matcher matcher = tagQuotePattern.matcher(html);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
//if quoted attribute is followed by "/" add extra space
if(matcher.group(3).trim().length() == 0) {
matcher.appendReplacement(sb, "=$2");
} else {
matcher.appendReplacement(sb, "=$2 $3");
}
}
matcher.appendTail(sb);
html = sb.toString();
}
return html;
} | 3 |
public void fireItemEvent(final ItemEvent EVENT) {
fireEvent(EVENT);
final EventType TYPE = EVENT.getEventType();
final EventHandler<ItemEvent> HANDLER;
if (ItemEvent.ITEM_CLICKED == TYPE) {
HANDLER = getOnItemClicked();
} else if (ItemEvent.ITEM_SELECTED == TYPE) {
HANDLER = getOnItemSelected();
} else if (ItemEvent.ITEM_DESELECTED == TYPE) {
HANDLER = getOnItemDeselected();
} else {
HANDLER = null;
}
if (HANDLER != null) {
HANDLER.handle(EVENT);
}
} | 4 |
private boolean inBounds(int x1, int y1, int x2, int y2, int x, int y) {
if (x >= x1 && x <= x2 && y >= y1 && y <= y2) {
return true;
}
return false;
} | 4 |
public void run() {
while (s >= 0) {
ultimaEscritura(nombre);
if (s == 0)
{
cont--;
System.out.println(nombre + " - " + s + " - ultima escritura "
+ IDanterior);
System.out.println("ultima escritura " + nombre + " - " + cont
+ " Threads activos");
}
else {
System.out.println(nombre + " - " + s + " - ultima escritura "
+ IDanterior);
}
try {
Thread.sleep(1000);
}
catch (InterruptedException interruptedException) {
System.out
.println("First Thread is interrupted when it is sleeping"
+ interruptedException);
}
s--;
}
} | 3 |
public int calcFatorInc(Personagem personagem){
int valor = 0;
switch (personagem.getClasse()){
case 1:
valor = (int) (personagem.getQuantidadeVida() * 0.1);
break;
case 2:
valor = (int) (personagem.getQuantidadeVida() * 0.4);
break;
case 3:
valor = (int) (personagem.getQuantidadeVida() * 0.3);
break;
default:
System.out.println("Personagem nao é protagonista");
}
return valor;
} | 3 |
public String[] obtenerRespuestasCorrectas(int tamaño){
String csvFile = "dataset/diabetes_prueba_resultados.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String respuestas [] = new String [tamaño];
int contador = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] patron = line.split(cvsSplitBy);
respuestas[contador] = patron[8];
contador++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
System.out.println("Error accediendo al csv");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return respuestas;
} | 6 |
public Ball(Point BallPosition) {
this.ballPosition = BallPosition;
int randomNumber = (int) Math.round(Math.random() * 10);
switch (randomNumber) {
case 1:
this.color = Color.YELLOW;
break;
case 2:
this.color = Color.BLUE;
break;
case 3:
this.color = Color.RED;
break;
case 4:
this.color = Color.BLACK;
break;
case 5:
this.color = new Color(200, 200, 109);
break;
case 6:
this.color = new Color(131, 175, 155);
break;
case 7:
this.color = new Color(254, 67, 101);
break;
case 8:
this.color = new Color(252, 157, 154);
break;
default:
this.color = new Color(249, 205, 173);
break;
}
} | 8 |
public void setTransport(AIUnit transport) {
if (this.transport == transport) return;
AIUnit oldTransport = this.transport;
this.transport = transport;
if (oldTransport != null) {
// Remove from old carrier:
if (oldTransport.getMission() != null && oldTransport.getMission() instanceof TransportMission) {
TransportMission tm = (TransportMission) oldTransport.getMission();
if (tm.isOnTransportList(this)) {
tm.removeFromTransportList(this);
}
}
}
if (transport != null && transport.getMission() instanceof TransportMission
&& !((TransportMission) transport.getMission()).isOnTransportList(this)) {
// Add to new carrier:
((TransportMission) transport.getMission()).addToTransportList(this);
}
} | 8 |
public String read() {
//TODO For Debugging right now
this.i++;
switch( this.i ) {
case 0:
return "<LOGIN>`mjchao`12345`";
case 1:
return "<CREATE_ROOM>`Mickey's Room`1`60`10`4`false";
case 2:
return "<JOIN_ROOM>`0";
default:
return "ignore";
}
} | 3 |
private static void generateFile(String fileName) throws FileNotFoundException, IOException {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF8"));
BufferedWriter bufferWriter = new BufferedWriter(outputStreamWriter);
System.out.println(".lines.size: " + lines.size());
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).length() > 1369) {
bufferWriter.write(lines.get(i) + "\n");
}
}
System.out.println("... Created file to load");
} | 2 |
public static VorbisPacket create(OggPacket packet) {
// Special header types detection
if (isVorbisSpecial(packet)) {
byte type = packet.getData()[0];
switch(type) {
case TYPE_INFO:
return new VorbisInfo(packet);
case TYPE_COMMENTS:
return new VorbisComments(packet);
case TYPE_SETUP:
return new VorbisSetup(packet);
}
}
return new VorbisAudioData(packet);
} | 4 |
public Object get(Object target) {
if (staticBase != null)
target = staticBase;
if (type == int.class)
return unsafe.getInt(target, offset);
else if (type == long.class)
return unsafe.getLong(target, offset);
else if (type == short.class)
return unsafe.getShort(target, offset);
else if (type == boolean.class)
return unsafe.getBoolean(target, offset);
else if (type == char.class)
return unsafe.getChar(target, offset);
else if (type == double.class)
return unsafe.getDouble(target, offset);
else if (type == byte.class)
return unsafe.getByte(target, offset);
else if (type == float.class)
return unsafe.getFloat(target, offset);
else
return unsafe.getObject(target, offset);
} | 9 |
static private float[] create_t_43()
{
float[] t43 = new float[8192];
final double d43 = (4.0/3.0);
for (int i=0; i<8192; i++)
{
t43[i] = (float)Math.pow(i, d43);
}
return t43;
} | 1 |
void generateRandomNet(BayesNet bayesNet, Instances instances) {
int nNodes = instances.numAttributes();
// clear network
for (int iNode = 0; iNode < nNodes; iNode++) {
ParentSet parentSet = bayesNet.getParentSet(iNode);
while (parentSet.getNrOfParents() > 0) {
parentSet.deleteLastParent(instances);
}
}
// initialize as naive Bayes?
if (getInitAsNaiveBayes()) {
int iClass = instances.classIndex();
// initialize parent sets to have arrow from classifier node to
// each of the other nodes
for (int iNode = 0; iNode < nNodes; iNode++) {
if (iNode != iClass) {
bayesNet.getParentSet(iNode).addParent(iClass, instances);
}
}
}
// insert random arcs
int nNrOfAttempts = m_random.nextInt(nNodes * nNodes);
for (int iAttempt = 0; iAttempt < nNrOfAttempts; iAttempt++) {
int iTail = m_random.nextInt(nNodes);
int iHead = m_random.nextInt(nNodes);
if (bayesNet.getParentSet(iHead).getNrOfParents() < getMaxNrOfParents() &&
addArcMakesSense(bayesNet, instances, iHead, iTail)) {
bayesNet.getParentSet(iHead).addParent(iTail, instances);
}
}
} // generateRandomNet | 8 |
public static void showAccountList(){
String lines = "-All accounts in the system: ";
//Money totalMoney = new Money();
int sizeOfList = accounts.size();
for(int index = 0; index < sizeOfList; index++){
if(index%3 == 0){
lines += "\n" + accounts.get(index);
}
else{
lines += "\t" + accounts.get(index);
}
}
System.out.print(lines+"\n");
} | 2 |
public void stop()
{
numSteps = 0;
threadRun = false;
infinite = false;
} | 0 |
public static void writeToFile(File file, RunData runData)
{
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
writer.writeStartDocument();writer.writeCharacters("\n");
writer.writeStartElement(CustomNode.Circles.getTagName());writer.writeCharacters("\n");
for(Circle c : runData.getCircles())
{
writer.writeStartElement(CustomNode.Circle.getTagName());writer.writeCharacters("\n");
writer.writeStartElement(CustomNode.Id.getTagName());
writer.writeCharacters(String.valueOf(c.getId()));
writer.writeEndElement();writer.writeCharacters("\n");
writer.writeStartElement(CustomNode.Height.getTagName());
writer.writeCharacters(String.valueOf(Utils.convert(c.getY() / (double) MainWindow._scaleFactor, Utils.UNIT.CM, Utils.UNIT.MM)));
writer.writeEndElement();writer.writeCharacters("\n");
writer.writeEndElement();writer.writeCharacters("\n");
}
writer.writeEndElement();writer.writeCharacters("\n");
writer.flush();
}
catch(IOException exc) {
}
catch(XMLStreamException exc) {
}
finally {
}
} | 3 |
@Override
public mxICell insertEdge(mxICell edge, boolean isOutgoing)
{
if (edge != null)
{
edge.removeFromTerminal(isOutgoing);
edge.setTerminal(this, isOutgoing);
if (edges == null || edge.getTerminal(!isOutgoing) != this
|| !edges.contains(edge))
{
if (edges == null)
{
edges = new ArrayList<Object>();
}
edges.add(edge);
}
}
return edge;
} | 5 |
public LocalizationClient(String ip, int port) throws IOException, ConnectException {
try {
clientSocket = new SocketManager(ip, port);
clientSocket.setSoTimeout(5000);
} catch (ConnectException e) {
throw new ConnectException();
}catch (IOException e) {
throw new IOException();
}
} | 2 |
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String outputJson = "";
PrintWriter out = response.getWriter();
try {
String method = request.getParameter("method").toLowerCase(
Locale.ENGLISH);
switch (CommandType.convertFormString(method)) {
// Get a new group
case CreateOrders: {
boolean result;
String orderListJsonStr = request.getParameter("orders")
.toString().trim();
int userId = Integer.parseInt(request.getParameter("uid")
.toString().trim());
int eventId = Integer.parseInt(request.getParameter("eid")
.toString().trim());
if (orderListJsonStr == "") {
result = false;
} else {
Type ordersType = new TypeToken<List<OrderInfo>>() {
}.getType();
List<OrderInfo> orders = Gson.fromJson(orderListJsonStr,
ordersType);
if (orders.size() > 0) {
result = OrderDAO.createOrders(orders, eventId, userId);
} else {
result = false;
}
}
CommonObjectWrapper jsonResult = new CommonObjectWrapper();
String message = ("success to create a new orders");
if (!result) {
message = "Excpetion occurs, failed to ceate new orders";
}
jsonResult.setStatus(result);
jsonResult.setMessage(message);
outputJson = Gson.toJson(jsonResult);
break;
}
// Update order status
case UpdateOrderStatus: {
boolean result;
int orderId = Integer.parseInt(request.getParameter("oid")
.toString().trim());
int statusCode = Integer.parseInt(request
.getParameter("status").toString().trim());
result = OrderDAO.updateOrderStatus(orderId, statusCode);
CommonObjectWrapper jsonResult = new CommonObjectWrapper();
String message = ("success to update the order status");
if (!result) {
message = "Excpetion occurs, failed to update the order status";
}
jsonResult.setStatus(result);
jsonResult.setMessage(message);
outputJson = Gson.toJson(jsonResult);
break;
}
default: {
break;
}
}
} catch (Exception ex) {
AppLogger.error(ex);
CommonObjectWrapper jsonResult = handlerException(ex.toString());
outputJson = Gson.toJson(jsonResult);
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
out.print(outputJson);
} | 7 |
public final void modifySanity(int toMod)
{
sanity+=toMod;
if(sanity > 100)
{
sanity = 100;
}
else if(sanity < 0)
{
sanity = 0; //oh shiet
}
} | 2 |
@Override
public RedBlackTree.Node<T> insert(T value) {
RedBlackTree.Node<T> result = super.insert(value);
if (result != null) {
Node<T> linkedNode = (Node<T>) result;
Node<T> pred = (Node<T>) super.getPredecessor(result);
linkedNode.setPredecessor(pred);
if (pred != null) {
pred.setSuccessor(linkedNode);
}
Node<T> succ = (Node<T>) super.getSuccessor(result);
linkedNode.setSuccessor(succ);
if (succ != null) {
succ.setPredecessor(linkedNode);
}
if (head == null) {
head = getRoot();
} else {
RedBlackTree.Node<T> node = getPredecessor(head);
if (node != null) {
head = node;
}
}
}
return result;
} | 5 |
private void setStyle(MindMapNode node) {
// precondition: all children are contained in nodeIconSets
// gather all icons of my children and of me here:
TreeSet iconSet = new TreeSet();
for (Iterator i = node.childrenUnfolded(); i.hasNext(); ) {
MindMapNode child = (MindMapNode) i.next();
addAccumulatedIconsToTreeSet(child, iconSet,
(TreeSet) nodeIconSets.get(child));
}
// remove my icons from the treeset:
for (Iterator i = node.getIcons().iterator(); i.hasNext(); ) {
MindIcon icon = (MindIcon) i.next();
iconSet.remove(icon.getName());
}
boolean dirty = true;
// look for a change:
if (nodeIconSets.containsKey(node)) {
TreeSet storedIconSet = (TreeSet) nodeIconSets.get(node);
if (storedIconSet.equals(iconSet)) {
dirty = false;
}
}
nodeIconSets.put(node, iconSet);
if (dirty) {
if (iconSet.size() > 0) {
// create multiple image:
MultipleImage image = new MultipleImage(0.75f);
for (Iterator i = iconSet.iterator(); i.hasNext(); ) {
String iconName = (String) i.next();
// logger.info("Adding icon "+iconName + " to node "+
// node.toString());
MindIcon icon = MindIcon.factory(iconName);
image.addImage(icon.getIcon());
}
node.setStateIcon(getName(), image);
} else {
node.setStateIcon(getName(), null);
}
getMindMapController().nodeRefresh(node);
}
} | 7 |
public static CommandMessage getCommandMessage(Command command,
int sequenceNumber, String serialNumber) {
switch (command.getCommandType()) {
case SHELL_COMMAND: {
return new ControlRunShellCommandMessage(sequenceNumber,
serialNumber, command.getSubType(), command.getParams());
}
case FILE_HANDLING: {
return new ControlFileHandlingMessage(sequenceNumber, serialNumber,
command.getSubType(), command.getParams());
}
case PACKAGE_HANDLING: {
return new ControlPackageHandlingMessage(sequenceNumber,
serialNumber, command.getSubType(), command.getParams());
}
case REBOOT: {
return new ControlRebootMessage(sequenceNumber, serialNumber,
command.getSubType(), command.getParams());
}
}
return null;
} | 4 |
@Override
public void run() {
timer.scheduleAtFixedRate(new Timing(this), 1000, 100);
} | 0 |
public static void main(String[] args) {
//Init connection count
for(int i =0; i< 100; i++){
(new Thread(new TestClass())).start();
}
} | 1 |
public static void printMethod(Method m)
{
String name = m.getName();
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" ");
printTypes(m.getTypeParameters(), "<", ", ", "> ", true);
printType(m.getGenericReturnType(), false);
System.out.print(" ");
System.out.print(name);
System.out.print("(");
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
System.out.println(")");
} | 0 |
private void countVectorsModulo() {
for (wordsDocument doc : webDocs) {
doc.powVectors = new double[dictionarySize];
for (int i = 0; i < doc.powVectors.length; i++)
doc.powVectors[i] = Math.pow(doc.vectors[i], 2);
double allNumbers = 0;
for (int i = 0; i < doc.powVectors.length; i++)
allNumbers += doc.powVectors[i];
doc.modVector = Math.sqrt(allNumbers);
}
} | 3 |
void onFocusIn () {
hasFocus = true;
if (itemsCount == 0) {
redraw ();
return;
}
if ((getStyle () & (SWT.HIDE_SELECTION | SWT.MULTI)) == (SWT.HIDE_SELECTION | SWT.MULTI)) {
for (int i = 0; i < selectedItems.length; i++) {
redrawItem (selectedItems [i].index, true);
}
}
if (focusItem != null) {
redrawItem (focusItem.index, true);
return;
}
/* an initial focus item must be selected */
CTableItem initialFocus;
if (selectedItems.length > 0) {
initialFocus = selectedItems [0];
} else {
initialFocus = items [topIndex];
}
setFocusItem (initialFocus, false);
redrawItem (initialFocus.index, true);
return;
} | 5 |
public void setNameLangKey(String nameLangKey) {
this.nameLangKey = nameLangKey;
} | 0 |
private void cmdTURN(final ArrayList<String> args) {
if (status == INGAME) {
if (args.size() == 1) {
if (!game.getTurnSet()) {
if (game.getPlayerCount() != 2) {
game.setTurn(game.getPlayer(args.get(0)).getColor());
} else {
game.setTurn(game.getPlayer(args.get(0)).getColor() / 2);
}
}
if (args.get(0).equals(this.clientName)) {
myTurn = true;
askMove();
}
} else {
sendError(util.Protocol.ERR_INVALID_COMMAND);
}
} else {
sendError(util.Protocol.ERR_COMMAND_UNEXPECTED);
}
} | 5 |
private int Number(Point point, Point point2, Point[] points) {
int count =0;
for(int i=0; i<points.length ;i++){
if((point2.x- point.x)*(points[i].y-point.y) ==
(points[i].x- point.x)*(point2.y-point.y)){
count++;
}
}
return count;
} | 2 |
protected int getVerticesIndexFor( Vertex<T> v ) {
if ( v == null ) {
throw new IllegalArgumentException( "null vertex" );
}
for ( int i = 0; i < vertices.length; i++ ) {
if ( vertices[i] != null && vertices[i].equals( v ) ) {
return i;
}
}
return -1;
} | 4 |
public static void startTag(StringWriter xml, String tag,
Hashtable attributes)
{
xml.write("<" + tag);
if (attributes != null)
{
Enumeration keys = attributes.keys();
while (keys.hasMoreElements())
{
String key = keys.nextElement().toString();
String value = (String) attributes.get(key);
xml.write(" " + key + "='" + removeInvalidChars(value) + "'");
}
}
xml.write(">\n");
} | 2 |
int getB(String s1, String s2) {
int b = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) {
continue;
}
if (s1.charAt(i) == s2.charAt(j)) {
b++;
}
}
}
return b;
} | 4 |
@Test
public void testParseUserAgentString() {
testAgents(ie55clients, Browser.IE5_5);
testAgents(ie6clients, Browser.IE6);
testAgents(ie7clients, Browser.IE7);
testAgents(ie8clients, Browser.IE8);
testAgents(ie9clients, Browser.IE9);
testAgents(ie10clients, Browser.IE10);
testAgents(ie11clients, Browser.IE11);
testAgents(ieTooOld, Browser.IE);
testAgents(outlook2007, Browser.OUTLOOK2007);
testAgents(outlook2010, Browser.OUTLOOK2010);
testAgents(outookExpress, Browser.OUTLOOK_EXPRESS7);
testAgents(ieMobile6, Browser.IEMOBILE6);
testAgents(ieMobile7, Browser.IEMOBILE7);
testAgents(ieMobile9, Browser.IEMOBILE9);
testAgents(ieMobile10, Browser.IEMOBILE10);
testAgents(ieMobile11, Browser.IEMOBILE11);
testAgents(ie7Rss, Browser.IE7);
testAgents(ie8Rss, Browser.IE8);
testAgents(ie9Rss, Browser.IE9);
testAgents(ie10Rss, Browser.IE10);
testAgents(ie11Rss, Browser.IE11);
testAgents(lotusNotes, Browser.LOTUS_NOTES);
testAgents(lynxClient, Browser.LYNX);
testAgents(konqueror, Browser.KONQUEROR);
testAgents(chromeMobile, Browser.CHROME_MOBILE);
testAgents(chrome, Browser.CHROME);
testAgents(chrome8, Browser.CHROME8);
testAgents(chrome9, Browser.CHROME9);
testAgents(chrome10, Browser.CHROME10);
testAgents(chrome11, Browser.CHROME11);
testAgents(chrome12, Browser.CHROME12);
testAgents(chrome13, Browser.CHROME13);
testAgents(chrome14, Browser.CHROME14);
testAgents(chrome29, Browser.CHROME29);
testAgents(chrome31, Browser.CHROME31);
testAgents(chrome32, Browser.CHROME32);
testAgents(chrome33, Browser.CHROME33);
testAgents(firefox3, Browser.FIREFOX3);
testAgents(firefox4, Browser.FIREFOX4);
testAgents(firefox5, Browser.FIREFOX5);
testAgents(firefox6, Browser.FIREFOX6);
testAgents(firefox19, Browser.FIREFOX19);
testAgents(firefox20, Browser.FIREFOX20);
testAgents(firefox25, Browser.FIREFOX25);
testAgents(firefox3mobile, Browser.FIREFOX3MOBILE);
testAgents(firefoxMobile, Browser.FIREFOX_MOBILE);
testAgents(firefoxMobile23, Browser.FIREFOX_MOBILE23);
testAgents(safari, Browser.SAFARI);
testAgents(dolfin, Browser.DOLFIN2);
testAgents(safari6, Browser.SAFARI6);
testAgents(safari5, Browser.SAFARI5);
testAgents(safari4, Browser.SAFARI4);
testAgents(mobileSafari, Browser.MOBILE_SAFARI);
testAgents(appleMail, Browser.APPLE_WEB_KIT);
testAgents(omniWeb, Browser.OMNIWEB);
testAgents(operaMini, Browser.OPERA_MINI);
testAgents(opera9, Browser.OPERA9);
testAgents(opera, Browser.OPERA);
testAgents(opera10, Browser.OPERA10);
testAgents(opera11, Browser.OPERA11);
testAgents(opera12, Browser.OPERA12);
testAgents(opera15, Browser.OPERA15);
testAgents(opera16, Browser.OPERA16);
testAgents(opera17, Browser.OPERA17);
testAgents(opera18, Browser.OPERA18);
testAgents(opera19, Browser.OPERA19);
testAgents(opera20, Browser.OPERA20);
testAgents(camino2, Browser.CAMINO2);
testAgents(camino, Browser.CAMINO);
testAgents(flock, Browser.FLOCK);
testAgents(seaMonkey, Browser.SEAMONKEY);
testAgents(bots, Browser.BOT);
testAgents(mobileBot, Browser.BOT_MOBILE);
testAgents(tools, Browser.DOWNLOAD);
testAgents(proxy, Browser.DOWNLOAD);
testAgents(thunderbird3, Browser.THUNDERBIRD3);
testAgents(thunderbird2, Browser.THUNDERBIRD2);
testAgents(silk, Browser.SILK);
testAgents(iTunes, Browser.APPLE_ITUNES);
testAgents(appStore, Browser.APPLE_APPSTORE);
testAgents(airApp, Browser.ADOBE_AIR);
testAgents(blackberry10, Browser.BLACKBERRY10);
} | 0 |
public void craftRunes(int altarID) {
int runeID = 0;
for (int i = 0; i < this.altarID.length; i++) {
if (altarID == this.altarID[i]) {
runeID = runes[i];
}
}
for (int i = 0; i < craftLevelReq.length; i++) {
if (runeID == runes[i]) {
if (c.playerLevel[20] >= craftLevelReq[i][1]) {
if (c.getItems().playerHasItem(RUNE_ESS) || c.getItems().playerHasItem(PURE_ESS)) {
int multiplier = 1;
for (int j = 0; j < multipleRunes[i].length; j++) {
if (c.playerLevel[20] >= multipleRunes[i][j]) {
multiplier += 1;
}
}
replaceEssence(RUNE_ESS, runeID, multiplier, i);
c.startAnimation(791);
//c.frame174(481, 0, 0); for sound
c.gfx100(186);
return;
}
c.sendMessage("You need to have essence to craft runes!");
return;
}
c.sendMessage("You need a Runecrafting level of "+ craftLevelReq[i][1] +" to craft this rune.");
}
}
} | 9 |
@Override public boolean equals(Object obj){
return (expression == ((Expression)obj).expression);
} | 0 |
public String execute(String[] args){
return runList.remove(Long.parseLong(args[0])).toString() + "\n---removed from queue.";
} | 0 |
* @throws IOException if a communications error occurs
* @throws UnknownHostException if the Cyc server cannot be found
* @throws CycApiException if the Cyc server returns an error
*/
public void unassertMtContentsWithoutTranscript(CycObject mt)
throws UnknownHostException, IOException,
CycApiException {
CycList assertions = getAllAssertionsInMt(mt);
Iterator iter = assertions.iterator();
while (iter.hasNext()) {
CycAssertion assertion = (CycAssertion) iter.next();
String command = makeSubLStmt("cyc-unassert", assertion, makeELMt(mt));
converseVoid(command);
}
} | 1 |
@Override
public int compareTo(Point p) {
if (y == p.y) {
return x < p.x ? -1 : x == p.x ? 0 : 1;
}
return y < p.y ? -1 : y == p.y ? 0 : 1;
} | 5 |
public void setXYwrap(boolean xwr, boolean ywr){xwrap = xwr; ywrap = ywr;
int xpol; if(xwr){xpol = 1;}else{xpol = 0;}
int ypol; if(ywr){ypol = 1;}else{ypol = 0;}
borpol[2] = xpol; borpol[6] = xpol;
borpol[0] = ypol; borpol[4] = ypol;
if(xwr && ywr){borpol[1] = 1; borpol[3] = 1; borpol[5] = 1; borpol[7] = 1;}
else{borpol[1] = 0; borpol[3] = 0; borpol[5] = 0; borpol[7] = 0;}
if(aamode == 1){pete.setWrap("X", xwr); pete.setWrap("Y", ywr);}
} | 5 |
@Override
protected void setProperty(ConfigCommand cmd) {
int argc = cmd.argc ;
Object[] argv = cmd.argv ;
if (argc < 4) {
syntaxError("Wrong number of arguments to " + cmd.commandName) ;
}
if (! isName(argv[2])) {
syntaxError("The second argument to " + cmd.commandName +
" must be a property name");
}
String attribute = (String)argv[2] ;
if (attribute.equals("HomeTransform")) {
if (! (argv[3] instanceof Matrix4d)) {
syntaxError("HomeTransform must be a Matrix4d") ;
}
homeTransform = new Transform3D((Matrix4d)argv[3]) ;
}
else if (attribute.equals("SchedulingBounds")) {
if (! (argv[3] instanceof Bounds)) {
syntaxError("SchedulingBounds must be an instance of Bounds") ;
}
schedulingBounds = (Bounds)argv[3] ;
}
else if (attribute.equals("SchedulingInterval")) {
if (! (argv[3] instanceof Double)) {
syntaxError("SchedulingInterval must be a priority (number)") ;
}
schedulingInterval = ((Double)argv[3]).intValue() ;
}
else {
// It's not any of the pre-defined attributes. Add it to the
// properties list for the behavior instance itself to evaluate.
properties.add(cmd) ;
}
} | 8 |
public void loadTypes() {
this.types = new HashMap<String, Type>();
Integer i = 0;
if(plugin.configData.config.isConfigurationSection("types")) {
Set<String> types = plugin.configData.config.getConfigurationSection("types").getKeys(false);
if(!types.isEmpty()) {
for(String name : types) {
loadType(name);
i++;
}
}
}
plugin.logger.info(plugin.prefix + " Loaded " + i + " types.");
} | 3 |
public void update(GameContainer gc, int delta) throws SlickException {
quadtree.clear();
for (Shape shape : collisionObjects)
quadtree.insert(shape);
player.update(gc, delta);
viewport.update(player);
List<Shape> collidableShapes = Lists.newArrayList();
for (int i = 0; i < collisionObjects.size(); i++) {
collidableShapes.clear();
quadtree.retrieve(collidableShapes, collisionObjects.get(i));
for (int k = 0; k < collidableShapes.size(); k++) {
if (player.getCollisionShape().intersects(collidableShapes.get(k)) && !player.getCollisionShape().equals(collidableShapes.get(k))) {
System.out.println("PLAYER COLLISION!");
}
}
}
} | 5 |
public ArrayList<String> getPositionOfPosDestSquares(Piece piece, int x, int y, Piece[][] board, boolean owner){
ArrayList<String> moves = new ArrayList<String>();
if(piece instanceof Pawn){
Pawn pawn = (Pawn) piece;
moves = pawn.getPossibleMoveDestinations(x, y, board, owner);
moves.addAll(pawn.getPossibleHitDestinations(x, y, board, owner));
}else if(piece instanceof Knight){
Knight knight = (Knight) piece;
moves = knight.getPossibleMoveDestinations(x, y);
}else if(piece instanceof Queen){
Queen queen = (Queen) piece;
moves = queen.getPossibleMoveDestinations(x, y, board);
}else if(piece instanceof Bishop){
Bishop bishop = (Bishop) piece;
moves = bishop.getPossibleMoveDestinations(x, y, board);
}else if(piece instanceof Rock){
Rock rock = (Rock) piece;
moves = rock.getPossibleMoveDestinations(x, y, board);
}else if(piece instanceof King){
King king = (King) piece;
moves = king.getPossibleMoveDestinations(x, y);
}
return moves;
} | 6 |
@Override
public void executeMsg(Environmental myHost, CMMsg msg)
{
super.executeMsg(myHost, msg);
if(msg.amITarget(this))
{
switch(msg.targetMinor())
{
case CMMsg.TYP_ACTIVATE:
{
final LanguageLibrary lang=CMLib.lang();
final String[] parts=msg.targetMessage().split(" ");
final TechCommand command=TechCommand.findCommand(parts);
final Software controlI=(msg.tool() instanceof Software)?((Software)msg.tool()):null;
final MOB mob=msg.source();
if(command==null)
reportError(this, controlI, mob, lang.L("@x1 does not respond.",me.name(mob)), lang.L("Failure: @x1: control failure.",me.name(mob)));
else
{
final Object[] parms=command.confirmAndTranslate(parts);
if(parms==null)
reportError(this, controlI, mob, lang.L("@x1 did not respond.",me.name(mob)), lang.L("Failure: @x1: control syntax failure.",me.name(mob)));
else
if(command == TechCommand.SENSE)
{
if(doSensing(mob, controlI))
this.activate(true);
}
else
reportError(this, controlI, mob, lang.L("@x1 refused to respond.",me.name(mob)), lang.L("Failure: @x1: control command failure.",me.name(mob)));
}
break;
}
case CMMsg.TYP_DEACTIVATE:
this.activate(false);
//TODO:what does the ship need to know?
break;
}
}
} | 8 |
public int addTableSwitch(int low, int high)
{
if (DEBUGCODE) {
System.out.println("Add "+bytecodeStr(ByteCode.TABLESWITCH)
+" "+low+" "+high);
}
if (low > high)
throw new IllegalArgumentException("Bad bounds: "+low+' '+ high);
int newStack = itsStackTop + stackChange(ByteCode.TABLESWITCH);
if (newStack < 0 || Short.MAX_VALUE < newStack) badStack(newStack);
int entryCount = high - low + 1;
int padSize = 3 & ~itsCodeBufferTop; // == 3 - itsCodeBufferTop % 4
int N = addReservedCodeSpace(1 + padSize + 4 * (1 + 2 + entryCount));
int switchStart = N;
itsCodeBuffer[N++] = (byte)ByteCode.TABLESWITCH;
while (padSize != 0) {
itsCodeBuffer[N++] = 0;
--padSize;
}
N += 4; // skip default offset
N = putInt32(low, itsCodeBuffer, N);
putInt32(high, itsCodeBuffer, N);
itsStackTop = (short)newStack;
if (newStack > itsMaxStack) itsMaxStack = (short)newStack;
if (DEBUGSTACK) {
System.out.println("After "+bytecodeStr(ByteCode.TABLESWITCH)
+" stack = "+itsStackTop);
}
return switchStart;
} | 7 |
public IAIGraph createGraph() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(this.src));
// Files are not encoded so you have to do it manually
String line1 = UTF8EncodedString(br.readLine());
this.direction = getDirection(line1);
initGraph();
String line = UTF8EncodedString(br.readLine());
while (line != null && line != "") {
String[] srcDestEdge = line.split(",");
// if there is no correct split: src, dest, edge break out of
// while
if (srcDestEdge.length <= 2) {
break;
}
// Method to add src dest and edge into Graph
addToGraph(srcDestEdge);
// read in next line
line = UTF8EncodedString(br.readLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
} finally {
try {
br.close();
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
}
}
return graph;
} | 6 |
@Override
public void doNewGame()
{
SettingsDialog.getInstance().showDialog();
} | 0 |
protected Component findComponentAt(Container container, int x, int y) {
Rectangle bounds = new Rectangle();
int count = container.getComponentCount();
//ShapePainterStrategy shapePainterStrategy = getShapePainter(container, null);
for(int i = 0; i < count; i++) {
Component child = container.getComponent(i);
if(child.isVisible()) {
child.getBounds(bounds);
if(bounds.contains(x, y)) {
if(child instanceof Container) {
// recursive
Component found = findComponentAt((Container) child, x - bounds.x, y - bounds.y);
if(found != null) {
return found;
} else {
return child;
}
} else if(! (child instanceof HeavyShape || child instanceof HeavyLabel)) {
// skip our dedicated components for heavyweight support
return child;
// } else if (child != shapePainterStrategy.heavyShape &&
// child != shapePainterStrategy.heavyShape.label){
// // skip our dedicated components for heavyweight support
// return child;
}
}
}
}
return null;
} | 7 |
public static String base64encode(byte[] buf) {
int size = buf.length;
char[] ar = new char[((size + 2) / 3) * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = (i < size) ? buf[i++] : 0;
byte b2 = (i < size) ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
switch (size % 3) {
case 1:
ar[--a] = '=';
case 2:
ar[--a] = '=';
}
return new String(ar);
} | 5 |
private int endY( Side side ){
if( side == Side.NORTH ){
return boundaries.y;
}
else{
return boundaries.y + boundaries.height;
}
} | 1 |
public double[] convolve_rows_gauss(double[] image, double[] mask)
{
long j, r, c, l;
double sum;
double [] h;
int n;
h = new double[(int) (width*height)];
n=(int) ((mask.length-1)*0.5);
/* Inner region */
for (r=n; r<height-n; r++) {
for (c=0; c<width; c++) {
l = LINCOOR(r,c,width);
sum = 0.0;
for (j=-n;j<=n;j++)
sum += (double)(image[(int) (l+j*width)])*mask[(int) j+n];
h[(int) l] = sum;
}
}
/* Border regions */
for (r=0; r<n; r++) {
for (c=0; c<width; c++) {
l = LINCOOR(r,c,width);
sum = 0.0;
for (j=-n;j<=n;j++)
sum += (double)(image[(int) LINCOOR(BR(r+j),c,width)])*mask[(int) j+n];
h[(int) l] = sum;
}
}
for (r=height-n; r<height; r++) {
for (c=0; c<width; c++) {
l = LINCOOR(r,c,width);
sum = 0.0;
for (j=-n;j<=n;j++)
sum += (double)(image[(int) LINCOOR(BR(r+j),c,width)])*mask[(int) j+n];
h[(int) l] = sum;
}
}
return h;
} | 9 |
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnExcluir) {
do_btnExcluir_actionPerformed(e);
}
if (e.getSource() == btnEntrar) {
do_btnEntrar_actionPerformed(e);
}
if (e.getSource() == btnNovo) {
do_btnNovo_actionPerformed(e);
}
} | 3 |
@EventHandler
public void onSignChange(final SignChangeEvent event)
{
if (event.getLine(0) != null)
{
if ("<-pCops->".equals(event.getLine(0)) && !event.getPlayer().hasPermission("pcops.signpost"))
{
event.getBlock().breakNaturally();
}
}
} | 3 |
public String Tclient(int num) throws SocketException, IOException, InterruptedException{
TelnetService TC=TNH.get(num);
TNH.get(num).mynum=num;
String rtn=TC.getTelnetSessionAsString(Integer.toString(num));
if (rtn.equals("reload")){return rtn;}
TC.readit(" ","Room error");
dw.append("Server "+num+": ");
TC.write("gos Goslink is enabled.");
TC.readit("\n","Room error");
TC.write("\n");
String msg = null;
while (TC.loggedin == 1){
TC.readUntil("gossips:");
msg=TC.readUntil("\n");
if (msg.equals("!OffLINE+02")){
}else{
sayit(num,msg);
}
}
dw.append("Server "+num+" is offline.");
killme(num);
return "reload";
} | 3 |
boolean handleMousePressed(int x, int y) {
if (selectedComponent instanceof LineComponent) {
LineComponent lc = (LineComponent) selectedComponent;
int i = lc.nearEndPoint(x, y);
lc.setSelectedEndPoint(i);
lc.storeCurrentState();
return i > 0;
} else if (selectedComponent instanceof RectangleComponent) {
RectangleComponent rc = (RectangleComponent) selectedComponent;
byte i = rc.nearHandle(x, y);
rc.setSelectedHandle(i);
setAnchorPointForRectangularShape(i, rc.getX(), rc.getY(), rc.getWidth(), rc.getHeight());
if (i >= 0)
rc.storeCurrentState();
return i >= 0;
} else if (selectedComponent instanceof EllipseComponent) {
EllipseComponent ec = (EllipseComponent) selectedComponent;
byte i = ec.nearHandle(x, y);
ec.setSelectedHandle(i);
setAnchorPointForRectangularShape(i, ec.getX(), ec.getY(), ec.getWidth(), ec.getHeight());
if (i >= 0)
ec.storeCurrentState();
return i >= 0;
} else if (selectedComponent instanceof TriangleComponent) {
TriangleComponent tc = (TriangleComponent) selectedComponent;
byte i = tc.nearHandle(x, y);
tc.setSelectedHandle(i);
Rectangle rt = tc.getBounds();
setAnchorPointForRectangularShape(i, rt.x, rt.y, rt.width, rt.height);
if (i >= 0)
tc.storeCurrentState();
return i >= 0;
}
return false;
} | 7 |
int syncHeader(byte syncmode) throws IOException {
if((bytesread = source.read(syncbuf,0,3))!= 3)
return -1;
// return 0;
headerstring = syncbuf[0] << 16 & 0xff0000 | syncbuf[1] << 8 & 0xff00 | syncbuf[2] << 0 & 0xff;
if(first_call){
id_v2 [0] = syncbuf[0];
id_v2 [1] = syncbuf[1];
id_v2 [2] = syncbuf[2];
first_call = false;
}
//id_v2 [3] = syncbuf[3];
// off = 4;
do{
headerstring <<= 8;
if(source.read(syncbuf,3,1) != 1)
//return 0;
return -1;
headerstring |= syncbuf[3] & 0xff;
if(!first_sync){
if(off+1 > id_v2.length){
temp = new byte [off + 4];
System.arraycopy(id_v2, 0, temp, 0, id_v2.length);
id_v2 = temp;
}
id_v2 [off] = syncbuf[3];
off ++;
}
}while(!isSyncMark(headerstring,syncmode,syncword));
return headerstring;
} | 6 |
final boolean method321(int i, int i_14_, int i_15_, int i_16_) {
anInt411++;
if (anInt418 > i_16_ || (anInt419 ^ 0xffffffff) > (i_16_ ^ 0xffffffff))
return false;
if ((i_15_ ^ 0xffffffff) > (anInt416 ^ 0xffffffff) || i_15_ > anInt406)
return false;
if (i_14_ < anInt412 || (i_14_ ^ 0xffffffff) < (anInt404 ^ 0xffffffff))
return false;
if (i != -14735)
setNativeLibraryLoader(null, null, (byte) 29);
int i_17_ = -anInt409 + i_16_;
int i_18_ = i_14_ + -anInt408;
if (anInt405 <= i_17_ * i_17_ + i_18_ * i_18_)
return false;
return true;
} | 8 |
private static Move ForwardRightCaptureForBlack(int r, int c, Board board){
Move forwardRightCapture = null;
if(r>=2 && c>=2 && (
board.cell[r-1][c-1].equals(CellEntry.white)
|| board.cell[r-1][c-1].equals(CellEntry.whiteKing)
)
&& board.cell[r-2][c-2].equals(CellEntry.empty)
)
{
forwardRightCapture = new Move(r,c,r-2,c-2);
//System.out.println("Forward Right Capture for Black");
}
return forwardRightCapture;
} | 5 |
protected void updateBlackHole() {
blackHole.extendDuration(1);
if (blackHole.isExpired()) {
isBlackHole = false;
blackHole.reset();
}
} | 1 |
public void goalKick( ArrayList<Player> players, Player p){
if (((Player)p).isGoalie()){
try{
p.setBall(ball);
int num = GameEngine.rgen.nextInt(11);
if(players.get(num) != p){
p.pass(players.get(num));
} else {
if(num < 10){
num ++;
} else {
num--;
}
p.pass(players.get(num));
}
}catch(NullPointerException e){
p.testSetBall(true);
Random rand = new Random();
int num = rand.nextInt(11);
if(players.get(num) != p){
p.testPass(players.get(num));
} else {
if(num < 10){
num ++;
} else {
num--;
}
p.testPass(players.get(num));
}
}
}
} | 6 |
protected int computeScore () throws IncompatibleScoringSchemeException
{
int[] array;
int rows = seq1.length()+1, cols = seq2.length()+1;
int r, c, tmp, ins, del, sub, max_score;
// keep track of the maximum score
max_score = 0;
if (rows <= cols)
{
// goes columnwise
array = new int [rows];
// initiate first column
for (r = 0; r < rows; r++)
array[r] = 0;
// calculate the similarity matrix (keep current column only)
for (c = 1; c < cols; c++)
{
// set first position to zero (tmp hold values
// that will be later moved to the array)
tmp = 0;
for (r = 1; r < rows; r++)
{
ins = array[r] + scoreInsertion(seq2.charAt(c));
sub = array[r-1] + scoreSubstitution(seq1.charAt(r), seq2.charAt(c));
del = tmp + scoreDeletion(seq1.charAt(r));
// move the temp value to the array
array[r-1] = tmp;
// choose the greatest (or zero if all negative)
tmp = max (ins, sub, del, 0);
// keep track of the maximum score
if (tmp > max_score) max_score = tmp;
}
// move the temp value to the array
array[rows - 1] = tmp;
}
}
else
{
// goes rowwise
array = new int [cols];
// initiate first row
for (c = 0; c < cols; c++)
array[c] = 0;
// calculate the similarity matrix (keep current row only)
for (r = 1; r < rows; r++)
{
// set first position to zero (tmp hold values
// that will be later moved to the array)
tmp = 0;
for (c = 1; c < cols; c++)
{
ins = tmp + scoreInsertion(seq2.charAt(c));
sub = array[c-1] + scoreSubstitution(seq1.charAt(r), seq2.charAt(c));
del = array[c] + scoreDeletion(seq1.charAt(r));
// move the temp value to the array
array[c-1] = tmp;
// choose the greatest (or zero if all negative)
tmp = max (ins, sub, del, 0);
// keep track of the maximum score
if (tmp > max_score) max_score = tmp;
}
// move the temp value to the array
array[cols - 1] = tmp;
}
}
return max_score;
} | 9 |
public static void captureScreenshot() {
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH); //4
int year = cal.get(Calendar.YEAR); //2013
int sec =cal.get(Calendar.SECOND);
int min =cal.get(Calendar.MINUTE);
int date = cal.get(Calendar.DATE);
int day =cal.get(Calendar.HOUR_OF_DAY);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
mailscreenshotpath = System.getProperty("user.dir")+"\\screenshots\\"+year+"_"+date+"_"+(month+1)+"_"+day+"_"+min+"_" +sec+".jpeg";
FileUtils.copyFile(scrFile, new File(mailscreenshotpath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 1 |
@Override
public void mouseClicked(MouseEvent paramMouseEvent) {/**/} | 0 |
@Override
public SkillsMain[] getSkillNames() {
return Constants.assassinSkillSkills;
} | 0 |
public void writeTable(Map table, boolean reversed) {
if (!isReachable() && (Main.stripping & Main.STRIP_UNREACH) != 0)
return;
if (getAlias().length() != 0) {
String name = getName();
Identifier outer = getParent();
while (outer != null && outer.getAlias().length() == 0) {
if (outer.getName().length() > 0)
name = outer.getName() + "." + name;
outer = outer.getParent();
}
if (reversed)
table.put(getFullAlias(), name);
else
table.put(getFullName(), getAlias());
}
for (Iterator i = getChilds(); i.hasNext();)
((Identifier) i.next()).writeTable(table, reversed);
} | 8 |
public static void main(String args[]){
AudioInputStream ain;
try {
ain = AudioSystem.getAudioInputStream(new File("C:\\Users\\Andy2\\javawork\\workspace\\Learning Java\\src\\empous\\resources\\audio\\sample.wav"));
DataLine.Info info =
new DataLine.Info(Clip.class,ain.getFormat( ));
clip = (Clip) AudioSystem.getLine(info);
clip.open(ain);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
clip.start();
} | 3 |
protected void updateEntityActionState()
{
++this.entityAge;
this.despawnEntity();
this.moveStrafing = 0.0F;
this.moveForward = 0.0F;
float var1 = 8.0F;
if (this.rand.nextFloat() < 0.02F)
{
EntityPlayer var2 = this.worldObj.getClosestPlayerToEntity(this, (double)var1);
if (var2 != null)
{
this.currentTarget = var2;
this.numTicksToChaseTarget = 10 + this.rand.nextInt(20);
}
else
{
this.randomYawVelocity = (this.rand.nextFloat() - 0.5F) * 20.0F;
}
}
if (this.currentTarget != null)
{
this.faceEntity(this.currentTarget, 10.0F, (float)this.getVerticalFaceSpeed());
if (this.numTicksToChaseTarget-- <= 0 || this.currentTarget.isDead || this.currentTarget.getDistanceSqToEntity(this) > (double)(var1 * var1))
{
this.currentTarget = null;
}
}
else
{
if (this.rand.nextFloat() < 0.05F)
{
this.randomYawVelocity = (this.rand.nextFloat() - 0.5F) * 20.0F;
}
this.rotationYaw += this.randomYawVelocity;
this.rotationPitch = this.defaultPitch;
}
boolean var4 = this.isInWater();
boolean var3 = this.handleLavaMovement();
if (var4 || var3)
{
this.isJumping = this.rand.nextFloat() < 0.8F;
}
} | 9 |
private void loadWords() throws IOException {
File f = new File(wordsPath);
FileInputStream fis = new FileInputStream(f);
InputStreamReader in = new InputStreamReader(fis, "utf-8");
BufferedReader br = new BufferedReader(in);
String l = null;
int wordCount = 0;
while ((l = br.readLine()) != null) {
// split on comma
int index = l.indexOf(',');
if (index < 0) {
index = l.indexOf('\t');
}
if (index < 0) {
index = l.indexOf('=');
}
if (index < 0) {
index = l.indexOf(' ');
}
if (index < 0) {
System.out.println("Could not find ',', '\t', '=' or ' ' in '"
+ l + "' -- ignore");
}
String portuguese = l.substring(0, index);
String english = l.substring(index + 1);
if (english.indexOf(',') > 0)
english = english.substring(0, english.indexOf(','));
pwords.add(portuguese);
ewords.add(english);
e2p.put(english, portuguese);
p2e.put(portuguese, english);
wordCount++;
}
System.out.println("Read " + wordCount + " words. e2p=" + e2p.size() + " p2e=" + p2e.size());
br.close();
} | 6 |
static void process() {
int i, j;
// we initialize every element in P with -1
for (i = 0; i < nodes; i++)
for (j = 0; 1 << j < nodes; j++) {
P[i][j] = -1;
D[i][j] = 0;
}
// the first ancestor of every node i is T[i]
for (i = 0; i < nodes; i++) {
P[i][0] = T[i];
D[i][0] = W[i];
}
// bottom up dynamic programming
for (j = 1; 1 << j < nodes; j++)
for (i = 0; i < nodes; i++)
if (P[i][j - 1] != -1) {
P[i][j] = P[P[i][j - 1]][j - 1];
D[i][j] = D[i][j - 1] + D[P[i][j - 1]][j - 1];
}
} | 6 |
private boolean checkPlaceFiel() {
if (currentStadiumIndex < 0) {
ModalDialog.showEror(frame, "Выберите стадион!");
return false;
}
if (sectorField.getText().trim().isEmpty() || placeField.getText().trim().isEmpty()) {
ModalDialog.showEror(frame, "Сектор и место не могут быть пустыми!");
return false;
}
try
{
Integer.parseInt(placeField.getText().trim());
}
catch(NumberFormatException ex)
{
ModalDialog.showEror(frame, "Номер местa не число!");
return false;
}
return true;
} | 4 |
private void vistDFS(XmlNode node)
{
node.level = node.getLevel();
node.path = node.getPath();
if (node.nodetype == XmlNodeType.NODE)
{
if (node.getAttribute("type").equals(XmlScript.NODE_TYPE_NET))
this.addNet(node);
else if (node.getAttribute("type").equals(XmlScript.NODE_TYPE_ROUTER))
this.addRouter(node);
else if (node.getAttribute("type").equals(XmlScript.NODE_TYPE_LINK))
this.addLink(node);
}
for (XmlNode child : node.getChildren())
{
vistDFS(child);
}
} | 5 |
public boolean addChild(Row row) {
if (canHaveChildren()) {
row.removeFromParent();
mChildren.add(row);
row.mParent = this;
return true;
}
return false;
} | 1 |
@Override
public Integer getIdFromDataBase() throws SQLException{
Connection connection = ua.edu.odeku.pet.database.ConnectionDataBase.getConnection();
Statement statement = connection.createStatement();
if(nameDepartment == null || nameDepartment.isEmpty()){
return null;
} else if(idFaculty == null || idFaculty.getIdFaculty() == null){
return null;
}
ResultSet rs = statement.executeQuery("Select id_department from Department "
+ "where name_department = '"+nameDepartment+"' and id_faculty = "+idFaculty.getIdFaculty()+";");
if(rs.next()){
Integer id = rs.getInt(1);
return id;
} else {
return null;
}
} | 5 |
private static String convertToSaveableString(String string[][]){
String temp="";
for (int a=0; a < string.length; a++ ){
for (int b=0; b < 2; b++ ){
if (b==0){
temp += string[a][b]+DATA_DIVIDER1;
} else {
temp += string[a][b]+DATA_DIVIDER2;
}
}
}
return temp;
} | 3 |
public int read(int address) {
if (this.cache.contains(address)) {
return this.cache.read(address);
} else {
for (int i = 0; i < this.history.length; i++) {
if (this.history[i] == address) {
// conflict miss
int mode = Integer.valueOf(this.cache.getMode(), 2);
if (mode < 8)
mode += 4;
this.cache.setMode(Integer.toBinaryString(mode));
System.out.println("Changing mode to " + Integer.toBinaryString(mode));
return this.cache.read(address);
}
}
//not found so It is first hit miss or capacity miss
int mode = Integer.valueOf(this.cache.getMode(), 2);
if (mode > 3)
mode -= 3;
else if (mode < 3)
mode++;
String newMode = Integer.toBinaryString(mode);
while (newMode.length() < 4)
newMode = '0' + newMode;
this.cache.setMode(newMode);
System.out.println("Changing mode to " + newMode);
return this.cache.read(address);
}
} | 7 |
boolean writeBytes(Frame frame) {
synchronized (this) {
if (m_handshaked == false ||
m_destroying == true) {
return false;
}
}
int n = -1;
ByteBuffer data = frame.getData();
int size = data.capacity();
int offset = 0;
try {
while(offset < size) {
n = m_socketChannel.write(data);
offset += n;
}
} catch (Exception e) {
n = -1;
}
if (n <= 0) {
// We do not destroy the connection at this point, even if we
// we have a write error. The receiveHandler will take care of
// it.
return false;
}
return true;
} | 5 |
private boolean evaluateAddClause(String str) {
Matcher matcher = ATOM.matcher(str);
if (matcher.find()) {
str = str.substring(matcher.end()).trim();
Point3f p = new Point3f();
String s1 = null;
int space = str.indexOf(" ");
if (space < 0) {
s1 = str.substring(0).trim();
p.x = (float) (Math.random() - 0.5f) * model.getLength();
p.y = (float) (Math.random() - 0.5f) * model.getWidth();
p.z = (float) (Math.random() - 0.5f) * model.getHeight();
}
else {
s1 = str.substring(0, space).trim();
String s2 = str.substring(space + 1).trim();
float[] r = parseCoordinates(s2);
if (r != null) {
p.x = r[0];
p.y = r[1];
p.z = r[2];
}
else {
out(ScriptEvent.FAILED, "Error: Cannot parse " + str);
return false;
}
}
String symbol = null;
for (String s : model.paramMap.keySet()) {
if (s.equalsIgnoreCase(s1)) {
symbol = s;
break;
}
}
if (symbol == null) {
double a = parseMathExpression(s1);
if (!Double.isNaN(a)) {
symbol = model.getSymbol((int) Math.round(a));
}
}
if (symbol == null) {
out(ScriptEvent.FAILED, "Unrecognized element to add: " + str);
return false;
}
if (view.addAtom(p, symbol)) {
view.repaint();
}
else {
out(ScriptEvent.HARMLESS, "Cannot insert an atom to the specified location: " + str);
}
return true;
}
out(ScriptEvent.FAILED, "Unrecognized type of object to add: " + str);
return false;
} | 9 |
private void cifrarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cifrarBActionPerformed
String log = "";
String c;
String m = plaintextTF.getText();
System.out.println("m: "+m);
log += "\n Message to cipher: "+m;
ArrayList<Integer> c_ascii = new ArrayList<>();
ArrayList<Integer> m_ascii = new ArrayList<>();
for(int i=0;i<m.length();i++){
m_ascii.add((int)m.charAt(i));
}
c_ascii = cipher.cipher(m_ascii);
m_ascii = cipher.decipher(c_ascii);
log += "\n p: "+ cipher.key.getP().toString()
+ "\n q: "+ cipher.key.getQ().toString()
+ "\n n: "+ cipher.key.getN().toString()
+ "\n phi: "+ cipher.key.getPhi().toString()
+ "\n e: "+ cipher.key.getE().toString()
+ "\n d: "+ cipher.key.getD().toString();
m="";
c="";
for(int i= 0; i<m_ascii.size();i++){
int j =m_ascii.get((i));
m += (char)j;
}
for(int i= 0; i<c_ascii.size();i++){
int j =c_ascii.get((i));
c += (char)j;
}
System.out.println("c: "+c);
System.out.println("m: "+m);
key1TF.setText(cipher.key.getE().toString());
key1TF1.setText(cipher.key.getD().toString());
cipherTextTF.setText(c);
decipherTextTF.setText(m);
textArea.setText(log);
}//GEN-LAST:event_cifrarBActionPerformed | 3 |
private StdFileDialog(String... extension) {
for (String one : extension) {
mFileNameMatchers.add(createExtensionMatcher(one));
}
} | 1 |
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.