text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void actionPerformed(ActionEvent action) {
if(action.getSource().equals(connect)) {
int desired = 48;
try {
pf.setString("connect_hostname", serverName.getText());
pf.setInt("connect_port", Integer.parseInt(portNum.getText()));
pf.setInt("listen_port", Integer.parseInt(localServerPortnum.getText()));
try {
desired = Integer.parseInt(desiredSize.getText());
} catch (NumberFormatException nfe) {
desired = 48;
desiredSize.setText("48");
}
pf.setInt("cache_size", desired);
desiredSize.setEditable(false);
pf.save();
} catch (NumberFormatException nfe) {
}
if(serverMainThread == null || !serverMainThread.isAlive()) {
safeSetButton("Stop");
final String distantServer = serverName.getText() + ":" + portNum.getText();
final String localServer = localServerPortnum.getText();
final String cacheSize = Integer.toString(desired * 1024 * 1024);
serverMainThread = new Thread(new Runnable() {
public void run() {
String[] args = {
localServer,
distantServer,
"local_cache",
"quiet",
"bridge_connection",
"cache_limit",
cacheSize
};
Main.main(args, false);
}
});
serverMainThread.start();
} else {
safeSetButton("Stopping");
serverMainThread.interrupt();
desiredSize.setEditable(true);
}
}
} | 5 |
public String getSumbitIp() {
return this.sumbitIp;
} | 0 |
private static double[] getSupportPoints(int lineNumber, double[] lowPrices) {
double[] sPoints = new double[lineNumber];
for(int i =0;i<lineNumber-1;i++){
double price = 999999999;
for(int j=-5;j<=0;j++){
if((i+j>=0) && (i+j<lineNumber-1) && lowPrices[i+j]<price){
price =lowPrices[i+j];
sPoints[i]=price;
}
}
}
return sPoints;
} | 5 |
public boolean execute() {
try {
updateGraph();
System.out.print(name+": ");
// initialize output streams
FileOutputStream fos = null;
PrintStream pstr = System.out;
if( baseName != null )
{
String fname = fng.nextCounterName();
fos = new FileOutputStream(fname);
System.out.println("writing to file "+fname);
pstr = new PrintStream(fos);
}
else System.out.println();
if( format.equals("neighborlist") )
GraphIO.writeNeighborList(g, pstr);
else if( format.equals("edgelist") )
GraphIO.writeEdgeList(g, pstr);
else if( format.equals("chaco") )
GraphIO.writeChaco(g, pstr);
else if( format.equals("netmeter") )
GraphIO.writeNetmeter(g, pstr);
else if( format.equals("gml") )
GraphIO.writeGML(g, pstr);
else if( format.equals("dot") )
GraphIO.writeDOT(g, pstr);
else
System.err.println(name+": unsupported format "+format);
if( fos != null ) fos.close();
return false;
}
catch( IOException e )
{
throw new RuntimeException(e);
}
} | 9 |
public Actor getActor(int x, int y){
for (Actor actor : actorList){
if (actor.getPosX() == x && actor.getPosY() == y){
return actor;
}
}
return null;
} | 3 |
public void run() {
// Call to
// /api/0.1/getBugs?b=36.17496&t=61.03797&l=-9.9793&r=31.54902&ucid=1
// Reply is something like: putAJAXMarker(552542, 6.971592, 50.810296,
// 'Strassensystem auf Friedhof fehlt [TobiR, 2010-08-09 23:30:37
// CEST]', 0);
try {
String url = OpenStreetBugs.API_URL + "getBugs?b=" + ymin + "&t=" + ymax + "&l=" + xmin
+ "&r=" + xmax;
HttpConnection httpConn = (HttpConnection) Connector.open(url);
DataInputStream in = httpConn.openDataInputStream();
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int openbrackets = 0;
for (int b = in.read(); b != -1; b = in.read()) {
char c = (char) b;
if (c == ')') {
openbrackets--;
if (openbrackets == 0) {
Bug bug = Bug.parse(buf.toString());
buf.reset();
if (bug != null) {
rec.receiveBug(bug);
if (++receivedBugs >= MAX_BUGS) {
break;
}
}
}
} else if (c == '(') {
openbrackets++;
} else if (openbrackets > 0) { // only store bytes between '('
// ')'
buf.write(b);
}
}
in.close();
httpConn.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
} | 9 |
public void draw(Graphics2D g) {
for(
int row = rowOffset;
row < rowOffset + numRowsToDraw;
row++) {
if(row >= numRows) break;
for(
int col = colOffset;
col < colOffset + numColsToDraw;
col++) {
if(col >= numCols) break;
if(map[row][col] == 0) continue;
int rc = map[row][col];
int r = rc / numTilesAcross;
int c = rc % numTilesAcross;
g.drawImage(
tiles[r][c].getImage(),
(int)x + col * tileSize,
(int)y + row * tileSize,
null
);
}
}
} | 5 |
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChange(final SignChangeEvent changing) {
final List<String> worldFilters = this.worlds.get(changing.getBlock().getWorld().getName());
if (worldFilters == null) return;
final String[] lines = changing.getLines();
for (final String filterName : worldFilters) {
if (this.filters.get(filterName).accepts(lines)) {
this.signChanges.add(new SignChange(filterName, changing.getBlock().getLocation(), System.currentTimeMillis(), lines));
this.stale = true;
}
}
} | 3 |
public boolean isConvex() throws TypeOverflowException {
int signPlus = 0,
signMinus = 0;
double z;
int n = vertices.size();
for (int i = 0; i < n; ++i) {
int j = (i + 1) % n;
int k = (i + 2) % n;
z = (vertices.get(j).x - vertices.get(i).x) * (vertices.get(k).y - vertices.get(j).y);
z -= (vertices.get(j).y - vertices.get(i).y) * (vertices.get(k).x - vertices.get(j).x);
if (z < 0) ++signMinus;
if (z > 0) ++signPlus;
if (Double.isInfinite(z) || Double.isNaN(z))
throw new TypeOverflowException();
if (signMinus != 0 && signPlus != 0)
return false;
}
if (signMinus != 0 && signPlus != 0)
return false;
else
return true;
} | 9 |
public ArrayList<ConnectedComponent> findTrajectory()
{
ArrayList<ConnectedComponent> traj = new ArrayList<ConnectedComponent>();
boolean searched[][] = new boolean[_height][_width];
for (int x = 50; x < _width - 50; x++)
for (int y = _groundLevel - 1; y > _height * 0.1; y--)
{
int cls = _class[y][x];
if (!searched[y][x] && cls == TRAJECTORY)
{
ConnectedComponent cc;
cc = new ConnectedComponent(_class, x, y, searched, false);
if (cc.getArea() >= MIN_SIZE[TRAJECTORY] && cc.getArea() <= MAX_SIZE[TRAJECTORY])
traj.add(cc);
}
}
return traj;
} | 6 |
private boolean safe(boolean[][]board, int i, int j) {
int d45x = j + i, d135x = j - i;
for (int k = 0; k < board.length; k ++) {
if (board[i][k]) return false;
if (board[k][j]) return false;
if (d45x - k >= 0 && d45x - k < board.length && board[k][d45x - k]) return false;
if (d135x + k >= 0 && d135x + k < board.length && board[k][d135x + k]) return false;
}
return true;
} | 9 |
public static void clearLowInventoryTable(DrugInventoryPage drugP){
int rows= drugP.getLowInventoryTable().getRowCount();
for(int i=0;i<rows;i++){
drugP.getLowInventoryTable().setValueAt("",i,0);
}
} | 1 |
private Repository getRepository(String organizationName, String repositoryName) throws IOException {
for (Repository repository : getRepositories(organizationName)) {
if (repository.getName().equals(repositoryName)) {
return repository;
}
}
// We don't know about that repo.
throw new NotFoundException("Could not find repository " + repositoryName + " in organization " + organizationName);
} | 2 |
public static void combatinitialize() {
int enemyInit; //enemies Initiative
int playerInit; //Players Initiative
Random rnd = new Random();
do{
enemyInit = rnd.nextInt(10) + 3; //Randomize chance Variable for enemy Initiative
playerInit = rnd.nextInt(10) + 1; //Randomize chance Variable for Player Initiative
} while (enemyInit == playerInit);
if (enemyInit > playerInit)
EnemyRat.enemyturn();
else if (playerInit > enemyInit);
EnemyRat.playerturn();
} | 3 |
private void addFleatingSpring() {
if (getModel().getView().isClicked()) {
double x = getModel().getView().getLastMousePosition().x;
double y = getModel().getView().getLastMousePosition().y;
Mass fleatingMass = new MoveableMass(x, y, 1);
if (myCurrentMass == null) {
myCurrentMass = closestMass(myMassesToAssembly.keySet(), fleatingMass);
}
Spring fleatingSpring = new Spring(myCurrentMass, fleatingMass,
Spring.DEFAULT_REST_LENGTH, Spring.DEFAULT_KVAL);
Assembly currentAssembly = myMassesToAssembly.get(myCurrentMass);
mySpringsToMass.put(fleatingSpring, myCurrentMass);
currentAssembly.add(fleatingSpring);
}
else {
myCurrentMass = null;
}
} | 2 |
public static void main(String[] args) {
// TODO Auto-generated method stub
// set variables for port, socket
final int port = 3344;
Socket sock = null;
// set variables for RSAKeySize, public key, private key
final int RSAKeySize = 1024;
PublicKey pubKey = null;
PrivateKey priKey = null;
Key serverPubKey = null;
String text = "password";
byte[] plainText = text.getBytes();
byte[] nonce = generateNonce();
byte[] serverNonce = null;
byte[] firtHalf;
byte[] secondHalf;
ObjectOutputStream obOut = null;
ObjectInputStream obIn = null;
//Connecting
try {
System.out.println("Client is now establishing connection.");
sock = new Socket(InetAddress.getLocalHost(), port);
obOut = new ObjectOutputStream(
sock.getOutputStream());
obIn = new ObjectInputStream(sock.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
try {
//Send nonce to server
obOut.writeObject(new String(nonce));
obOut.flush();
//Receive nonce from server
String nonceString= (String)obIn.readObject();
serverNonce = nonceString.getBytes();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Generate public key
try {
System.out.println("Start generating RSA key:");
KeyPairGenerator RSAKeyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
RSAKeyGen.initialize(RSAKeySize, random);
KeyPair pair = RSAKeyGen.generateKeyPair();
pubKey = pair.getPublic();
priKey = pair.getPrivate();
System.out.println("Finish generating RSA key");
} catch (Exception e) {
e.printStackTrace();
}
try {
//Send public key to server
System.out.println("Send client public key to server:\n");
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(pubKey.getEncoded().length);
sock.getOutputStream().write(bb.array());
sock.getOutputStream().write(pubKey.getEncoded());
sock.getOutputStream().flush();
//Get server's public key
byte[] lenb = new byte[4];
sock.getInputStream().read(lenb, 0, 4);
ByteBuffer inbb = ByteBuffer.wrap(lenb);
int len = inbb.getInt();
System.out.println("Length of the public key: " + len);
byte[] cPubKeyBytes = new byte[len];
sock.getInputStream().read(cPubKeyBytes);
System.out.println("Public Key:\n");
X509EncodedKeySpec ks = new X509EncodedKeySpec(cPubKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
serverPubKey = kf.generatePublic(ks);
System.out.println("Encoded Public Key:\n");
//combine nonce and password and break in between
byte[] newText = combineNonce(serverNonce, plainText);
String newString = new String(newText);
firtHalf = newString.substring(0, newString.length()/2).getBytes();
secondHalf = newString.substring(newString.length()/2).getBytes();
//Encrypt the message
System.out.println("Start Encryption for plainText");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, serverPubKey);
byte[] cipherFirst = cipher.doFinal(firtHalf);
byte[] cipherSecond = cipher.doFinal(secondHalf);
System.out.println("Finish Encryption to cipherText:\n");
BASE64Encoder base64 = new BASE64Encoder();
String encryptedFirst = base64.encode(cipherFirst);
String encryptedSecond = base64.encode(cipherSecond);
System.out.println("Base64 Encoded:\n"); // + encryptedValue);
//Send the first half encrypted message
obOut.writeObject(encryptedFirst);
obOut.flush();
//receive the first half from server
String first = (String)obIn.readObject();
//Send the second half
obOut.writeObject(encryptedSecond);
obOut.flush();
//Receive message from servers
String second = (String)obIn.readObject();
System.out.println("Receive from server:\n");
//String received = first+second;
//Decode message from server
byte[] decoFirst = new BASE64Decoder().decodeBuffer(first);
byte[] decoSec = new BASE64Decoder().decodeBuffer(second);
System.out.println("Start decryption");
Cipher priCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
priCipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] newPlainTextFirst = priCipher.doFinal(decoFirst);
byte[] newPlainTextSec = priCipher.doFinal(decoSec);
String finalDeco = new String(newPlainTextFirst) + new String(newPlainTextSec);
System.out.println("Finish decryption:\n" + finalDeco);
if (finalDeco.toLowerCase().contains(text.toLowerCase())) {
verificationSucceed();
} else {
verificationFail();
}
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 6 |
public void addItem(int type){
for(int i = 0; i < invCount; i++){
if(inv[i].type == 0){
inv[i].type = type;
if(invCount < inv.length)invCount++;
break;
}
}
} | 3 |
private String getVariablesList() {
StringBuilder list = new StringBuilder();
for ( int i = 0; i < sqlVariables.size(); i++ ) {
if ( i % 5 == 0 && i != 0 )
list.append( "\n" + TAB + TAB + TAB );
switch ( databaseType ) {
case H2:
case ORACLE:
list.append( sqlVariables.get( i ) );
}
if ( i != sqlVariables.size() - 1 ) {
list.append( " , " );
}
}
return list.toString();
} | 6 |
public void PaymentHandler(){} | 0 |
public static void export(ResolveReport resolved,String output,String classpath,String pattern,String pathprefix) throws IOException {
File outputPath = new File(output);
if( !outputPath.exists() )
outputPath.mkdirs();
if( !outputPath.exists() || !outputPath.isDirectory())
throw new RuntimeException("invalid output directory");
PrintWriter classpathWriter = null;
if( classpath!=null )
classpathWriter = new PrintWriter(new FileWriter(classpath));
for(ArtifactDownloadReport r : resolved.getAllArtifactsReports()) {
Artifact a = r.getArtifact();
if( TypeUtils.jar(a) ) {
String name = name(pattern,a);
FileUtil.copy(r.getLocalFile(),new File(output,name),null);
if( classpathWriter!=null )
classpathWriter.println( (pathprefix==null?"":pathprefix) + name );
}
}
if( classpathWriter!=null )
classpathWriter.close();
} | 9 |
private static void eliminarTienda()
{
boolean salir;
Integer idTienda;
do
{
try
{
System.out.print( "Introduce el Id de la tienda: ");
idTienda = Integer.parseInt( scanner.nextLine());
Tienda.eliminar( idTienda);
System.out.println( "- Tienda id " + idTienda + " eliminada del registro -");
salir = true;
}
catch (Exception e)
{
System.out.println( e.getMessage());
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
} while (!salir);
} | 2 |
private Piece checkCase(Piece[] B,int X, int Y,boolean isCapture) {
if (!(Utils.isVoid(B,X,Y))) {
Piece obstacle = Utils.getPiece(B,X,Y);
//Warning : pawn can move only to capture vertically
if ((isCapture) && (obstacle.isWhite()!=null) && (isWhite()!=obstacle.isWhite())) {
possibleMoves.add(obstacle.getPos());
}
return Utils.getPiece(B,X,Y);
} else {
//Warning : pawn can move to void case only when not capturing
if (!isCapture) possibleMoves.add(Utils.getPos(X,Y));
return null;
}
} | 5 |
public static String pad(String s) {
if (s.length() == 0) return " ";
char first = s.charAt(0);
char last = s.charAt(s.length()-1);
if (first == ' ' && last == ' ') return s;
if (first == ' ' && last != ' ') return s + " ";
if (first != ' ' && last == ' ') return " " + s;
if (first != ' ' && last != ' ') return " " + s + " ";
// impossible
return s;
} | 9 |
public FlacPicture(PropertyTree parent) {
super(MediaProperty.PICTURE, parent);
} | 0 |
public void addAP(MapleClient c, byte stat, short amount) {
MapleCharacter player = c.getPlayer();
switch (stat) {
case 1: // STR
player.getStat().setStr(player.getStat().getStr() + amount);
player.updateSingleStat(MapleStat.STR, player.getStat().getStr());
break;
case 2: // DEX
player.getStat().setDex(player.getStat().getDex() + amount);
player.updateSingleStat(MapleStat.DEX, player.getStat().getDex());
break;
case 3: // INT
player.getStat().setInt(player.getStat().getInt() + amount);
player.updateSingleStat(MapleStat.INT, player.getStat().getInt());
break;
case 4: // LUK
player.getStat().setLuk(player.getStat().getLuk() + amount);
player.updateSingleStat(MapleStat.LUK, player.getStat().getLuk());
break;
case 5:
player.setStorageAp(player.getStorageAp() + amount);
break;
}
if (!player.isAdmin()) {
player.setRemainingAp(player.getRemainingAp() - amount);
}
player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
} | 6 |
public void startElement(String uri, String localName, String qName, Attributes attributes) {
String value;
if (qName.equals("eblast")) {
if ((value = attributes.getValue("port")) != null) mSettings.setPort(Integer.valueOf(value));
if ((value = attributes.getValue("maxpeers")) != null) mSettings.setMaxPeers(Integer.valueOf(value));
if ((value = attributes.getValue("encrypted")) != null) mSettings.setEncryption(Boolean.valueOf(value));
if ((value = attributes.getValue("ignoreunencrypted")) != null) mSettings.setIgnoreUnencrypted(Boolean.valueOf(value));
} else if (qName.equals("download")) {
if ((value = attributes.getValue("path")) != null) mSettings.setDownloadDir(new File(value));
}
} | 7 |
private void setTimerDelay() {
switch (gameState.getDifficultyLevel()) {
case GameState.DIFFICULTY_EASY:
changePinTimer.setInitialDelay(randomGen.nextInt(10000) + 10000);
changePinTimer.restart();
break;
case GameState.DIFFICULTY_MEDIUM:
changePinTimer.setInitialDelay(randomGen.nextInt(15000) + 5000);
changePinTimer.restart();
break;
case GameState.DIFFICULTY_HARD:
changePinTimer.setInitialDelay(randomGen.nextInt(25000) + 2000);
changePinTimer.restart();
break;
}
} | 3 |
public int getRound()
{
return round;
} | 0 |
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Class declaringClass = method.getDeclaringClass();
if (declaringClass == Object.class) {
if (method.equals(hashCodeMethod)) {
return proxyHashCode(proxy);
} else if (method.equals(equalsMethod)) {
return proxyEquals(proxy, args[0]);
} else if (method.equals(toStringMethod)) {
return proxyToString(proxy);
} else {
throw new InternalError("unexpected Object method dispatched: "
+ method);
}
} else {
for (int i = 0; i < interfaces.length; i++) {
if (declaringClass.isAssignableFrom(interfaces[i])) {
try {
return method.invoke(delegates[i], args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
return invokeNotDelegated(proxy, method, args);
}
} | 7 |
public static <E> Map<E,int[][]> intTwoDArrayMapCopy(Map<E,int[][]> map) {
Map<E,int[][]> copy = null;
if (map instanceof HashMap<?,?>) {
copy = new HashMap<E,int[][]>();
} else if (map instanceof TreeMap<?,?>) {
copy = new TreeMap<E,int[][]>();
}
for (E e : map.keySet()) {
int[][] cts = map.get(e);
int[][] cpy = new int[cts.length][];
for (int i = 0; i < cts.length; i++) {
if (cts[i] != null) {
cpy[i] = new int[cts[i].length];
System.arraycopy(cts[i],0,cpy[i],0,cts[i].length);
}
}
copy.put(e,cpy);
}
return copy;
} | 9 |
Power(String name, int properties, String imgFile, String helpInfo) {
this.name = name ;
this.helpInfo = helpInfo ;
this.buttonTex = Texture.loadTexture(IMG_DIR+imgFile) ;
this.properties = properties ;
} | 4 |
@Override
public void execute(VirtualMachine vm) {
super.execute(vm);
((DebuggerVirtualMachine) vm).enterFunction();
((DebuggerVirtualMachine) vm).saveFunctionArgs(functionArgList);
((DebuggerVirtualMachine) vm).saveFunctionAddress(address);
} | 0 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
@Override
public boolean execute(RuleExecutorParam param) {
Rule rule=param.getRule();
String compareValue=rule.getValue();
try {
if(!Util.isNullOrEmpty(compareValue)){
Class<? extends RuleExecutor> methExe= Thread.currentThread().getContextClassLoader().loadClass(compareValue.trim()).asSubclass(RuleExecutor.class);
RuleExecutor ruleExe= methExe.newInstance();
return ruleExe.execute(param);
}
} catch (ClassNotFoundException e) {
throw new ExecutionException(e);
} catch (InstantiationException e) {
throw new ExecutionException(e);
} catch (IllegalAccessException e) {
throw new ExecutionException(e);
}
return false;
} | 5 |
public String getLstServicios() {
String lista = "";
for (Servicio s : lstServicios) {
lista += s;
}
return lista;
} | 1 |
@Override
public void onEnable() {
reloadPlugin();
joinListener = new PlayerJoinListener(this);
moveListener = new PlayerMoveListener(this);
if (getConfig().getBoolean("options.allow-plugin-metrics", true)) {
try {
metrics = new Metrics(this);
metrics.start();
getLogger().info("MultiSpawnPlus: Succesfully submitting stats to MCStats.org!");
} catch (IOException e) {
getLogger().info("MultiSpawnPlus: Failed to submit stats to MCStats.org! Error: " + e);
}
} else {
getLogger().info("MultiSpawnPlus: Plugin Metrics disallowed! Disabling submission of stats to MCStats.org...");
}
if (getConfig().getBoolean("options.auto-update") == true) {
updater = new Updater(this, 81894, this.getFile(), Updater.UpdateType.DEFAULT, true);
} else if (getConfig().getBoolean("options.auto-update") == false) {
updater = new Updater(this, 81894, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, false);
String latest = updater.getLatestName().substring(15);
if (version.equalsIgnoreCase(latest)) {
getLogger().info("MultiSpawnPlus: No updates available.");
} else {
getLogger().info("MultiSpawnPlus: Update available! (" + latest + ")");
getLogger().info("MultiSpawnPlus: Download here: " + updater.getLatestFileLink());
}
}
} | 5 |
public NodeId (byte[] bytes) {
Objects.requireNonNull(bytes);
if (bytes.length != 20) {
throw new IllegalArgumentException("invalid length");
}
this.bytes = Arrays.copyOf(bytes, bytes.length);
this.hash = Arrays.hashCode(bytes);
// Hex String
StringBuilder sb = new StringBuilder("NodeID(");
for (byte b : bytes) {
int ub = (b) & 0xFF;
if (ub < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(ub).toUpperCase());
}
this.string = sb.append(")").toString();
} | 3 |
@Override
public void run() {
while (cloudMap.getNoMaps()<CloudMapPanel.sampleSize && !stop) {
cloudMap.addMaps( 1 );
try {
Thread.sleep( 5 );
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
while (cloudMap.getNoPlaytestedSamples() < CloudMapPanel.sampleSize && !stop) {
cloudMap.playtestSample();
}
} | 5 |
public int getInvalidRxCount() {
return invalidRxPackets;
} | 0 |
private JMenu createFillMenu(){
fill = new JMenu("Fill");
algorithmZatravki = new JCheckBoxMenuItem(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(algorithmZatravki.isSelected()){
algorithmZatravki.setSelected(false);
}
if(!algorithmZatravki.isSelected()){
algorithmZatravki.setSelected(true);
}
algorithmScan.setSelected(false);
algorithmBrezenhem.setSelected(false);
algorithmDDA.setSelected(false);
algorithmCircle.setSelected(false);
algorithmParabola.setSelected(false);
algorithmBeze.setSelected(false);
algorithmBSpline.setSelected(false);
Coordinates.numberOfAlgorithm = 5;
}
});
algorithmZatravki.setText("Zatravka");
algorithmScan = new JCheckBoxMenuItem(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(algorithmScan.isSelected()){
algorithmScan.setSelected(false);
}
if(!algorithmScan.isSelected()){
algorithmScan.setSelected(true);
}
algorithmZatravki.setSelected(false);
algorithmBrezenhem.setSelected(false);
algorithmDDA.setSelected(false);
algorithmCircle.setSelected(false);
algorithmParabola.setSelected(false);
algorithmBeze.setSelected(false);
algorithmBSpline.setSelected(false);
Coordinates.numberOfAlgorithm = 5;
}
});
algorithmScan.setText("Scanning");
fill.add(algorithmZatravki);
fill.add(algorithmScan);
return fill;
} | 4 |
@Override
public boolean useItem(Player player, int type) {
Block block = Block.blocks[type];
if (block == Block.RED_MUSHROOM && minecraft.player.inventory.removeResource(type)) {
player.health += 4;
if (player.health > 30) {
player.health = 30;
}
return true;
} else if (block == Block.BROWN_MUSHROOM && minecraft.player.inventory.removeResource(type)) {
player.health += 4;
if (player.health > 15) {
player.health = 30;
}
return true;
} else {
return false;
}
} | 6 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OAuthToken)) return false;
OAuthToken that = (OAuthToken) o;
if (secretKeySpec != null ? !secretKeySpec.equals(that.secretKeySpec) : that.secretKeySpec != null)
return false;
if (!token.equals(that.token)) return false;
if (!tokenSecret.equals(that.tokenSecret)) return false;
return true;
} | 6 |
private Submission is_rankier( List<Submission> input ) {
if ( input.isEmpty() ) return null;
Submission winner = null;
for ( Submission s : input ) {
if ( winner == null ) {
winner = s;
}
else {
if ( s.card.rank() > winner.card.rank() ) {
winner = s;
}
}
}
return winner;
} | 4 |
public void warn(final String msg) {
if(disabled) return;
else logger.warning(msg);
// System.out.debug(route_name + "-" + connection_id + "[warn]: " + msg);
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(testingConnectionDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(testingConnectionDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(testingConnectionDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(testingConnectionDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new testingConnectionDatabase().setVisible(true);
}
});
} | 6 |
public int stepthrough(int i) {
switch(sim40.memory[i]) {
/* stop */
case 0: this.isProgramTerminated = true;
return i;
/* print, printb, printch */
case 1: case 2: case 3:
this.stdStream.getOutput().add(result(i));
++i;
break;
default:
/* jump, comp, xcomp, ycomp, jineg, jipos, jizero, jicarry */
if(sim40.memory[i] >= 19 && sim40.memory[i] <= 26)
i = compareExecute(i);
else if(sim40.memory[i] >= 4 && sim40.memory[i] <= 9)
i = unaryExecute(i);
else
i = binaryExecute(i);
}
checkResetAllRegsAndFlags();
sim40.updateViewVars();
sim40.memory[Simulator.PROGRAM_COUNTER] = i;
return i;
} | 8 |
private Vector<String> getNext() throws ServerException {
if (m_exhausted) return null;
try {
if (m_rs.next()) {
Vector<String> result = new Vector<String> ();
Integer recordKey = m_rs.getInt(1);
result.add(m_rs.getString(2));
Date d = new Date(m_rs.getLong(3));
try {
result.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(d));
} catch (Exception e) { // won't happen
e.printStackTrace();
}
ResultSet rs = null;
try {
String sql = "SELECT rcSet.setSpec from rcSet, rcMembership "
+ "WHERE rcMembership.recordKey = " + recordKey
+ " AND rcMembership.setKey = rcSet.setKey";
logger.debug("Executing query: " + sql);
rs = new_stmt.executeQuery(sql);
while (rs.next()) {
String setSpec = rs.getString(1);
result.add(setSpec);
}
} catch (SQLException e) {
throw new ServerException("Error determining set specs for record with a key : " + recordKey, e);
} finally {
if (rs != null) try { rs.close(); } catch (Exception e) { }
}
return result;
} else {
m_exhausted = true;
close(); // since we know it was exhausted
return null;
}
} catch (SQLException e) {
close(); // since we know there was an error
throw new ServerException("Error pre-getting next string from db", e);
}
} | 8 |
public static Collection getDatas(Collection result, ResultSet rs, Class clazz) {
try {
while (rs.next()) {
//创建类的实例
Object vo = clazz.newInstance();
//获取本对象的属性
Field[] fields = clazz.getDeclaredFields();
//获取父类的属性
// Field[] superFields = clazz.getSuperclass().getDeclaredFields();
// //父类的属性和自己的属性相加
// Field[] allFields = addFields(superFields, fields);
//遍历所有的属性
for (Field field : fields) {
//获得setter方法的方法名
String setterMethodName = getSetterMethodName(field.getName());
//获得setter方法
Method setterMethod = clazz.getMethod(setterMethodName, field.getType());
invokeMethod(rs, field, vo, setterMethod);
}
result.add(vo);
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
//throw new DataException(e.getMessage());
}
return result;
} | 3 |
private void search(int step){
searchCount++;
if(searchCount%100000==0){
System.out.println("Search count:"+searchCount);
}
int estimate=lowerBound(curPancakes);
if(step+estimate>curPancakes.size()*2) return;
if(isSorted(curPancakes) && step<minSwap){
minSwap=step;
finalResults=new ArrayList<Integer>();
swapResults=new ArrayList<Integer>();
for(int i:curPancakes){
finalResults.add(i);
}
for(int i=0;i<step;i++){
swapResults.add(steps.get(i));
}
return;
}
for(int i=1;i<curPancakes.size();i++){
reverse(curPancakes,i);
if(steps.size()>step)
steps.set(step, i);
else
steps.add(i);
search(step+1);
reverse(curPancakes,i);
}
} | 8 |
public void leavePercentageOutSplit(String filename, int percentage, boolean random) {
List<Bookmark> trainLines = new ArrayList<Bookmark>();
List<Bookmark> testLines = new ArrayList<Bookmark>();
Set<Integer> indices = new HashSet<Integer>();
int currentUser = -1, userIndex = -1, userSize = -1;
for (int i = 0; i < this.reader.getBookmarks().size(); i++) {
Bookmark data = this.reader.getBookmarks().get(i);
if (currentUser != data.getUserID()) { // new user
currentUser = data.getUserID();
userSize = this.reader.getUserCounts().get(currentUser);
userIndex = 1;
indices.clear();
int limit = (userSize - 1 < percentage ? userSize - 1 : percentage);
if (random) {
while (indices.size() < limit) {
indices.add(1 + (int)(Math.random() * ((userSize - 1) + 1)));
}
} else {
for (int index : getBestIndices(this.reader.getBookmarks().subList(i, i + userSize), false)) {
if (indices.size() < limit) {
indices.add(index);
} else {
break;
}
}
}
}
if (indices.contains(userIndex++)) {
testLines.add(data);
} else {
trainLines.add(data);
}
}
writeWikiSample(this.reader, trainLines, filename + "_train", null);
writeWikiSample(this.reader, testLines, filename + "_test", null);
trainLines.addAll(testLines);
writeWikiSample(this.reader, trainLines, filename, null);
} | 8 |
public EncryptionPropertiesType getEncryptionProperties() {
return encryptionProperties;
} | 0 |
@Override
public boolean containsAll(Collection<?> c) {
int count = 0;
for(Object o : c) {
if(this.contains(o)) {
count++;
}
}
if(count == c.size()) {
return true;
}
return false;
} | 4 |
@Override
public void quickPlay( boolean priority, boolean toStream, boolean toLoop,
String sourcename, FilenameURL filenameURL, float x,
float y, float z, int attModel, float distOrRoll,
boolean temporary )
{
SoundBuffer buffer = null;
if( !toStream )
{
// Grab the audio data for this file:
buffer = bufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( buffer == null )
{
if( !loadSound( filenameURL ) )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because an error occurred while loading "
+ filenameURL.getFilename() );
return;
}
}
// try and grab the sound buffer again:
buffer = bufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( buffer == null )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because audio data was not found for "
+ filenameURL.getFilename() );
return;
}
}
if( !toStream && buffer != null)
buffer.trimData( maxClipSize );
sourceMap.put( sourcename,
new SourceJavaSound( listener, priority, toStream,
toLoop, sourcename, filenameURL,
buffer, x, y, z, attModel,
distOrRoll, temporary ) );
} | 6 |
public String toString() {
String output = "suited: \n";
for (int i = 0; i < suitedPreFlop.length; i++) {
for (int j = 0; j < suitedPreFlop[i].length; j++) {
output += "\t" + suitedPreFlop[i][j];
}
output += "\n";
}
output += "\nunsuited: \n";
for (int i = 0; i < unsuitedPreFlop.length; i++) {
for (int j = 0; j < unsuitedPreFlop[i].length; j++) {
output += "\t" + unsuitedPreFlop[i][j];
}
output += "\n";
}
return output;
} | 4 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + bitsPerSample;
result = prime * result
+ (int) (frameDataStart ^ (frameDataStart >>> 32));
result = prime * result + Arrays.hashCode(md5);
result = prime * result + numChannels;
result = prime * result + numMetadataBlocks;
result = prime * result + (int) (numSamples ^ (numSamples >>> 32));
result = prime * result + sampleRateHz;
return result;
} | 0 |
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} | 8 |
private void fireDebuff()
{
int[] debuffList = getDebuffs();
ArrayList <Integer> numDebuffs = new ArrayList<Integer>();
for (int i = 0; i < debuffList.length; i++){
if (Math.random() <= Data.debuffChance[debuffList[i] ] ){
numDebuffs.add (debuffList[i]);
//add this to the weapon class
}
}
int[] fDL = new int [numDebuffs.size()];
for (int i = 0; i < fDL.length; i++){
fDL[i] = numDebuffs.get (i);
}
basicAttack.addDebuff(fDL, 1 );
} | 3 |
public void fillDialogFields(StockItem stockItem) {
if (stockItem != null) {
barCodeField.setText(stockItem.getId() + "");
getNameField().setText(stockItem.getName());
String priceString = String.valueOf(stockItem.getPrice());
priceField.setText(priceString);
} else {
reset();
}
} | 1 |
public String compareCountryRank(Stats previousStats)
{
if(previousStats == null)
return "";
if(previousStats.getCountryRank() < 1)
return "";
double delta = previousStats.getCountryRank() - getCountryRank();
if(delta == 0D)
return "";
return "<font color=" + (delta >= 0 ? "green" : "red") + ">(" + getArrow(delta) + NumberFormat.getInstance(Utils.locale).format(Math.abs(delta)) + ")</font>";
} | 4 |
public String getAsString(FacesContext context, UIComponent component,
Object value) {
if (context == null || component == null) {
throw new NullPointerException();
}
try {
// If the specified value is null, return a zero-length String
if (value == null) {
return "";
}
// If the incoming value is still a string, play nice
// and return the value unmodified
if (value instanceof String) {
return (String) value;
}
// Identify the Locale to use for formatting
Locale locale = getLocale(context);
// Create and configure the formatter to be used
NumberFormat formatter =
getNumberFormat(locale);
if (((pattern != null) && pattern.length() != 0)
|| "currency".equals(type)) {
configureCurrency(formatter);
}
configureFormatter(formatter);
// Perform the requested formatting
return (formatter.format(value));
} catch (ConverterException e) {
throw new ConverterException(MessageFactory.getMessage(
context, STRING_ID, value,
MessageFactory.getLabel(context, component)), e);
} catch (Exception e) {
throw new ConverterException(MessageFactory.getMessage(
context, STRING_ID, value,
MessageFactory.getLabel(context, component)), e);
}
} | 9 |
public static void set(int addr, int val) {
val &= 0xFF;
if (Util.inRange(addr, 0, 0x00EF)) { // Zero page
mem[addr] = val;
return;
} else if (Util.inRange(addr, 0x00F0, 0x00FF)) { // Function registers
writeReg(addr, val);
return;
} else if (Util.inRange(addr, 0x0100, 0x7FFF)) { // Sound RAM
mem[addr] = val;
return;
} else if (Util.inRange(addr, 0xFFC0, 0xFFFF)) { // IPL-ROM
if (!iplRomEnable) {
iplRam[addr - 0xFFC0] = val;
}
return;
}
if (Settings.isTrue(Settings.MEM_THROW_INVALID_ADDR))
throw new RuntimeException(String.format("APU: Write invalid memory address: 0x%04x",addr));
} | 6 |
public void zoomImage()
{
//For clarity of code, create some variables to hold slide dimensions
//and original image dimensions
int slideWidth = hostSize.width;
int slideHeight = hostSize.height;
int originalWidth = getMainImage().getWidth(null);
int originalHeight = getMainImage().getHeight(null);
//Determine maximum zoomed size on the basis of a maximum zoom factor
//of 2(to avoid excessive pixelation)
int maxWidth = 2*originalWidth;
int maxHeight = 2*originalHeight;
//Determine the overlap with the slide edges
//Positive value = magnitude of overlap
//Negative value (no overlap) = distance to slide edge from image edge
int xOverlap = maxWidth - slideWidth;
int yOverlap = maxHeight - slideHeight;
//The overlap with the greatest positive value defines the maximum scale
//factor since the image must not clip the slide edges.
double scaleFactor;
if(xOverlap > yOverlap)
scaleFactor = (double)slideWidth/originalWidth;
else
scaleFactor = (double)slideHeight/originalHeight;
//If neither are positive then resulting scale factor will be greater
//than 2. If so, set it to 2 (maximum)
if(scaleFactor > 2)
scaleFactor = 2;
//Instantiate variables zoomedSize and zoomedPosition if required
if(null == zoomedSize)
zoomedSize = new Dimension(0,0);
if(null == zoomedPosition)
zoomedPosition = new Point(0,0);
//Determine new width and height
zoomedSize.width = (int)(scaleFactor*originalWidth);
zoomedSize.height = (int)(scaleFactor*originalHeight);
//Determine new position
zoomedPosition.x = (int)(0.5*slideWidth - 0.5*zoomedSize.width);
zoomedPosition.y = (int)(0.5*slideHeight - 0.5*zoomedSize.height);
//Debug message to inform of new size and position of image
if(Debug.imagePlayer) System.out.println("Zoomed image will be drawn at ("+
zoomedPosition.x+","+zoomedPosition.y+") with dimensions "+
zoomedSize.width+" x "+zoomedSize.height);
//Hide the image panel whilst it is reconfigured for zoom mode
unDisplayInternal();
//Determine highest unoccupied layer of the slide panel
int topLayer = slidePanel.highestLayer() + 1;
//Promote the image panel to the top layer, so that no other object will
//obscure the image by displaying on top of it
slidePanel.remove(imagePanel);
slidePanel.add(imagePanel,new Integer(topLayer));
//Enlarge the image panel to completely fill the slide area
imagePanel.setSize(hostSize);
imagePanel.setLocation(0,0);
//Enable drawing to screen of the image panel, and make it black and
//semitransparent to provide slide darkening effect
imagePanel.setOpaque(true);
imagePanel.setBackground(new Color(0,0,0,127));
//Set flag to indicate that zoomed mode is now activated, and display
//the reconfigured image
isZoomed = true;
display();
//Update the mouse detection zone to match the new size of image panel
//updateMouseDetection(true,true);
} | 5 |
static void draw_sprites(osd_bitmap bitmap)
{
int offs;
if (zaxxon_vid_type == CONGO_VID)
{
int i;
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
/* Sprites actually start at 0xff * [0xc031], it seems to be static tho'*/
/* The number of active sprites is stored at 0xc032 */
for (offs = 0x1e * 0x20 ;offs >= 0x00 ;offs -= 0x20)
sprpri[ spriteram.read(offs+1) ] = offs;
for (i=0x1e ; i>=0; i--)
{
offs = sprpri[i];
if (spriteram.read(offs+2) != 0xff)
{
drawgfx(bitmap,Machine.gfx[2],
spriteram.read(offs+2+1)& 0x7f,
spriteram.read(offs+2+2),
spriteram.read(offs+2+2) & 0x80,spriteram.read(offs+2+1) & 0x80,
((spriteram.read(offs+2+3) + 16) & 0xff) - 31,255 - spriteram.read(offs+2) - 15,
Machine.drv.visible_area,TRANSPARENCY_PEN,0);
}
}
}
else if (zaxxon_vid_type == FUTSPY_VID)
{
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
for (offs = spriteram_size[0] - 4;offs >= 0;offs -= 4)
{
if (spriteram.read(offs) != 0xff)
{
drawgfx(bitmap,Machine.gfx[2],
spriteram.read(offs+1) & 0x7f,
spriteram.read(offs+2) & 0x3f,
spriteram.read(offs+1) & 0x80,spriteram.read(offs+1) & 0x80, /* ?? */
((spriteram.read(offs+3) + 16) & 0xff) - 32,255 - spriteram.read(offs) - 16,
Machine.drv.visible_area,TRANSPARENCY_PEN,0);
}
}
}
else
{
/* Draw the sprites. Note that it is important to draw them exactly in this */
/* order, to have the correct priorities. */
for (offs = spriteram_size[0] - 4;offs >= 0;offs -= 4)
{
if (spriteram.read(offs) != 0xff)
{
drawgfx(bitmap,Machine.gfx[2],
spriteram.read(offs+1) & 0x3f,
spriteram.read(offs+2) & 0x3f,
spriteram.read(offs+1) & 0x40,spriteram.read(offs+1) & 0x80,
((spriteram.read(offs+3) + 16) & 0xff) - 32,255 - spriteram.read(offs) - 16,
Machine.drv.visible_area,TRANSPARENCY_PEN,0);
}
}
}
} | 9 |
public static int[] loadSource(String filepath, int maxSources, boolean looping) {
// Load .wav data into a buffer.
int buffer = AL10.alGenBuffers();
int error = AL10.alGetError();
if(error != AL10.AL_NO_ERROR) {
System.err.println("Encountered AL error code " + error + "!");
System.exit(-1);
}
//Load .wav file
java.io.FileInputStream fin = null;
try {
fin = new java.io.FileInputStream(filepath);
} catch (java.io.FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
WaveData waveFile = WaveData.create(new BufferedInputStream(fin));
try {
fin.close();
} catch (java.io.IOException ex) {}
AL10.alBufferData(buffer, waveFile.format, waveFile.data, waveFile.samplerate);
waveFile.dispose();
int[] sources = new int[maxSources];
for (int i = 0; i < maxSources; i++) {
// Bind the buffer with the source.
sources[i] = AL10.alGenSources();
error = AL10.alGetError();
if(error != AL10.AL_NO_ERROR) {
System.err.println("Encountered AL error code " + error + "!");
System.exit(-1);
}
AL10.alSourcei(sources[i], AL10.AL_BUFFER, buffer );
AL10.alSourcef(sources[i], AL10.AL_PITCH, 1.0f );
AL10.alSourcef(sources[i], AL10.AL_GAIN, 1.0f );
AL10.alSource (sources[i], AL10.AL_POSITION, sourcePos);
AL10.alSource (sources[i], AL10.AL_VELOCITY, sourceVel);
if (looping)
AL10.alSourcei(sources[i], AL10.AL_LOOPING, AL10.AL_TRUE );
}
// Do another error check and return.
error = AL10.alGetError();
if(error != AL10.AL_NO_ERROR) {
System.err.println("Encountered AL error code " + error + "!");
System.exit(-1);
}
return sources;
} | 7 |
@Override
public void crearFichero(String ruta)
{
FileInputStream from = null;
FileOutputStream to = null;
File toFile = new File(ruta + this.getMetadato("nombre") + this.getMetadato("extension"));
try
{
from = new FileInputStream(this.audio);
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
}
catch (IOException e) {}
finally
{
if (from != null)
try {from.close();}
catch (IOException e) {}
if (to != null)
try {to.close();}
catch (IOException e) {}
}
} | 6 |
public List<String> getAllValidAliases()
{
List<String> list = new ArrayList<>();
for(String alias : backingMap.keySet())
{
list.add(alias);
}
for(String alias : aliasesMap.keySet())
{
if(aliasesMap.get(alias).valid())
{
list.add(alias);
}
}
return list;
} | 3 |
public final static boolean isLongOp(final Object obj0, final Object obj1) {
return (obj0 instanceof Long
|| obj1 instanceof Long
|| obj0 instanceof Integer
|| obj1 instanceof Integer
|| obj0 instanceof Character
|| obj1 instanceof Character
|| obj0 instanceof Short
|| obj1 instanceof Short
|| obj0 instanceof Byte
|| obj1 instanceof Byte);
} | 9 |
public boolean moveEast(int w)
{
boolean moved = false;
if(isFighting==false && isConcious() && getEnergy()>0)
{
if(w==3 || w==4)
{
setX(getX()+1);
moved = true;
}
else if(w>=10)
{
updateLocationInfoForEnteringABuilding(w);
}
else if(w==5)
{
updateLocationInfoForExitingABuilding();
}
setLastMoveDirection("east");
}
return moved;
} | 7 |
public static String toLanguageTag(Locale locale) {
return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
} | 1 |
public Release calculateDelta(File aTopTempDir, File aTempXmlDir,
File aTempMD5Dir) throws Exception
{
int nbDeleted = 0;
int nbCreated = 0;
int nbModified = 0;
// create a temp release
File releaseTempDir = FileSystem.createTempDirectory("release-",
aTopTempDir);
Release tempRelease = Release.createRelease(releaseTempDir);
Release latestRelease = m_ReleaseDB.getLatestRelease();
// copy the SOURCE Part of Release
tempRelease.addInSrcMD5s(aTempMD5Dir);
tempRelease.addInSrcXmls(aTempXmlDir);
// No previous Release so all origin XML files go into Delta Result and
// there are no deleted files
if (latestRelease == null)
{
// Copy XML into Delta/Result
tempRelease.addInDeltaResult(aTempXmlDir);
for (String filename : tempRelease.getDeltaXmlFilenames())
{
this.cleverPrinting(Release.getIDFromReleaseFile(filename)
+ " metadata is new.", nbCreated);
nbCreated++;
}
}
else
{
// get list of previous MD5s and the list of current MD5s
HashMap<String, Pair<String, String>> prev = latestRelease
.getSrcMD5s();
HashMap<String, Pair<String, String>> curr = tempRelease
.getSrcMD5s();
Set<String> currSet = new HashSet<String>();
Set<String> deletedSet = new HashSet<String>();
Set<String> newSet = new HashSet<String>();
/*
* calculate the delta It is important to understand that the UID is
* the MD_Metadata.fileidentifier and not the filename. Several
* modifications of the same metadata in the Release are not handled
* properly here (this should not happen but). algorithm: for
* elemOld in old: if elemOld not in new: add in deletedSet if
* elemOld in new and elemOld.md5 != elemNew.md5: add in newSet
*
* remove elemOld from currSet
*
* All elem left in currSet are the new ones and must be added in
* newSet newSet.add(currSet);
*/
// copy curr keys in currSet
currSet.addAll(curr.keySet());
for (String key : prev.keySet())
{
if (!curr.containsKey(key))
{
deletedSet.add(key);
}
else
{
if (!prev.get(key).equals(curr.get(key)))
{
// md5 different so the file has been updated
logger.debug(
"MD5 Differents for {}. old:[{}], new:[{}]",
new String[] { key, prev.get(key).getKey(),
curr.get(key).getKey() });
this.cleverPrinting(key
+ " metadata has been modified.", nbModified);
nbModified++;
// add in newSet because it has been modified
newSet.add(key);
}
// remove from currSet in any case
currSet.remove(key);
}
}
// elems left in currSet are new and need to be added to newSet
newSet.addAll(currSet);
// print elems left in currSet which are the new ones
for (String name : currSet)
{
this.cleverPrinting(name + " metadata is new.", nbCreated);
nbCreated++;
}
String basename;
// copy newSet in Delta/Files
for (String name : newSet)
{
// add files in Results and their MD5s in MD5
// get the basename from curr HashMap
basename = curr.get(name).getValue();
tempRelease.addFileInDeltaResult(new File(aTempXmlDir
+ File.separator + basename + ".xml"));
}
// add files in deleted
for (String name : deletedSet)
{
this.cleverPrinting(name + " metadata has been deleted.",
nbDeleted);
nbDeleted++;
tempRelease.flagAsDeleted(name);
}
}
if (nbCreated + nbModified + nbDeleted != 0)
{
logger
.info("Delta Summary: " + nbCreated + " new - "
+ nbModified + " modified - " + nbDeleted
+ " deleted.");
}
return tempRelease;
} | 9 |
@Override
public String[] getTableRenameStatements(String oldTableName,Class<?>oldClass, String newTableName,Class<?>newClass)
{
String [] res = new String[2];
res[0] = "CREATE TABLE "+newTableName+" AS SELECT * FROM " +oldTableName+" WITH DATA";
res[1] = "DROP TABLE " + oldTableName;
return res;
} | 2 |
public static int getSailplaneTensionUnit() throws ClassNotFoundException {
int weightUnit = 0;
try{
//Class derbyClass = RMIClassLoader.loadClass("lib/", "derby.jar");
Class.forName(driverName);
Class.forName(clientDriverName);
}catch(java.lang.ClassNotFoundException e) {
throw e;
}
try (Connection connect = DriverManager.getConnection(databaseConnectionName)) {
Statement stmt = connect.createStatement();
ResultSet thePilots = stmt.executeQuery("SELECT tension_unit "
+ "FROM SailplaneUnits "
+ "WHERE unit_set = 0");
while(thePilots.next()) {
try {
weightUnit = Integer.parseInt(thePilots.getString(1));
}catch(NumberFormatException e) {
//TODO What happens when the Database sends back invalid data
JOptionPane.showMessageDialog(null, "Number Format Exception in reading from DB");
}
}
thePilots.close();
stmt.close();
}catch(SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return -1;
}
return weightUnit;
} | 4 |
private boolean isWhitespace( int v ) {
return ( v == 0x20 || v == 0x09 || v == 0x0A || v == 0x0D );
} | 3 |
@Override
protected boolean doStep() {
double minDeltaCost = Double.MAX_VALUE;
Move11 bestMove = null;
boolean moveFound = false;
Set<Move11> moves = generator.getMoves();
for (Move11 move : moves) {
if (move.getDeltaCost() < minDeltaCost &&
move.getDeltaInfIndex() == 0) {
/* new move candidate */
bestMove = move;
minDeltaCost = move.getDeltaCost();
moveFound = true;
}
}
if (moveFound && minDeltaCost < - 0.1) {
generator.apply(bestMove);
setBestSolution(solution);
return true;
}
return false;
} | 5 |
public ConfigurationSection getConfigurationSection(String path) {
Object val = get(path, null);
if (val != null) {
return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
}
val = get(path, getDefault(path));
return (val instanceof ConfigurationSection) ? createSection(path) : null;
} | 3 |
public static boolean copyFile(File from, File to, byte[] buf) {
if (buf == null) buf = new byte[BUFFER_SIZE];
FileInputStream from_s = null;
FileOutputStream to_s = null;
try {
from_s = new FileInputStream(from);
to_s = new FileOutputStream(to);
for(int bytesRead = from_s.read(buf); bytesRead > 0; bytesRead = from_s.read(buf)) {
to_s.write(buf, 0, bytesRead);
}
to_s.getFD().sync();
} catch (IOException ioe) {
return false;
} finally {
if (from_s != null) {
try {
from_s.close();
from_s = null;
} catch (IOException ioe) {
}
}
if (to_s != null) {
try {
to_s.close();
to_s = null;
} catch (IOException ioe) {
}
}
}
return true;
} | 7 |
public static void main(String[] args)
{
File dictionary = null;
File document = null;
String option = "";
if(args.length < 2 || args.length > 3)
{
System.out.println("Incorrect number of arguments!");
return;
}
dictionary = new File(args[0]);
if(!dictionary.isFile()){
System.out.println("Unable to use the dictionary file!");
return;
}
document = new File(args[1]);
if(!document.isFile()){
System.out.println("Unable to use the document file!");
return;
}
// If a third parameter was passed for the options, check its validity
if (args.length == 3)
if(args[2].equalsIgnoreCase("-p") || args[2].equalsIgnoreCase("-f"))
option = args[2];
else
{
System.out.println("Invalid printing or filing option argument!");
return;
}
// Passing the dictionary file, document file, and the option
run_spell_check(dictionary, document, option);
} | 7 |
public void connect() throws IOException {
if (level != 0) // otherwise disconnected or connect
throw new SocketException("Socket closed or already open ("+ level +")");
IOException exception = null;
Socket s = null;
for (int i = 0; i < ports.length && s == null; i++) {
try {
s = new Socket(host, ports[i]);
exception = null;
} catch (IOException exc) {
if (s != null)
s.close();
s = null;
exception = exc;
}
}
if (exception != null)
throw exception; // connection wasn't successful at any port
prepare(s);
} | 6 |
public static boolean getKeyUp(int keyCode)
{
return !getKey(keyCode) && lastKeys[keyCode];
} | 1 |
public static void boostByMarketingTagMatch(ScoredSolrDoc doc, String keyword, float boost) {
if (doc == null || keyword == null)
return;
if (boost <= 0)
boost = 5.0f;
List<String> keywordList = StringUtil.stringToStringList(keyword, "[ ]");
int keywordCount = keywordList.size();
// to keep the maximum boost = boost, scale down the boost by number of words in the keyword
if (keywordCount > 0)
boost /= (float)keywordCount;
else
return;
String marketingTag = doc.getFieldValue(SolrUtil.INDEX_FIELD_MARKETING_TAG);
if (marketingTag == null || marketingTag.length() == 0)
return;
List<String> tagList = StringUtil.stringToStringList(marketingTag, "[ ]");
int tagCount = tagList.size();
// compare the last words between marketing tag and keywords
int compareSize = (keywordCount < tagCount) ? keywordCount : tagCount;
for (int i = 0; i < compareSize; i++) {
if (StringUtil.wordMatch(keywordList.get(keywordCount - 1 - i), tagList.get(tagCount - 1 - i))) {
doc.boostScore(boost);
} else {
// do not continue matching if a non-match already found
break;
}
}
} | 9 |
public static final boolean method983(int z, int x, int y) {
int l = Canvas_Sub1.anIntArrayArrayArray52[z][x][y];
if (l == -Class142_Sub10.anInt3361) {
return false;
}
if (l == Class142_Sub10.anInt3361) {
return true;
}
int i1 = x << 7;
int j1 = y << 7;
if (Class67.method731(i1 + 1, Class106.groundHeights[z][x][y], j1 + 1)
&& Class67.method731((i1 + 128) - 1, Class106.groundHeights[z][x + 1][y], j1 + 1)
&& Class67.method731((i1 + 128) - 1, Class106.groundHeights[z][x + 1][y + 1], (j1 + 128) - 1)
&& Class67.method731(i1 + 1, Class106.groundHeights[z][x][y + 1], (j1 + 128) - 1)) {
Canvas_Sub1.anIntArrayArrayArray52[z][x][y] = Class142_Sub10.anInt3361;
return true;
} else {
Canvas_Sub1.anIntArrayArrayArray52[z][x][y] = -Class142_Sub10.anInt3361;
return false;
}
} | 6 |
private void changeValueRandomly(Random r, int numOfValues,
int indexOfAtt,
Instance instance,
boolean useMissing) {
int currValue;
// get current value
// if value is missing set current value to number of values
// whiche is the highest possible value plus one
if (instance.isMissing(indexOfAtt)) {
currValue = numOfValues;
} else {
currValue = (int) instance.value(indexOfAtt);
}
// with only two possible values it is easier
if ((numOfValues == 2) && (!instance.isMissing(indexOfAtt))) {
instance.setValue(indexOfAtt, (double) ((currValue+1)% 2));
} else {
// get randomly a new value not equal to the current value
// if missing values are used as values they must be treated
// in a special way
while (true) {
int newValue;
if (useMissing) {
newValue = (int) (r.nextDouble() * (double) (numOfValues + 1));
} else {
newValue = (int) (r.nextDouble() * (double) numOfValues);
}
// have we found a new value?
if (newValue != currValue) {
// the value 1 above the highest possible value (=numOfValues)
// is used as missing value
if (newValue == numOfValues) { instance.setMissing(indexOfAtt); }
else { instance.setValue(indexOfAtt, (double) newValue); }
break;
}
}
}
} | 7 |
private void paintEnemyPath(Graphics2D g2, Iterable<Point> enemyPath) {
g2.setColor(Color.gray);
for (Point currentGridPoint : enemyPath) {
g2.fill(new Rectangle(GlobalPositioning.getXPixel(currentGridPoint.getX()), GlobalPositioning.getYPixel(currentGridPoint.getY()),
Board.getSquareWidth(), Board.getSquareHeight()));
}
} | 1 |
public static String getModifierKeyText() {
boolean isMac = (System.getProperty("os.name").startsWith("Mac"));
String text = "";
if ((MENU_SHORTCUT_KEY_MASK & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
text = "Shift";
}
if ((MENU_SHORTCUT_KEY_MASK & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
if (text.length() > 0) {
text += '+';
}
text = "Ctrl";
}
if ((MENU_SHORTCUT_KEY_MASK & InputEvent.ALT_MASK) == InputEvent.ALT_MASK) {
if (text.length() > 0) {
text += '+';
}
text = isMac ? "Opt" : "Alt";
}
if ((MENU_SHORTCUT_KEY_MASK & InputEvent.META_MASK) == InputEvent.META_MASK) {
if (text.length() > 0) {
text += '+';
}
text = isMac ? "Cmd" : "Meta";
}
return text;
} | 9 |
public void setNextMessage() {
try{
clearMessageBoard();
message1 = message[currentMessageIndex].substring(0,message[currentMessageIndex].length() > 40 ? 40 : message[currentMessageIndex].length());
message2 = message[currentMessageIndex].length() > 40?message[currentMessageIndex].substring(40,message[currentMessageIndex].length()) : "";
}catch(ArrayIndexOutOfBoundsException e){
setVisible(false);
}
currentMessageIndex++;
} | 3 |
private static TobiiHeader readHeader(CSVReader reader) throws IOException {
TobiiHeader header = new TobiiHeader();
//
// SYSTEM PROPERTIES section
String line[] = reader.readNext();
assert(line[0].equalsIgnoreCase("System Properties:"));
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Operating System:"));
header.setSysOS(line[1]);
line = reader.readNext();
assert(line[0].equalsIgnoreCase("System User Name:"));
header.setSysUser(line[1]);
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Machine Name:"));
header.setSysMachine(line[1]);
//
// DATA PROPERTIES section
reader.readNext();
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Data Properties:"));
//
// RECORDING section
reader.readNext();
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Recording name:"));
if(!line[1].isEmpty()) {
header.setRecName(line[1]);
} else if(!line[2].isEmpty()) {
header.setRecName(line[2]);
}
// Date and Time of the recording in Tobii. We combine these into one Date
// Formatted as, e.g., "6/24/2011" and "11:42:32 AM"
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Recording date:"));
String recDateStr = line[1].trim();
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Recording time:"));
String recTimeStr = line[1].trim();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
try {
Date recDateTime = dateFormat.parse(recDateStr + " " + recTimeStr);
header.setRecDateTime(recDateTime);
header.setRecDateTimestamp(recDateTime.getTime());
} catch(ParseException e) {
System.err.println("Had trouble parsing the date/times in a Tobii header file. Non-fatal.");
System.err.println("Date string: " + recDateStr + "\t\tTime string: " + recTimeStr);
}
// Resolution at which the Tobii experiment was recorded
// Formatted as string, e.g., "1024 x 768"
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Recording resolution:"));
String[] recResolutionStr = line[1].trim().split(" ");
int width = Double.valueOf(recResolutionStr[0]).intValue();
int height = Double.valueOf(recResolutionStr[2]).intValue();
header.setRecResolution(new Dimension(width, height));
// Newer version of Tobii also reports screen size in millimeters;
// older versions skip straight to the export section (added Feb. 2012)
line = reader.readNext();
if(line.length > 1) {
assert(line[0].equalsIgnoreCase("Recording screen size in millimeter:"));
String[] screenSizeStr = line[1].trim().split(" ");
double widthMM = Double.valueOf(screenSizeStr[0]).doubleValue();
double heightMM = Double.valueOf(screenSizeStr[2]).doubleValue();
header.setScreenSizeMM(new Rectangle2D.Double(0,0,widthMM, heightMM));
reader.readNext();
}
//
// EXPORT section
// Date and Time of the recording in Tobii. We combine these into one Date
// Formatted as, e.g., "6/24/2011" and "11:42:32 AM"
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Export date:"));
String exportDateStr = line[1].trim();
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Export time:"));
String exportTimeStr = line[1].trim();
try {
Date exportDateTime = dateFormat.parse(exportDateStr + " " + exportTimeStr);
header.setExportDateTime(exportDateTime);
} catch(ParseException e) {
System.err.println("Had trouble parsing the date/times in a Tobii header file. Non-fatal.");
System.err.println("Date string: " + exportDateStr + "\t\tTime string: " + exportTimeStr);
}
//
// PARTICIPANT section
reader.readNext();
line = reader.readNext();
assert(line[0].equalsIgnoreCase("Participant:"));
header.setParticipant(line[1]);
return header;
} | 5 |
@PersistenceContext
public void setEm(EntityManager em) {
this.em = em;
} | 0 |
private void initCharacterFlowPane() {
ColorUtil picker = new ColorUtil();
for (int k = 0; k < 10; k++) {
FlowPane content = new FlowPane();
TitledPane tPane = new TitledPane();
tPane.setText("Test_" + k);
/**
* Add content *
*/
for (int i = 0; i < 10; i++) {
Image image = new Image(getClass().getResourceAsStream("Mario.png"), 150, 200, true, false);
Button button = new Button("", new ImageView(image));
content.getChildren().add(button);
}
content.setHgap(5);
content.setVgap(5);
content.setStyle(picker.pickNext());
content.prefWrapLengthProperty().bind(characterScrollPane.widthProperty());
tPane.prefWidthProperty().bind(characterScrollPane.widthProperty());
tPane.setContent(content);
tPane.setExpanded(false);
characterContentFlowPane.getChildren().add(tPane);
}
} | 2 |
public static boolean isSupportedOutputFormatType(String format, String type)
{
if (!isSupportedOutputFormat(format))
{
return false;
}
if (format == ThumbnailParameter.ORIGINAL_FORMAT
&& type == ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return true;
}
else if (format == ThumbnailParameter.ORIGINAL_FORMAT
&& type != ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return false;
}
else if (type == ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return true;
}
for (String supportedType : getSupportedOutputFormatTypes(format))
{
if (supportedType.equals(type))
{
return true;
}
}
return false;
} | 8 |
static final int method1812(int i) {
anInt2122++;
if (Class213.aBoolean2510) {
return 6;
}
if (i != 5) {
LOCAL_PLAYERS_INDEXES_COUNT = -106;
}
if (Node_Sub38_Sub23.aCacheNode_Sub13_10343 == null) {
return 0;
}
int i_5_ = Node_Sub38_Sub23.aCacheNode_Sub13_10343.anInt9562;
if (Class251.method3101(i_5_, (byte) -62)) {
return 1;
}
if (Class134.method1574(false, i_5_)) {
return 2;
}
if (Class194_Sub3.method1973(i_5_, 31922)) {
return 3;
}
if (OutcommingPacket.method3666(i_5_, (byte) 112)) {
return 4;
}
if (Class262_Sub2.method3155(i_5_, (byte) -18)) {
return 7;
}
if (i_5_ == 4) {
return 8;
}
return 5;
} | 9 |
private List expand(List symbols) {
if (contexts == null)
return expandNoContext(symbols);
return expandContext(symbols);
} | 1 |
static public TreeMap<Integer, TreeSet<Integer> > graphBuilder(String fichierTexte)
{
TreeMap<Integer, TreeSet<Integer> > tmpNoeuds = new TreeMap<Integer, TreeSet<Integer> >();
StringTokenizer tokenizer = new StringTokenizer(fichierTexte);
while (tokenizer.hasMoreTokens()) {
Integer token = Integer.parseInt(tokenizer.nextToken());
Integer token1 = Integer.parseInt(tokenizer.nextToken());
ajouterNoeud(token,token1,tmpNoeuds);
}
return tmpNoeuds;
} | 1 |
public static boolean isDouble(String DBL)
{
if (DBL.length() == 0)
return false;
if (DBL.startsWith("-") && (DBL.length() > 1))
DBL = DBL.substring(1);
boolean alreadyDot = false;
for (int i = 0; i < DBL.length(); i++)
{
if (!Character.isDigit(DBL.charAt(i)))
{
if (DBL.charAt(i) == '.')
{
if (alreadyDot)
return false;
alreadyDot = true;
}
else
return false;
}
}
return alreadyDot;
} | 7 |
@Override
public void addMedia(String name, String year, String genre,
Object[] objects, int duration, int mediaType) throws SQLException {
CallableStatement stMedia = null;
CallableStatement stCreator = null;
try {
connection.setAutoCommit(false);
//parameters: username, password, name, year, genre, duration, type
String sql = "{call AddMedia(?, ?, ?, ?, ?, ?, ?, ?)}";
stMedia = connection.prepareCall(sql);
stMedia.setString(1, model.getUser());
stMedia.setString(2, model.getPass());
stMedia.setString(3, name);
stMedia.setString(4, year);
stMedia.setString(5, genre);
stMedia.setInt(6, duration);
stMedia.setInt(7, mediaType);
// returns the PK of the newly added media item, required when adding creators.
stMedia.registerOutParameter(8, java.sql.Types.INTEGER);
stMedia.execute();
// parameters: username, password, creator name, mediaId
// the stored procedure will create a creator if not exists.
sql = "{call AddCreator(?, ?, ?, ?)}";
stCreator = connection.prepareCall(sql);
for (int i = 0; i < objects.length; i++) {
stCreator.setString(1, model.getUser());
stCreator.setString(2, model.getPass());
stCreator.setString(3, objects[i].toString());
stCreator.setInt(4, stMedia.getInt(8));
stCreator.execute();
}
connection.commit();
}
catch (SQLException e)
{
connection.rollback();
throw e;
}
finally {
connection.setAutoCommit(true);
closeStatement(stMedia);
closeStatement(stCreator);
}
// run last search query again, to display the added media.
rebootDataSet();
} | 2 |
@Override
public void mouseMoved(MouseEvent e) {
if (state == 0) {
if (e.getX() > getWidth() / 2 + 16) {
user.setFacingRight(true);
} else {
user.setFacingRight(false);
}
if (user.getInHand() instanceof ProjectileShooter)
if (user.isFacingRight())
((ProjectileShooter) user.getInHand()).setrAngle(
Math.atan2(e.getY() - getHeight() / 2 - 32 * zoom, e.getX() - getWidth() / 2 - 16 * zoom));
else
((ProjectileShooter) user.getInHand()).setrAngle(
Math.atan2(e.getY() - getHeight() / 2 - 32 * zoom, e.getX() - getWidth() / 2 - 16 * zoom)
- Math.PI);
}
} | 4 |
private void refFtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refFtActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_refFtActionPerformed | 0 |
public boolean equals(Network A){
boolean result = true;
if(numNodes == A.getNumNodes()){
for(int i=0; i<numNodes; i++){
if(!Arrays.equals(nodes.get(i).getInputs(), A.getNodes().get(i).getInputs())){
result = false;
}
}
}
else{
result = false;
}
return result;
} | 3 |
@Override
public void documentAdded(DocumentRepositoryEvent e) {} | 0 |
public int step()
{
boolean found=false;
boolean growth=false;//used to check growth of the search
GridCell goal = GridCell.getgoalCell();
@SuppressWarnings("unchecked")
Vector<GridCell> temp = (Vector<GridCell>) edge.clone();
for(int i=0;i<temp.size();i++)//runs as many times as the edge vector
{
GridCell now = (GridCell)temp.elementAt(i);
GridCell next[] = map.getsurrounding(now);//creates an array of cells around the now cell
for(int j=0;j<8;j++)//runs 8 times, once for each cell int he array
{
if(next[j]!=null )//checks for emptyness
{
if(next[j]==goal)//checks if for goal node
{
found=true;
}
next[j].addToPathFromStart(now.getDistFromStart());//adds to path with distance
if(!next[j].isblock() && !edge.contains(next[j]))//if the cell isnt in either its added to edge and growth set to true
{
edge.addElement(next[j]);
growth=true;
}
}
}
if(found)
{
return FOUND;
}
searched.addElement(now);
}
map.repaint();
if(!growth)//if growth isnt set to true the algorithms cannot continue
{
return NO_PATH;
}
return NOT_FOUND;
} | 8 |
private static void copyPri(File inputFile, File outputFile,
boolean isOverWrite) throws IOException {
// 是个文件。
if (inputFile.isFile()) {
copySimpleFile(inputFile, outputFile, isOverWrite);
} else {
// 文件夹
if (!outputFile.exists()) {
outputFile.mkdir();
}
// 循环子文件夹
for (File child : inputFile.listFiles()) {
copy(child,
new File(outputFile.getPath() + "/" + child.getName()),
isOverWrite);
}
}
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.