text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void read(){
try {
FileInputStream fis1;
fis1 = new FileInputStream("Datas/AccountPO.out");
FileInputStream fis2 = new FileInputStream("Datas/CollectionOrPaymentPO.out") ;
FileInputStream fis3 = new FileInputStream("Datas/CashPO.out");
if(fis1.available()>0 ){
ObjectInputStream oin1 ;
oin1 = new ObjectInputStream(fis1);
accounts=(ArrayList<AccountPO>)oin1.readObject();
}
if(fis2.available()>0){
ObjectInputStream oin2 = new ObjectInputStream(fis2) ;
cpReceipts = (ArrayList<CollectionOrPaymentPO>)oin2.readObject() ;
}
if(fis3.available()>0){
ObjectInputStream oin3 = new ObjectInputStream(fis3) ;
cashReceipts = (ArrayList<CashPO>)oin3.readObject() ;
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
public void actionPerformed(ActionEvent ae) {
double x = 0.0, y = 0.0;
Double d;
try {
d = new Double(eastings.getText());
x = d.doubleValue();
} catch (NumberFormatException nfe) {
eastings.setText("0");
x = 0.0;
}
try {
d = new Double(northings.getText());
y = d.doubleValue();
} catch (NumberFormatException nfe) {
northings.setText("0");
y = 0.0;
}
DPoint p0 = new DPoint(x, y);
String pfxs = prefix.getSelectedItem();
DPoint dp = osni.GridSquareToOffset(pfxs.charAt(0));
dp.offsetBy(p0);
DPoint p = osni.GridToLongitudeAndLatitude(dp);
double phi, lambda;
lambda = (180.0 / Math.PI) * p.getX();
phi = (180.0 / Math.PI) * p.getY();
double ls = Math.abs(lambda);
double ps = Math.abs(phi);
int ld, lm, pd, pm;
ld = (int) ls;
ls = 60.0 * (ls - ld);
lm = (int) ls;
ls = 60.0 * (ls - lm);
pd = (int) ps;
ps = 60.0 * (ps - pd);
pm = (int) ps;
ps = 60.0 * (ps - pm);
String str = ld + "\u00b0 " + lm + "\' " + myFormat.format(ls) + "\""
+ ((lambda < 0.0) ? " West" : " East");
latitude.setText(str);
str = pd + "\u00b0 " + pm + "\' " + myFormat.format(ps) + "\""
+ ((phi < 0.0) ? " South" : " North");
longitude.setText(str);
str = pfxs + " " + myFormat.format(p0.getX()) + " "
+ myFormat.format(p0.getY());
gridinput.setText(str);
} | 4 |
public void dropCourseFromAll(String course) {
if (root == null) {
System.out.println("Roster is empty, can't drop course " + course);
return;
}
Queue<StudentNode> queue = new LinkedList<StudentNode>();
queue.add(root);
while (queue.size() != 0) {
StudentNode temp = queue.remove();
if (temp.courses.contains(course)) {
temp.courses.remove(course);
}
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
} | 5 |
public void run() {
int counter = 0;
while (!maze.allRatsOnTarget()
&& counter < maze.getMaxSimulationStep()) {
for (MazeRat rat : maze.getRats()) {
if (!maze.isRatOnTarget(rat))
rat.performStep();
}
mazePanel.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
}
System.out.println("Finished simulation!");
if (maze.allRatsOnTarget()) {
System.out.println("Rats finished! It took " + counter
+ " steps");
} else {
System.out.println("Rats failed");
}
} | 6 |
@Override
public <Y> Y convert(IntNode node, Class<Y> cls) {
if (Object.class.equals(cls) || Number.class.equals(cls)) {
cls = (Class<Y>) Long.class;
} else if (cls.isPrimitive()) {
cls = (Class<Y>) WRAPPERS.get((Class<? extends Number>) cls);
if (cls == null) {
throw new BencDeserializer.DeserializationException(
"Number should be deserialized to numeric primitive field");
}
}
if (!Number.class.isAssignableFrom(cls)) {
throw new BencDeserializer.DeserializationException(
"Number should be deserialized to numeric field");
}
String val = Long.toString(node.getValue());
try {
Constructor c = cls.getConstructor(String.class);
return (Y) c.newInstance(val);
} catch (NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new BencDeserializer.DeserializationException(
"Unexpected error: " + e);
}
} | 7 |
@Override
public void run()
{
if(!EntityConcentrationMap.isRunning())
mPlugin.runGroups(false);
} | 1 |
protected void closeStatements(String Closer)
{
try
{
if(!Closer.equals(""))
{
if(myStatement!=null)
{
lastSQL=Closer;
lastQueryTime=System.currentTimeMillis();
myStatement.executeUpdate(Closer);
}
}
if(myResultSet!=null)
{
myResultSet.close();
myResultSet=null;
}
if(myPreparedStatement!=null)
{
myPreparedStatement.close();
myPreparedStatement=null;
}
if(myStatement!=null)
{
myStatement.close();
myStatement=null;
}
if(myConnection!=null)
{
if(!myConnection.getAutoCommit())
myConnection.commit();
}
}
catch(final SQLException e)
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SQLERRORS))
{
Log.errOut("DBConnection",e);
}
// not a real error?
}
} | 9 |
public void test_collapseZeroGap() {
initRand();
int numMarkers = 20;
Chromosome chr = genome.getChromosome("1");
for (int num = 1; num < 1000; num++) {
// Create markers
Tuple<Markers, Markers> tupleMarkers = createMarkers(chr, numMarkers);
Markers markersOri = tupleMarkers.first;
Markers markersCollapsedOri = tupleMarkers.second;
//---
// Compare created markers
//---
String mStr = markers2string(markersOri);
String mColOriStr = markers2string(markersCollapsedOri);
if (verbose) Gpr.debug("Iteration : " + num + "\n\tMarkers : " + mStr + "\n\tMarkers collapsed : " + mColOriStr);
// Are generated intervasl OK?
if (!mStr.equals(mColOriStr)) {
System.err.println("Markers : ");
for (Marker m : markersOri)
System.err.println(m);
System.err.println("Markers collapsed: ");
for (Marker m : markersCollapsedOri)
System.err.println(m);
throw new RuntimeException("Error creating markers! Markers and collapsed marker do not match!\n\t" + mStr + "\n\t" + mColOriStr);
}
//---
// Compare to Markers.collapseZeroGap
//---
// Collapse
Map<Marker, Marker> collapse = MarkerUtil.collapseZeroGap(markersOri);
// Get unique markers
HashSet<Marker> collapsed = new HashSet<Marker>();
collapsed.addAll(collapse.values());
Markers markers = new Markers();
markers.addAll(collapsed);
String mColStr = markers2string(markers); // Create string
// Are generated intervasl OK?
if (!mColStr.equals(mStr)) {
Gpr.debug("Error checing markers! Markers and collapsed marker do not match!\n\t" + mStr + "\n\t" + mColStr);
System.err.println("Markers : ");
for (Marker m : markersOri)
System.err.println(m);
System.err.println("Markers collapsed: ");
markers = new Markers();
markers.addAll(collapse.keySet());
Markers keySorted = markers.sort(false, false);
for (Marker mkey : keySorted)
System.err.println(mkey + "\t->\t" + collapse.get(mkey));
throw new RuntimeException("Error checing markers! Markers and collapsed marker do not match!\n\t" + mStr + "\n\t" + mColStr);
}
}
} | 8 |
public void testRemoveBadIndex2() {
Converter[] array = new Converter[] {
c1, c2, c3, c4,
};
ConverterSet set = new ConverterSet(array);
try {
set.remove(-1, null);
fail();
} catch (IndexOutOfBoundsException ex) {}
assertEquals(4, set.size());
} | 1 |
public static void main(String[] args) {
int width = 20;
int height = width;
Node[][] grid = new Node[width + 1][height + 1];
for (int y = 0; y <= height; y++) {
for (int x = 0; x <= width; x++) {
Node left = null;
Node above = null;
if (x > 0) {
left = grid[x - 1][y];
}
if (y > 0) {
above = grid[x][y - 1];
}
grid[x][y] = new Node(x, y, left, above);
}
}
Node start = grid[width][height];
System.out.println(start.getPathCount());
} | 4 |
public Grid(int x, int y){
boolean test = false;
if (test || m_test) {
System.out.println("Grid :: Grid() BEGIN");
}
setGrid(new Game.PlayerTurn[x][y]);
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
setCoordinate(new Coordinate(i, j, Game.PlayerTurn.NONE));
if (test || m_test) {
System.out.println("Grid :: Grid() END");
}
}
}
} | 6 |
private void adjustVolume(IAudioSamplesEvent event) {
ShortBuffer buffer = event.getAudioSamples().getByteBuffer().asShortBuffer();
for (int i = 0; i < buffer.limit(); ++i) {
buffer.put(i, (short) (buffer.get(i) * volumeScale));
}
} | 1 |
@Override
public MoveResult makeMove(HantoPieceType pieceType, HantoCoordinate from,
HantoCoordinate to) throws HantoException {
MoveResult result;
HantoPlayerColor color;
// use copy constructor on given HantoCoordinates
PieceCoordinate newFrom = from == null? null : new PieceCoordinate(from);
PieceCoordinate newTo = to == null? null : new PieceCoordinate(to);
validateMove(pieceType, newFrom, newTo);
if (turnCount % 2 == 0) { // if the turn count is even - blue should go
color = HantoPlayerColor.BLUE;
}
else { // turn count is odd - red should go
color = HantoPlayerColor.RED;
}
Butterfly butterfly = new Butterfly(color);
board.addPiece(newTo, butterfly);
turnCount++;
if (turnCount == 2) { // Alpha Hanto ends after turn 2
result = MoveResult.DRAW;
}
else {
result = MoveResult.OK;
}
return result;
} | 4 |
public void initGraphicData() {
final int W = 200;
final int H = 100;
boolean changed = false;
int x = 10;
int y = 10;
if (x < 0) x = 0;
if (y < 0) y = 0;
for (int i = 0; i < nodeList.size(); i++) {
y = y + H + 10;
Rectangle rect = new Rectangle(x, y, W, H);
circles.addElement(rect);
drawingPane.scrollRectToVisible(rect);
if (area.width < x) {
area.width = x;
}
if (area.height < y) {
area.height = y;
}
// Update client's preferred size because the area taken
// up by the graphics has gotten larger or smaller(id cleared)
drawingPane.setPreferredSize(area);
// Let the scroll pane know to update itself and its scrollbars
drawingPane.revalidate();
}
drawingPane.repaint();
} | 5 |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Map params=request.getParameterMap();
boolean show=false;
String env="ppe";
String min=null;
String max=null;
String state=null;
if(params.containsKey("show")){
String[] vals=(String[])params.get("show");
if(vals[0].equals("true")){
show=true;
}
}
if(params.containsKey("env")){
String[] vals=(String[])params.get("env");
if(vals[0].equals("cert") || vals[0].equals("ppe") || vals[0].equals("prod")){
env=vals[0];
}
}
if(params.containsKey("state")){
String[] vals=(String[])params.get("state");
state=vals[0];
}
if(params.containsKey("minRelativeToNowInMinutes")){
String[] vals=(String[])params.get("minRelativeToNowInMinutes");
min=vals[0];
}
if(params.containsKey("maxRelativeToNowInMinutes")){
String[] vals=(String[])params.get("maxRelativeToNowInMinutes");
max=vals[0];
}
Driver d=new Driver(show);
d.htmlContent(out,env,min,max,state);
} | 9 |
public Set<Map.Entry<Short,Byte>> entrySet() {
return new AbstractSet<Map.Entry<Short,Byte>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TShortByteMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TShortByteMapDecorator.this.containsKey(k)
&& TShortByteMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Short,Byte>> iterator() {
return new Iterator<Map.Entry<Short,Byte>>() {
private final TShortByteIterator it = _map.iterator();
public Map.Entry<Short,Byte> next() {
it.advance();
short ik = it.key();
final Short key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
byte iv = it.value();
final Byte v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Short,Byte>() {
private Byte val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Short getKey() {
return key;
}
public Byte getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Byte setValue( Byte value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Short,Byte> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Short key = ( ( Map.Entry<Short,Byte> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Short, Byte>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TShortByteMapDecorator.this.clear();
}
};
} | 8 |
public WindowsRegistry(boolean user) {
if (!Platform.isWindows()) {
throw new IllegalStateException("Only avaliable on a Windows platform");
}
if (user) {
mRoot = Preferences.userRoot();
mRootKey = Integer.valueOf(0x80000001);
} else {
mRoot = Preferences.systemRoot();
mRootKey = Integer.valueOf(0x80000002);
}
} | 2 |
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM HH:mm");
do {
try {
trayIcon.setToolTip("Busy...");
trayIcon.setImage(imageBusy);
TemperatureStatus t=controller.invoke();
t.save(orm);
trayIcon.setToolTip("Last sample: " + sdf.format(new Date()));
trayIcon.setImage(imageIdle);
} catch (Exception ex) {
if (ex instanceof java.sql.SQLException) {
logger.error(ex.getMessage(), ex);
System.exit(-1);
}
if (!(ex instanceof InterruptedException)) {
logger.error(ex.getMessage(), ex);
//System.exit(-1);
trayIcon.setImage(imageError);
trayIcon.setToolTip(ex.getMessage());
}
}
try {
Thread.sleep(interval);
} catch (Exception ex) {
if (!(ex instanceof InterruptedException)) {
logger.error(ex.getMessage(), ex);
alive = false;
}
}
} while (alive);
System.exit(0);
} | 6 |
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Customer customer = customers.get(rowIndex);
switch (columnIndex) {
case 0:
customer.setId((Long) aValue);
break;
case 1:
customer.setFirstname((String) aValue);
break;
case 2:
customer.setLastname((String) aValue);
break;
case 3:
customer.setBirth(Date.valueOf((String) aValue));
break;
case 4:
customer.setEmail((String) aValue);
break;
default:
throw new IllegalArgumentException("columnIndex");
}
try {
customerManager.updateCustomer(customer);
fireTableDataChanged();
} catch (Exception ex) {
String msg = "User request failed";
LOGGER.log(Level.INFO, msg);
}
} | 6 |
@Override
public void rightMultiply(IMatrix other) {
// TODO Auto-generated method stub
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
copy[i][j]=0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
copy[i][j]=copy[i][j] + this.get(k, i) * other.get(j, k);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
this.set(j, i, copy[i][j]);
}
}
} | 7 |
public void keyPressed(int k) {
if(player.getMovable()){
if(k == KeyEvent.VK_LEFT) player.setLeft(true);
if(k == KeyEvent.VK_RIGHT) player.setRight(true);
if(k == KeyEvent.VK_W) player.setJumping(true);
if(k == KeyEvent.VK_R) player.setScratching();
if(k == KeyEvent.VK_F) player.setFiring();
}
} | 6 |
@Override
public double calculateJuliaWithoutPeriodicity(Complex pixel) {
iterations = 0;
Complex tempz2 = new Complex(init_val2.getPixel(pixel));
Complex[] complex = new Complex[3];
complex[0] = new Complex(pixel);//z
complex[1] = new Complex(seed);//c
complex[2] = tempz2;//z2
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
for(; iterations < max_iterations; iterations++) {
if(bailout_algorithm.escaped(complex[0], zold)) {
Object[] object = {iterations, complex[0], zold};
return out_color_algorithm.getResult(object);
}
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
return in_color_algorithm.getResult(object);
} | 8 |
public String testStartLocal(String appKey, String userKey, String testId) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
testId = URLEncoder.encode(testId, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/testStartExternal/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId);
} | 1 |
public void setTitle(String title) {
this.title = title;
} | 0 |
public Document createDocument(final List<Student> students) {
Document doc = null;
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
final Element root = doc.createElement(Model.FIELD_STUDENTS);
for (final Student student : students) {
final Element studentElement = doc.createElement(Model.FIELD_STUDENT);
root.appendChild(studentElement);
newElement(doc, Model.FIELD_NAME, studentElement, student.getName());
newElement(doc, Model.FIELD_GROUP, studentElement, student.getGroup()
.toString());
final List<Exam> exams = student.getExams();
final Element examsElement = doc.createElement(Model.FIELD_EXAMS);
studentElement.appendChild(examsElement);
for (final Exam exam : exams) {
if (!exam.isEmpty()) {
final Element examElement = doc.createElement(Model.FIELD_EXAM);
examsElement.appendChild(examElement);
newElement(doc, Model.FIELD_NAME, examElement,
exam.getName() != null ? exam.getName() : " ");
newElement(doc, Model.FIELD_MARK, examElement,
exam.getMark() != null ? exam.getMark().toString() : " ");
}
}
}
doc.appendChild(root);
} catch (final Exception e) {
XMLWriter.LOG
.log(Level.SEVERE,
Window.geti18nString(Model.PROBLEM_PARSING_THE_FILE)
+ e.getMessage(), e);
}
return doc;
} | 6 |
private final void split() {
if (isLeaf()) {
int hw = mWidth / 2;
int hh = mHeight / 2;
mNorthWest = new Node<>(mX, mY, hw, hh, mMaxCapacity);
mNorthEast = new Node<>(mX + hw, mY, mWidth - hw, hh, mMaxCapacity);
mSouthWest = new Node<>(mX, mY + hh, hw, mHeight - hh, mMaxCapacity);
mSouthEast = new Node<>(mX + hw, mY + hh, mWidth - hw, mHeight - hh, mMaxCapacity);
Set<T> temp = mContents;
mContents = new HashSet<>();
for (T one : temp) {
add(one);
}
}
} | 2 |
private boolean hasAppropriateFirstTerminal() {
return peekTypeMatches("ID") || peekTypeMatches("LPAREN")
|| peekTypeMatches("INTLIT") || peekTypeMatches("STRLIT")
|| peekTypeMatches("NIL");
} | 4 |
@Override
protected void paint(Graphics2D g2) {
if (debug) {
paintDebuggingFrame(g2);
}
super.paint(g2);
} | 1 |
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Jump other = (Jump) obj;
if (captureX != other.captureX) {
return false;
}
if (captureY != other.captureY) {
return false;
}
if (x1 != other.x1) {
return false;
}
if (x2 != other.x2) {
return false;
}
if (y1 != other.y1) {
return false;
}
if (y2 != other.y2) {
return false;
}
return true;
} | 9 |
public static void restoreGODatabase(){
for (File file: new File("C:/Users/hgabr/Desktop/go_201207-assocdb-tables").listFiles()){
if (file.getName().indexOf(".sql") > 0){
try {
Process process = Runtime.getRuntime().exec("cmd /c mysql -u root go < " + "c:\\Users\\hgabr\\Desktop\\go_201207-assocdb-tables\\" + file.getName());
System.out.println(process.waitFor());
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (File file: new File("C:/Users/hgabr/Desktop/go_201207-assocdb-tables").listFiles()){
if (file.getName().indexOf(".txt") > 0){
try {
System.out.println(file.getName());
Process process = Runtime.getRuntime().exec("cmd /c mysqlimport -u root -L go " + "c:\\Users\\hgabr\\Desktop\\go_201207-assocdb-tables\\" + file.getName());
System.out.println(process.waitFor());
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} | 8 |
public Message<?> debug(Message<?> message) {
StringBuilder builder = new StringBuilder();
builder.append("\n############################## DEBUG HOOK ##############################\n");
builder.append("Payload:"+message.getPayload()+"\n");
builder.append("Headers:"+message.getHeaders()+"\n");
builder.append("########################################################################\n");
System.out.println(builder.toString());
LOG.info(builder.toString());
return message;
} | 2 |
private void registerJobs(){
List<String> list =getJobsConf().getStringList("enabled-jobs");
for(String job : list){
registerJob(job);
}
} | 1 |
public void setSelected(TreeNode node, boolean select) {
if (select)
selectedNodes.put(node, null);
else
selectedNodes.remove(node);
} | 1 |
public static void main(String args[]) throws Throwable{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
for(int t=0,T=parseInt(in.readLine().trim());t++<T;){
int N=parseInt(in.readLine().trim());
int arr[][]=new int[N][2];
long s1=0,s3=0;
StringTokenizer st=new StringTokenizer(in.readLine());
TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();
for(int i=0;i<N;i++){
s1+=(arr[i][0]=parseInt(st.nextToken()));
Integer s=map.get(arr[i][0]);
if(s==null)s=0;
s++;
map.put(arr[i][0],s);
}
st=new StringTokenizer(in.readLine());
for(int i=0;i<N;i++){
arr[i][1]=parseInt(st.nextToken());
if(map.containsKey(arr[i][1])){
int s=map.get(arr[i][1]);
if(s==1)map.remove(arr[i][1]);
else map.put(arr[i][1],s--);
}
else s1+=arr[i][1];
}
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
s3+=min(arr[i][0],arr[j][1]);
sb.append("Matty needs at least "+s1+" blocks, and can add at most "+(s3-s1)+" extra blocks.\n");
}
System.out.print(new String(sb));
} | 8 |
@Override
public void addUser(User user) throws SQLException {
Session session=null;
try{
session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null && session.isOpen())
session.close();
}
} | 3 |
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(InserirMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InserirMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InserirMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InserirMarcaGui.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 InserirMarcaGui().setVisible(true);
}
});
} | 6 |
public JPanel createSettings() {
JPanel settings = new JPanel();
settings.setLayout(new GridBagLayout());
settings.setBackground(new Color(255, 231, 186));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
JLabel set = new JLabel("Settings");
set.setFont(new Font("Arial", Font.BOLD, 25));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
settings.add(set, gbc);
JLabel diff = new JLabel("Difficulties");
diff.setFont(new Font("Arial", Font.PLAIN, 15));
gbc.weightx = 0.5;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
settings.add(diff, gbc);
JRadioButton one = new JRadioButton("1");
one.setMnemonic(KeyEvent.VK_C);
one.setBackground(new Color(255, 231, 186));
selected = one;
selected.setSelected(true);
one.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
difficulty = 1;
if(selected != null) {
selected.setSelected(false);
}
selected = (JRadioButton) (event.getSource());
selected.setSelected(true);
}
});
gbc.weightx = 0.5;
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridwidth = 1;
settings.add(one, gbc);
JRadioButton two = new JRadioButton("2");
two.setMnemonic(KeyEvent.VK_C);
two.setBackground(new Color(255, 231, 186));
two.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
difficulty = 2;
if(selected != null) {
selected.setSelected(false);
}
selected = (JRadioButton) (event.getSource());
selected.setSelected(true);
}
});
gbc.weightx = 0.5;
gbc.gridx = 4;
gbc.gridy = 2;
gbc.gridwidth = 1;
settings.add(two, gbc);
JRadioButton three = new JRadioButton("3");
three.setMnemonic(KeyEvent.VK_C);
three.setBackground(new Color(255, 231, 186));
three.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
difficulty = 3;
if(selected != null) {
selected.setSelected(false);
}
selected = (JRadioButton) (event.getSource());
selected.setSelected(true);
}
});
gbc.weightx = 0.5;
gbc.gridx = 6;
gbc.gridy = 2;
gbc.gridwidth = 1;
settings.add(three, gbc);
JRadioButton four = new JRadioButton("4");
four.setMnemonic(KeyEvent.VK_C);
four.setBackground(new Color(255, 231, 186));
four.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
difficulty = 4;
if(selected != null) {
selected.setSelected(false);
}
selected = (JRadioButton) (event.getSource());
selected.setSelected(true);
}
});
gbc.weightx = 0.5;
gbc.gridx = 8;
gbc.gridy = 2;
gbc.gridwidth = 1;
settings.add(four, gbc);
return settings;
} | 4 |
protected PseudoSequencePair getLastInstanceOfPrefixSequenceNEW(List<Itemset> prefix, int i){
int remainingToMatchFromPrefix = i;
List<Position> listPositions = new ArrayList<Position>();
int prefixItemsetPosition = prefix.size() -1;
// for each itemset of sequence
for(int j = size() -1; j>=0; j--){
int itemInPrefixPosition = prefix.get(prefixItemsetPosition).size()-1;
boolean allMatched = false;
int searchedItem = prefix.get(prefixItemsetPosition).get(itemInPrefixPosition);
List<Position> tempList = new ArrayList<Position>();
// for each item in itemset
for(int k=getSizeOfItemsetAt(j)-1; k >=0; k--) {
int currentItem = getItemAtInItemsetAt(k, j);
if(currentItem == searchedItem) {
tempList.add(new Position(j, k));
itemInPrefixPosition--;
if(itemInPrefixPosition == -1 || tempList.size() == remainingToMatchFromPrefix) {
allMatched = true;
break;
}
searchedItem = prefix.get(prefixItemsetPosition).get(itemInPrefixPosition);
}else if(currentItem < searchedItem) {
break;
}
}
if(allMatched) {
remainingToMatchFromPrefix -= tempList.size();
listPositions.addAll(tempList);
prefixItemsetPosition--;
if(prefixItemsetPosition == -1) {
return new PseudoSequencePair(this, listPositions);
}
}
}
return null; // should not happen
} | 8 |
public static void main(String[] args) throws UnknownHostException, SocketException{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while(ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
System.out.println(i.getHostAddress());
}
}
} | 2 |
public List<Endereco> listarTodos(int idPessoa){
try{
PreparedStatement comando = banco.getConexao()
.prepareStatement("SELECT * FROM enderecos WHERE id_pessoa = ? "
+ "AND ativo = 1");
comando.setInt(1, idPessoa);
ResultSet consulta = comando.executeQuery();
comando.getConnection().commit();
List<Endereco> listaEnderecos = new LinkedList<>();
while(consulta.next()){
Endereco tmp = new Endereco();
tmp.setBairro(consulta.getString("bairro"));
tmp.setCep(consulta.getString("cpf"));
tmp.setCidade(consulta.getString("cidade"));
tmp.setEstado(consulta.getString("estado"));
tmp.setId(consulta.getInt("id"));
tmp.setNumero(Integer.parseInt(consulta.getString("numero")));
tmp.setRua(consulta.getString("rua"));
listaEnderecos.add(tmp);
}
return listaEnderecos;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}
} | 2 |
public void shiftLeft(boolean isJump){
reDrawIndex = reDrawIndex - 5;
if(reDrawIndex < 0){
reDrawIndex = files.size() + reDrawIndex;
}
if(isJump){
listPosition = listPosition - 5;
if(listPosition < 0){
listPosition = files.size() + listPosition;
}
}
} | 3 |
public int insert(List<DBRow> rows) throws Exception{
File table = new File("Databases/" + name + ".xml");
if(!table.exists())
throw new Exception("The table " + name + " doesn't exist.");
SAXBuilder builder = new SAXBuilder();
Document document = null;
try {
document = (Document) builder.build(table);
Element rootNode = document.getRootElement();
this.nextIndex = Integer.parseInt(rootNode.getAttributeValue("nextIndex"));
Element rowsTag = rootNode.getChild("rows");
Element rowElement = null;
for(DBRow row : rows){
rowElement = new Element("row");
for(DBItem item : row.getItems()){
Column column;
if((column = columns.get(item.getColumn())) != null){
if(column.getType().validate(item.getValue())){
Element value = new Element("value");
value.setAttribute("column", column.getName());
value.setText(item.getValue().toString());
rowElement.addContent(value);
}else
System.out.println("Not valid! " + column.getName());
}
}
Element index = new Element("value");
index.setAttribute("column", this.indexColumn);
index.setText(nextIndex++ + "");
rootNode.setAttribute("nextIndex", nextIndex + "");
rowElement.addContent(index);
rowsTag.addContent(rowElement);
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
try {
xmlOutput.output(document, new FileWriter(table));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nextIndex-1;
} | 8 |
public RQHTTPHandler(RemoteQuery plugin, RQSchedulerHandler schedHandler)
{
this.plugin = plugin;
this.schedHandler = schedHandler;
try
{
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // must match with remote PHP scripts encryption scheme
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
} | 2 |
public Set<Map.Entry<Double,Character>> entrySet() {
return new AbstractSet<Map.Entry<Double,Character>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TDoubleCharMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TDoubleCharMapDecorator.this.containsKey(k)
&& TDoubleCharMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Double,Character>> iterator() {
return new Iterator<Map.Entry<Double,Character>>() {
private final TDoubleCharIterator it = _map.iterator();
public Map.Entry<Double,Character> next() {
it.advance();
double ik = it.key();
final Double key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
char iv = it.value();
final Character v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Double,Character>() {
private Character val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Double getKey() {
return key;
}
public Character getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Character setValue( Character value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Double,Character> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Double key = ( ( Map.Entry<Double,Character> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Double, Character>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TDoubleCharMapDecorator.this.clear();
}
};
} | 8 |
protected long encodeBinary(OutputStream objOut, RPCObject rpcObj) throws IOException {
long byteSent = 0L;
RPCBinaryObject rcpbinary = (RPCBinaryObject)rpcObj;
Object val = rpcObj.getValue();
File f = null;
byte[] data = null;
if(val instanceof File){
f = (File) val;
}else if(val instanceof String){
f = new File((String) val);
}else{
data = (byte[])val;
}
if(f!=null){
String fname = rcpbinary.getName()==null?f.getCanonicalPath().replaceAll("\\", "/"):rcpbinary.getName();
byte[] fnames = fname.getBytes();
writeInt(objOut,fnames.length);
byteSent += 4L;
objOut.write(fnames);
byteSent += fnames.length;
long flength = f.length();
writeInt(objOut,(int)flength);
FileInputStream fin = null;
try{
fin = new FileInputStream(f);
int sent = 0;
int read = 0;
while((read=fin.read(BINARY_BUFFER))!=-1){
objOut.write(BINARY_BUFFER, 0, read);
sent += read;
}
if(sent!=f.length()){
//Warnning message here;
}
byteSent += sent;
}finally{
if(fin!=null) fin.close();
}
}else{
String fname = rcpbinary.getName()==null?"":rcpbinary.getName();
byte[] fnames = fname.getBytes();
writeInt(objOut,fnames.length);
objOut.write(fnames);
byteSent += 4L;
if(data==null){
writeLong(objOut, RPC_OBJECT_VAL_NIL);
}else{
writeLong(objOut, data.length);
objOut.write(data);
byteSent += data.length;
}
}
return byteSent;
} | 9 |
private void changeViewMode()
{
viewModeCounter++;
if(viewModeCounter==4){viewModeCounter=0;}
MapGetter.setMapType(viewMode[viewModeCounter]);
MapGetter.getMapImage(MapGetter.createUrl(0, 0));
buttonViewMode.setText(viewMode[viewModeCounter].toUpperCase());
repaint();
} | 1 |
public void handlePacket(LoginPacket packet) {
final IoBuffer buf = packet.getPayload();
switch (packet.getOpcode()) {
case LoginPacket.CHECK_LOGIN: {
final String name = NameUtils.formatNameForProtocol(IoBufferUtils
.getRS2String(buf));
final String password = IoBufferUtils.getRS2String(buf);
final LoginResult res = server.getLoader().checkLogin(
new PlayerDetails(null, name, password, 0, null, null));
if (res.getReturnCode() == 2) {
final PlayerData pd = new PlayerData(name, res.getPlayer()
.getRights().toInteger());
NodeManager.getNodeManager().register(pd, this);
}
final IoBuffer resp = IoBuffer.allocate(16);
resp.setAutoExpand(true);
IoBufferUtils.putRS2String(resp, name);
resp.put((byte) res.getReturnCode());
resp.flip();
session.write(new LoginPacket(LoginPacket.CHECK_LOGIN_RESPONSE,
resp));
break;
}
case LoginPacket.LOAD: {
final String name = NameUtils.formatNameForProtocol(IoBufferUtils
.getRS2String(buf));
final Player p = new Player(new PlayerDetails(null, name, "", 0,
null, null));
final int code = server.getLoader().loadPlayer(p) ? 1 : 0;
final IoBuffer resp = IoBuffer.allocate(1024);
resp.setAutoExpand(true);
IoBufferUtils.putRS2String(resp, name);
resp.put((byte) code);
if (code == 1) {
final IoBuffer data = IoBuffer.allocate(16);
data.setAutoExpand(true);
p.serialize(data);
data.flip();
resp.putShort((short) data.remaining());
resp.put(data);
}
resp.flip();
session.write(new LoginPacket(LoginPacket.LOAD_RESPONSE, resp));
break;
}
case LoginPacket.SAVE: {
final String name = NameUtils.formatNameForProtocol(IoBufferUtils
.getRS2String(buf));
final int dataLength = buf.getUnsignedShort();
final byte[] data = new byte[dataLength];
buf.get(data);
final IoBuffer dataBuffer = IoBuffer.allocate(dataLength);
dataBuffer.put(data);
dataBuffer.flip();
final Player p = new Player(new PlayerDetails(null, name, "", 0,
null, null));
p.deserialize(dataBuffer);
final int code = server.getLoader().savePlayer(p) ? 1 : 0;
final IoBuffer resp = IoBuffer.allocate(16);
resp.setAutoExpand(true);
IoBufferUtils.putRS2String(resp, name);
resp.put((byte) code);
resp.flip();
session.write(new LoginPacket(LoginPacket.SAVE_RESPONSE, resp));
break;
}
case LoginPacket.DISCONNECT: {
final String name = NameUtils.formatNameForProtocol(IoBufferUtils
.getRS2String(buf));
final PlayerData p = NodeManager.getNodeManager().getPlayer(name);
if (p != null) {
NodeManager.getNodeManager().unregister(p);
}
}
break;
}
} | 9 |
public boolean collides(Ship someShip)
{
for(int i = 0; i < fleet.size(); i++)
{
Ship ship = fleet.get(i);
if(someShip.contains(ship))
return true;
}
return false;
} | 2 |
public static final BruteParams<?>[] valuesGlobal() {
final BruteParams<?>[] values_ = values();
for (int i = 0; i < values_.length; i++) {
if (!values_[i].global) {
values_[i] = null;
}
}
return values_;
} | 4 |
public Matrix getBack() {
return cam.getBack();
} | 0 |
private void acao111() throws SemanticError {
try{
IdentificadorMetodo idMetodo = pilhaMetodosAtuais.peek();
for(Identificador id : listaParametros){
IdentificadorParametro idParametro = completarIdParametro(id);
idMetodo.getParametros().add(idParametro);
tabela.override(idParametro, nivelAtual);
}
listaParametros = new ArrayList<>();
}catch(IdentificadorJaDefinidoException ex){
throw new SemanticError(ex.getMessage());
}
} | 2 |
void drawObject(Graphics g, JGObject o) {
if (!o.is_suspended) {
//o.prepareForFrame();
drawImage(g,(int)o.x,(int)o.y,o.getImageName(),true);
try {
o.paint();
} catch (JGameError ex) {
exitEngine(dbgExceptionToString(ex));
} catch (Exception e) {
dbgShowException(o.getName(),e);
}
}
// note that the debug bbox of suspended objects will be visible
if ((debugflags&JGEngine.BBOX_DEBUG)!=0) {
setColor(g,el.fg_color);
JGRectangle bbox = o.getBBox();
if (bbox!=null) { // bounding box defined
//bbox.x -= xofs;
//bbox.y -= yofs;
bbox = el.scalePos(bbox,true);
g.drawRect(bbox.x,bbox.y,bbox.width,bbox.height);
}
bbox = o.getTileBBox();
if (bbox!=null) { // tile bounding box defined
//bbox.x -= xofs;
//bbox.y -= yofs;
bbox = el.scalePos(bbox,true);
g.drawRect(bbox.x,bbox.y,bbox.width,bbox.height);
setColor(g,debug_auxcolor1);
bbox = o.getTileBBox();
bbox = getTiles(bbox);
bbox.x *= el.tilex;
bbox.y *= el.tiley;
//bbox.x -= xofs;
//bbox.y -= yofs;
bbox.width *= el.tilex;
bbox.height *= el.tiley;
bbox = el.scalePos(bbox,true);
g.drawRect(bbox.x,bbox.y,bbox.width,bbox.height);
setColor(g,debug_auxcolor2);
bbox = o.getCenterTiles();
bbox.x *= el.tilex;
bbox.y *= el.tiley;
//bbox.x -= xofs;
//bbox.y -= yofs;
bbox.width *= el.tilex;
bbox.height *= el.tiley;
bbox = el.scalePos(bbox,true);
g.drawRect(bbox.x+2,bbox.y+2,bbox.width-4,bbox.height-4);
}
}
//o.frameFinished();
} | 6 |
public String getCampoVenta(String clave, beansVentas venta){
if(clave.trim().equals("nombre"))
return venta.getNombre();
if(clave.trim().equals("nick"))
return venta.getNick();
if(clave.trim().equals( "precio"))
return Integer.toString(venta.getPrecio());
if(clave.trim().equals("fecha"))
return venta.getFecha();
if(clave.trim().equals("cantidad"))
return Integer.toString(venta.getCantidad());
if(clave.trim().equals("codigo"))
return Integer.toString(venta.getId());
if(clave.trim().equals("total"))
return Integer.toString(venta.getTotal());
return "null";
} | 7 |
private void toFastboot_fastbootMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toFastboot_fastbootMenuActionPerformed
try {
adbController.getFastbootController().rebootDeviceFastboot(deviceManager.getSelectedFastbootDevice(), RebootTo.BOOTLOADER);
} catch (IOException | NullPointerException ex) {
logger.log(Level.ERROR, "An error occurred while rebooting device " + selectedDevice.getSerial() + " to Fastboot: " + ex.toString() + "\n"
+ "The error stack trace will be printed to the console...");
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_toFastboot_fastbootMenuActionPerformed | 1 |
public void play(int numGames, int numPlayer, int numCard, int itemsPerLine, boolean shuffle) {
for (int i = 0; i < numGames; i++) {
System.out.println("=== Game " + (i+1) + " ===");
System.out.println();
if (shuffle) {
cardDeck.shuffle();
}
Hand playerHand[] = new Hand[numPlayer];
for (int j = 0; j < numPlayer; j++) {
playerHand[j] = new Hand();
}
deal(playerHand, numPlayer, numCard);
printScores(playerHand, numPlayer, numCard, itemsPerLine);
}
System.out.println("=== Games Complete ===");
System.out.println();
} | 3 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already detecting invisibility."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> open(s) <S-HIS-HER> softly glowing eyes."):L("^S<S-NAME> incant(s) softly, and open(s) <S-HIS-HER> glowing eyes.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
beneficialVisualFizzle(mob,null,L("<S-NAME> incant(s) and open(s) <S-HIS-HER> eyes softly, but the spell fizzles."));
return success;
} | 8 |
public Cuboid getFace(CuboidDirection dir) {
switch (dir) {
case Down:
return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y1, this.z2);
case Up:
return new Cuboid(this.worldName, this.x1, this.y2, this.z1, this.x2, this.y2, this.z2);
case North:
return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x1, this.y2, this.z2);
case South:
return new Cuboid(this.worldName, this.x2, this.y1, this.z1, this.x2, this.y2, this.z2);
case East:
return new Cuboid(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, this.z1);
case West:
return new Cuboid(this.worldName, this.x1, this.y1, this.z2, this.x2, this.y2, this.z2);
default:
throw new IllegalArgumentException("Invalid direction " + dir);
}
} | 6 |
public static void OrdiVsOrdi(Parametre param){
// Faire des statistiques sur plusieurs parties
Ligne ligneOrdi1 = new Ligne(param, true);
Ligne ligneOrdi2 = new Ligne(param, false);
LigneMarqueur liMarq = new LigneMarqueur(param.getTailleLigne());
String esp = param.esp(" "); // On récupère le nombre d'espace qu'il faut pour l'affichage
int nbCoup = 1;
Scanner sc = new Scanner(System.in);
String rep;
boolean continuer;
boolean gagne = false;
IA ordi2 = new IA(param);
System.out.print("L'ordi 1 entre une combinaison : ");
ligneOrdi1.afficher();
System.out.println("\n Ordi 2 : \n");
System.out.println("------------------------------------------------" + param.esp("---"));
System.out.println("| Joueur | "+esp+"Jeu"+esp+" |"+esp+"Réponse"+esp+"| Coup |");
System.out.println("------------------------------------------------" + param.esp("---"));
while(!gagne && nbCoup <= param.getNbCoupMax()){
System.out.print("| Ordi 2 entre : | ");
ligneOrdi2 = ordi2.jouer(liMarq); // L'ordinateur propose une combinaison, pas de souci si liMarq est vide. Tous ces éléments sont initilisés à 0
System.out.print(" ");
ligneOrdi2.afficher();
liMarq = ligneOrdi1.compare(ligneOrdi2); // On compare la ligne de l'ordi avec la ligne secrète
System.out.print(" | ");
liMarq.afficher();
System.out.print(esp+" | "+nbCoup+ " |\n");
System.out.println("-------------------------------------------------" + param.esp("---"));
if(liMarq.gagne()){
System.out.println("L'ordi2 a gagné, en "+ nbCoup+" coups.");
gagne = true;
}
else if(nbCoup > param.getNbCoupMax()){
System.out.println("L'ordi2 a perdu ! le réponse était : " + ligneOrdi1.toString());
}
nbCoup++;
}
} | 4 |
public FenetreVisualiserRaster(){
//maintenant la fenêtre de visualisation
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Visualisation de Raster");
this.setSize(500, 240);
// this.connexion=connexion;
if(FenetreVisualiserRaster.nomShape1.size()==0){
FenetreVisualiserRaster.nomShape1=ConnexionVisualiserRaster.getArrayy();
}
for(String fg:nomShape1){
System.out.println("fg "+fg);
}
for(String bc:nomShape1){
System.out.println("bc"+bc);
}
//avant this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//this.setDefaultCloseOperation(this.nomShape1.remove(0));
//avant this.setTitle("JTable5678");
//avant this.setSize(500, 240);
// final DefaultTableModel model = new DefaultTableModel();
// final JTable tableau = new JTable(model);
// tableau.setColumnSelectionAllowed (true);
// tableau.setRowSelectionAllowed (false);
TableColumn ColumnName = new TableColumn();
ColumnName.setHeaderValue(new String("Name") );
ColumnName.setMinWidth(200);
model.addColumn(ColumnName);
tableau.getColumnModel().getColumn(0).setHeaderValue(new String("Nom"));
tableau.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public synchronized void valueChanged(ListSelectionEvent abc) {
// TODO Auto-generated method stub
setSel(tableau.getSelectedRow());
System.out.println("sel"+getSel());
}
});
if(model.getRowCount()<nomShape1.size()&&model.getRowCount()==0){
//System.out.println("sizze "+model.getRowCount());
for (int efg=0;efg<nomShape1.size();efg++){
model.addRow(new Object [] {nomShape1.get(efg)});
// System.out.println("sizze "+model.getRowCount());
}
}
//this.model.removeRow(1);
JPanel pan = new JPanel();
change.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel Model = new DefaultTableModel();
Model.addColumn("test");
hmm = OuvrirFenetre.pathArray();
//tableau.set
Object[][] data = new Object[hmm.size()][hmm.size()];
for (int i = 0; i<hmm.size();i++){
data[i][0]= hmm.get(i);
}
//tableau.setValueAt("New Value", rowIndex, vColIndex);
// Model.addRow(new Object[] { "test" } );
//for(String f:hmm){
System.out.println(hmm.size());
for(int f=0;f<hmm.size();f++){
// System.out.println("test"+hmm.get(f));
//model.addRow(new Object [] {f});
// if (model.getValueAt(0,0) == hmm.get(0)){
// hmm.remove(hmm.get(0));
// }
int ab = model.getRowCount();
System.out.println(ab);
model.insertRow(ab, new Object[]{hmm.get(f)});
System.out.println("ab"+hmm.get(f));
// hmm.remove(hmm.get(f));
OuvrirFenetre.path.remove(hmm.get(f));
//System.out.println("bb"+hmm.get(f));
}
}
});
int a = tableau.getSelectedColumn();
System.out.println("a"+ a);
supprimer.addActionListener(new ActionListener(){
@Override
public synchronized void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
nomShape1.remove(getSel());
model.removeRow(getSel());
}
}
);
pan.add(supprimer);
pan.add(change);
//
//
// String titl2[] = {"Nome shape"};
//
// this.tableau = new JTable(data,titl2);
//model.setRowHeight(30);
//model.setNumRows(30);
//On remplace cette ligne
this.getContentPane().add(new JScrollPane(tableau), BorderLayout.CENTER);
this.getContentPane().add(pan, BorderLayout.SOUTH);
valider.addActionListener(this);
pan.add(valider);
} | 8 |
private RepositoryConfig createRepositoryConfig(Properties properties) throws MojoExecutionException{
String driverClass = this.databaseDriverClass;
String username = this.databaseUsername;
String password = this.databasePassword;
String url = this.databaseUrl;
if (Strings.isNullOrEmpty(driverClass) && Strings.isNullOrEmpty((driverClass = properties.getProperty("database.driver.class")))){
throw new MojoExecutionException("Driver class must not be null");
}
if (Strings.isNullOrEmpty(username) && Strings.isNullOrEmpty((username = properties.getProperty("database.username")))){
throw new MojoExecutionException("Database username must not be null");
}
if (Strings.isNullOrEmpty(password) && Strings.isNullOrEmpty((password = properties.getProperty("database.password")))){
throw new MojoExecutionException("Database password must not be null");
}
if (Strings.isNullOrEmpty(url) && Strings.isNullOrEmpty((url = properties.getProperty("database.url")))){
throw new MojoExecutionException("Database url must not be null");
}
try {
return new RepositoryConfig(Class.forName(driverClass), username, password, url);
} catch (ClassNotFoundException exception) {
throw new MojoExecutionException(exception.getMessage(), exception);
}
} | 9 |
public CloudController(String componentName, Config config, InputStream userRequestStream, PrintStream userResponseStream) {
this.componentName = componentName;
this.controllerConfig = config;
this.userRequestStream = userRequestStream;
this.userResponseStream = userResponseStream;
/*
* Initialize the user map
*/
userMap = new UserConcurrentHashMap();
/*
* Initialize the node lists
*/
nodeMap = new NodeConcurrentHashMap();
/*
* Read out all of the config information for the controller and initialize the variables
*/
tcpPort = controllerConfig.getInt("tcp.port");
udpPort = controllerConfig.getInt("udp.port");
nodeTimeout = controllerConfig.getInt("node.timeout");
nodeCheckPeriod = controllerConfig.getInt("node.checkPeriod");
/*
* Read user list from user.properties, build userMap and assign user attributes (password, credits)
*/
userConfig = new Config("user");
Set<String> userKeys = userConfig.listKeys();
for (String key : userKeys) {
String[] parts = key.split("\\.");
String userName = parts[0];
String attr = parts[1];
if (!userMap.containsKey(userName)) {
UserData user = new UserData();
user.setUserName(userName);
if (attr.equals("credits"))
user.setCredits(userConfig.getInt(userName + "." + attr));
if (attr.equals("password"))
user.setPassword(userConfig.getString(userName + "." + attr));
userMap.put(userName, user);
} else {
if (attr.equals("credits"))
userMap.get(userName).setCredits(userConfig.getInt(userName + "." + attr));
if (attr.equals("password"))
userMap.get(userName).setPassword(userConfig.getString(userName + "." + attr));
}
}
/*
* Instantiate thread pool
*/
pool = Executors.newCachedThreadPool();
/*
* Instantiate ServerSocket and DatagramSocket
*/
try {
serverSocket = new ServerSocket(tcpPort);
datagramSocket = new DatagramSocket(udpPort);
} catch (SocketException e) {
System.out.println("ERROR: " + e.getMessage());
} catch (IOException e) {
System.out.println("ERROR: " + e.getMessage());
}
aliveTimer = new Timer();
aliveTimerTask = new AliveTimerTask(nodeMap, nodeTimeout);
} | 8 |
public Object[][] bacaDaftar(){
boolean adaKesalahan = false;
Connection cn = null;
Object[][] daftarPembeli = new Object[0][0];
try{
Class.forName(Koneksi.driver);
} catch (Exception ex){
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"JDBC Driver tidak ditemukan atau rusak\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
if (!adaKesalahan){
try {
cn = (Connection) DriverManager.getConnection(Koneksi.database+"?user="+Koneksi.user+"&password="+Koneksi.password+"");
} catch (Exception ex) {
adaKesalahan = true;
JOptionPane.showMessageDialog(null,"Koneksi ke"+Koneksi.database+" gagal\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
if (!adaKesalahan){
String SQLStatemen;
Statement sta;
ResultSet rset;
try {
SQLStatemen = "select no_beli,nama from pembeli";
sta = (Statement) cn.createStatement();
rset = sta.executeQuery(SQLStatemen);
rset.next();
rset.last();
daftarPembeli = new Object[rset.getRow()][2];
if (rset.getRow()>0){
rset.first();
int i=0;
do {
daftarPembeli[i] = new
Object[]{rset.getString("no_beli"), rset.getString("nama")};
i++;
} while (rset.next());
}
sta.close();
rset.close();
} catch (Exception ex){
JOptionPane.showMessageDialog(null,"Tidak dapat membuka tabel pembeli\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE);
}
}
}
return daftarPembeli;
} | 7 |
public void setK(double K) {
assert K >= 0 && K <= 1;
this.K = K;
} | 1 |
public void drawGridLines(Graphics g) {
if (gridLines) {
g.setColor(new Color(0, 0, 200));
for (int i = 0; i < GameConstants.HEIGHT; i++) {
g.drawLine((finalFormatX + padding) - (wallSize / 2), i
* wallSize + padding + finalFormatY,
(finalFormatX + padding) + wallSize
* GameConstants.WIDTH - (wallSize / 2), i
* wallSize + padding + finalFormatY);
}
for (int i = 0; i < GameConstants.WIDTH; i++) {
g.drawLine((finalFormatX + padding) + i * wallSize, padding
+ finalFormatY - (wallSize / 2),
(padding + finalFormatX) + i * wallSize, padding
+ finalFormatY + wallSize
* GameConstants.HEIGHT - (wallSize / 2));
}
}
} | 3 |
private void setBreakableLines() {
for (int i = 0; i < program.size(); i++) {
if (program.getCode(i).getClass() == LineCode.class && ((LineCode) program.
getCode(i)).
getLineNumber() > 0) {
sourceLines.get(((LineCode) program.getCode(i)).getLineNumber()).
setAsPossibleBreakPoint();
}
}
} | 3 |
private List<PhaseField> getPhasesStatuses(DaySchedule daySchedule,
List<TaskRow> tasksData) {
List<PhaseField> tmpPhaseFields = new ArrayList<PhaseField>();
String prevProjectName = tasksData.get(0).getProjectName();
String prevPhaseName = tasksData.get(0).getPhaseName();
int phaseStatus = 0;
int row = 0;
while(row < tasksData.size()){
String currProjectName = tasksData.get(row).getProjectName();
String currPhaseName = tasksData.get(row).getPhaseName();
ScheduleField field = daySchedule.getScheduleFields().get(row);
if(prevPhaseName.equals(currPhaseName)
&& prevProjectName.equals(currProjectName)){
if(field.getWorkDone() >= tasksData.get(row).getDurationTime()){
if(phaseStatus == 0){
phaseStatus = 2;
}
}else if(field.getWorkDone() > 0){
phaseStatus = 1;
}
row++;
// jesli dojde do konca to musze dodac ta faze
if(row == tasksData.size()){
PhaseField phaseField = new PhaseField();
phaseField.projectName = currProjectName;
phaseField.phaseName = currPhaseName;
phaseField.phaseStatus = phaseStatus;
tmpPhaseFields.add(phaseField);
}
}else{
PhaseField phaseField = new PhaseField();
phaseField.projectName = prevProjectName;
phaseField.phaseName = prevPhaseName;
phaseField.phaseStatus = phaseStatus;
tmpPhaseFields.add(phaseField);
// nie zwiekszam zmiennej row -> musze
// jeszcze raz przeleciec petla po tym wierszu
phaseStatus = 0;
}
prevProjectName = currProjectName;
prevPhaseName = currPhaseName;
}
return tmpPhaseFields;
} | 7 |
private byte[] readInputStreamSlowMode(InputStream is) {
boolean lastByteWasReturnByte = false;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while (true) {
int intB = is.read();
byte b = (byte) intB;
/**
* prevent OutOfMemory exceptions, per leopoldkot
*/
if (intB == -1) {
throw new BeanstalkException("The end of InputStream is reached");
}
if (b == '\n' && lastByteWasReturnByte) {
break;
}
if (b == '\r') {
lastByteWasReturnByte = true;
} else {
if (lastByteWasReturnByte) {
lastByteWasReturnByte = false;
baos.write('\r');
}
baos.write(b);
}
}
return baos.toByteArray();
} catch (Exception e) {
throw new BeanstalkException(e.getMessage());
}
} | 7 |
public static Node transplant(Node root,Node u, Node v){
if(u.p == null){
root = v;
}
else if(u == u.p.left)
u.p.left = v;
else
u.p.right = v;
if(v != null)
v.p = u.p;
return root;
} | 3 |
public String truncate(String string, int maxLength)
{
if(null == string) return null;
if(_trimFirst)
{
string = string.trim();
}
if(_compressWhiteSpace)
{
string = string.replaceAll("\\s{2,}", " ");
}
if(string.length() <= maxLength)
{
return string;
}
int maxCapture = maxLength - 1 - _suffix.length();
int minCapture = maxCapture - _breakWordLongerThan;
if(minCapture < 0 || minCapture >= maxCapture)
{
minCapture = 0;
}
Pattern patt = Pattern.compile(String.format(
"(?s)^(.{%d,%d}%s)%s.*",
minCapture,
maxCapture,
_wordPattern,
_wordDelimeterPattern
));
Matcher match = patt.matcher(string);
if(match.matches())
{
return string.substring(0, match.end(1)) + _suffix;
}
return string.substring(0, maxLength - _suffix.length()) + _suffix;
} | 7 |
private void updateVersion(Object[] args) throws CacheUnreachableException {
List<VersionUpdateDefinition> updates = cacheDefinitionCollection.getVersionUpdateDefinitions();
if (updates == null) {
return;
}
// 根据cacheDefinitionCollection中配置的所有更新版本操作,循环调用,更新版本号
for (VersionUpdateDefinition definition : updates) {
String versionKey = definition.generateVersionKey(args);
if (versionKey == null) {
LOGGER.info("无法生成更新版本信息缓存的Key,更新缓存版本失败");
}
// 使用系统时间作为版本号,防止当前版本号与之前某个版本号正好一致,而是对象无法失效
long currentVersion = System.currentTimeMillis();
if (versionKey != null) {
Cache cache = cacheManager.getCache(definition.getPool());
long expire = definition.getExpire();
cache.add(versionKey, currentVersion, expire);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("更新版本信息,版本Key值[" + versionKey + "],版本号[" + currentVersion + "], 版本信息缓存时间[" + expire
+ "]毫秒");
}
}
}
} | 5 |
protected void fireReceiveDataEvent(ReceiveDataOnServerEvent evt) {
if (receiveDataOnServerListenerList != null) {
Object[] listeners = receiveDataOnServerListenerList.getListenerList();
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==ReceiveDataOnServerListener.class) {
((ReceiveDataOnServerListener)listeners[i+1]).OnReceiveDataOnServerEvent(evt);
}
}
}
} | 3 |
private int findMinIndex( )
{
int i;
int minIndex;
for( i = 0; theTrees[ i ] == null; i++ )
;
for( minIndex = i; i < theTrees.length; i++ )
if( theTrees[ i ] != null &&
theTrees[ i ].element.compareTo( theTrees[ minIndex ].element ) < 0 )
minIndex = i;
return minIndex;
} | 4 |
private void clean()
{
for(int i=0; i<mapHeight; i++)
for(int j=0; j<mapWidth; j++)
{
buttons[i][j].setText("");
buttons[i][j].setBackground(Color.WHITE);
}
} | 2 |
@SuppressWarnings("unchecked")
public static BaseJob createJob(ClassLoader classLoader,
Map<String, Object> map, JQlessClient client) {
try {
// Guarantee "data" is a Map
if (map.containsKey("data") && map.get("data") instanceof String) {
try {
Map<String, Object> data = JsonHelper.parseMap((String) map
.get("data"));
map.put("data", data);
} catch (Exception ex) {
_logger.error("Exception occurred while attempting to fix a data issue. The string value "
+ map.get("data")
+ "could not be converted to a Map");
}
}
Attributes attrs = new Attributes(map);
Class<?> klazz = classLoader.loadClass(attrs.getKlassName());
ParameterizedType type = Types.newParameterizedType(
GenericJobFactory.class, klazz);
TypeLiteral<?> typeLiteral = TypeLiteral.get(type);
GenericJobFactory<BaseJob> jobFactory = (GenericJobFactory<BaseJob>) injector
.getInstance(Key.get(typeLiteral));
BaseJob job = jobFactory.create(client, attrs);
// Alternative Approach - Need to performance test these approaches
// MapBinder<String, GenericJobFactory<BaseJob>> mapBinder =
// MapBinder.newMapBinder(binder(), String.class,
// TypeLiteral<GenericJobFactory<BaseJob>>(){});
// mapBinder.addBinding("OfferWriterJob").to(TypeLiteral<GenericJobFactory<OfferWriterJob>>(){});
// mapBinder.addBinding("OtherJob").to(TypeLiteral<GenericJobFactory<OtherJob>>(){});
// Usage
// @Inject Map<String, GenericJobFactory<BaseJob>> factoryMap;
// return factoryMap.get("OfferWriterJob");
// @SuppressWarnings("rawtypes")
// Constructor c = klazz.getConstructor(JQlessClient.class,
// Attributes.class);
// if (c == null)
// c = klazz.getConstructor(JQlessClient.class);
//
// BaseJob job = (BaseJob) c.newInstance(client, attrs);
return job;
} catch (ClassNotFoundException e) {
_logger.error("ClassNotFoundException while attempting to create a Job - exception: "
+ e.getMessage() + e.getStackTrace());
// } catch (NoSuchMethodException e) {
// _logger.error("NoSuchMethodException while attempting to create a Job - exception: "
// + e.getMessage() + e.getStackTrace());
} catch (SecurityException e) {
_logger.error("SecurityException while attempting to create a Job - exception: "
+ e.getMessage() + e.getStackTrace());
// } catch (InstantiationException e) {
// _logger.error("InstantiationException while attempting to create a Job - exception: "
// + e.getMessage() + e.getStackTrace());
// } catch (IllegalAccessException e) {
// _logger.error("IllegalAccessException while attempting to create a Job - exception: "
// + e.getMessage() + e.getStackTrace());
} catch (IllegalArgumentException e) {
_logger.error("IllegalArgumentException while attempting to create a Job - exception: "
+ e.getMessage() + e.getStackTrace());
// } catch (InvocationTargetException e) {
// _logger.error("InvocationTargetException while attempting to create a Job - exception: "
// + e.getMessage() + e.getStackTrace());
} catch (Exception e) {
_logger.error("Exception while attempting to create a Job - exception: "
+ e.getMessage() + e.getStackTrace());
}
return null;
} | 9 |
private void makeHouse(int y, int x, int h, int w) {
for(int i=y; i<y+h; i++)
{
for(int j=x; j<x+w; j++)
{
if(i==y || j==x || i==y+h-1 || j==x+w-1)
{
if(i==y+h/2)
tiles.get(j+i*width).switchType(2);
else
tiles.get(j+i*width).switchType(1);
continue;
}
tiles.get(j+i*width).switchType(2);
}
}
} | 7 |
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_LEFT){
if(mainMenuShowing==false){
showPreviousSlide();
}
}
if(e.getKeyCode()== KeyEvent.VK_RIGHT){
if(mainMenuShowing==false){
showNextSlide();
}
}
} | 4 |
private boolean areEqual(String string1, String string2) {
if (string1 == "")
string1 = null;
if (string2 == "")
string2 = null;
if ((string1 == null && string2 != null) ||
(string1 != null && string2 == null)) {
return false;
}
else if (string1 != null && string2 != null && !string1.equalsIgnoreCase(string2))
return false;
return true;
} | 9 |
@SuppressWarnings({ "rawtypes", "unchecked" })
private static File[] createFileArray(final BufferedReader bReader, final PrintStream out) {
try {
java.util.List list = new java.util.ArrayList();
java.lang.String line = null;
while ((line = bReader.readLine()) != null) {
try {
// kde seems to append a 0 char to the end of the reader
if (ZERO_CHAR_STRING.equals(line))
continue;
java.io.File file = new java.io.File(new java.net.URI(line));
list.add(file);
} catch (Exception ex) {
log(out, "Error with " + line + ": " + ex.getMessage());
}
}
return (java.io.File[]) list.toArray(new File[list.size()]);
} catch (IOException ex) {
log(out, "FileDrop: IOException");
}
return new File[0];
} | 4 |
public void step(boolean blockStep) {
Configuration[] configs = configurations.getValidConfigurations();
ArrayList list = new ArrayList();
HashSet reject = new HashSet();
// Clear out old states.
configurations.clearThawed();
if (!blockStep){ //for ordinary automaton
for (int i = 0; i < configs.length; i++) {
//System.out.println("HERE!");
ArrayList next = simulator.stepConfiguration(configs[i]);
//MERLIN MERLIN MERLIN MERLIN MERLIN//
if (next.size() == 0) { //crucial check for rejection
//System.out.println("Rejected");
reject.add(configs[i]);
list.add(configs[i]);
} else
list.addAll(next);
}
}
// Replace them with the successors.
Iterator it = list.iterator();
while (it.hasNext()) {
Configuration config = (Configuration) it.next();
configurations.add(config);
if (reject.contains(config))
configurations.setReject(config);
}
// What the devil do I have to do to get it to repaint?
configurations.validate();
configurations.repaint();
// Change them darned selections.
changeSelection();
// Ready for the ugliest code in the whole world, ever?
try {
// I take this action without the knowledge or sanction of
// my government...
JSplitPane split = (JSplitPane) configurations.getParent()
.getParent().getParent().getParent();
int loc = split.getDividerLocation();
split.setDividerLocation(loc - 1);
split.setDividerLocation(loc);
// Yes! GridLayout doesn't display properly in a scroll
// pane, but if the user "wiggled" the size a little it
// displays correctly -- now the size is wiggled in code!
} catch (Throwable e) {
}
// State current = null;
// Iterator iter = list.iterator();
// int count = 0;
//MERLIN MERLIN MERLIN MERLIN MERLIN// //forgetting BlockStep for now
//// if (blockStep) { //should ONLY apply to Turing Machines // while (iter.hasNext()) {
//// Configuration configure = (Configuration) iter.next();
//// current = configure.getCurrentState();
//// if (configure.getBlockStack().size() > 0) {
//// if(((Automaton)configure.getAutoStack().peek()).getInitialState() != current || configure.getBlockStack().size()>1){
//// if(!configure.isAccept()){
//// count++;
//// if(count > 10000){
//// int result = JOptionPane.showConfirmDialog(null, "JFLAP has generated 10000 configurations. Continue?");
//// switch (result) {
//// case JOptionPane.CANCEL_OPTION:
//// case JOptionPane.NO_OPTION:
//// return;
//// default:
//// }
//// }
// step(blockStep);
//// }
//// break;
//// }
//// }
//// }
// }
} | 6 |
public void heapSort() { // decreasing order, since this is maxHeap
for (int i = 0; i < heap.size(); i++) {
BTPosition<T> tmp = remove();
System.out.println("Removed: " + tmp.element());
}
} | 1 |
private boolean castlingPossible(final boolean kingside) {
// First check whether castling is generally allowed in this position.
boolean result = this.getPos().isCastlingAvailable(kingside,
this.getColor());
if (result) {
// Castling to the specified side is generally allowed, we are good
// to go on checking.
// Prepare the file index limit (left or right corner)
int fileBorder = kingside ? ChessRules.MAX_FILE
: ChessRules.MIN_FILE;
// Decide whether we have to go left (-1) or right (+1)
int step = kingside ? 1 : -1;
/*
* Make sure no piece is blocking the castling and no field between
* the rook and the king is controlled.
*/
/*
* IMPROVE Castling in Fischer Random Chess: there can be the
* situation where the rook is actually on the wrong side of the
* king with castling being a legal move. In this case we have to
* check the fields between the king and his target coordinate as
* well as the range between the king and the rook. The calculation
* is not correct in this case at the moment as we would check the
* whole range from the king to the border because the index moves
* away from the rook position.
*/
for (int i = this.getCoord().getFile(); i != this.getPos()
.getCastlingRookFile(true, this.getColor())
&& i != fileBorder; i += step) {
// Get target coordinate and piece at coordinate
final ChessCoord tarCoord = Coords.coord(i, this.getCoord()
.getRank());
final Piece tarPiece = this.getPos().getPieceAt(tarCoord);
// Make sure our target coordinate is not blocked or
// controlled
if (this.getPos().isControlled(tarCoord) || (tarPiece != null)) {
// It is blocked, so we cannot castle. Break the loop and
// return.
result = false;
break;
}
}
}
return result;
} | 7 |
@EventHandler(priority = EventPriority.NORMAL)
public void onInteract(PlayerInteractEvent e)
{
Player player = e.getPlayer();
if (e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
if (e.getClickedBlock().getState() instanceof Sign)
{
Sign s = (Sign) e.getClickedBlock().getState();
if (s.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[BowSpleef]") && s.getLine(1).equalsIgnoreCase(ChatColor.GREEN + "Join"))
{
String arena = s.getLine(2);
if (arena != null)
{
if (BowSpleef.arenaConfig.getBoolean("arenas." + arena + ".enabled"))
{
if (!BowSpleef.arenaConfig.getBoolean("arenas." + arena + ".inGame"))
{
Methods.join(player, arena, plugin);
return;
}
this.pm("That arena is in game!", player);
return;
}
this.pm("That arena is Disabled", player);
}
}
}
}
} | 7 |
public boolean begin() {
try {
//Sanity check
if(filename == null || filename.isEmpty()) {
throw new Exception("File name must be set");
}
//Ready the output writer
Charset charset = Charset.forName("UTF-8");
bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), charset));
//Set headers to default values if not set explicitly
if(host == null || host.isEmpty()) {
host = "http://api.somewebapp.com/";
}
if(title == null || title.isEmpty()) {
title = "Project Name";
}
if(description == null || description.isEmpty()) {
description = "Project Description goes here.";
}
//Write out the headers
bWriter.write("HOST: ");
bWriter.write(host);
bWriter.newLine();
bWriter.newLine();
bWriter.write("--- " + title + " ---");
bWriter.newLine();
bWriter.newLine();
bWriter.write("---");
bWriter.newLine();
bWriter.write(description);
bWriter.newLine();
bWriter.write("---");
bWriter.newLine();
bWriter.newLine();
gson = new GsonBuilder().setPrettyPrinting().create();
return true;
} catch (Exception e) {
System.out.println(this.getClass().getName() + ": " + e.getMessage());
return false;
}
} | 9 |
public String getParameterString(){
String retString = super.getParameterString();
try{
if(sourceText!=null) retString+="&sourceText="+sourceText;
if(cQuery!=null) retString+="&cquery="+URLEncoder.encode(cQuery,"UTF-8");
if(xPath!=null) retString+="&xpath="+URLEncoder.encode(xPath,"UTF-8");
if(baseUrl!=null) retString+="&baseUrl="+URLEncoder.encode(baseUrl,"UTF-8");
}
catch(UnsupportedEncodingException e ){
retString = "";
}
return retString;
} | 5 |
public void sanityCheck() {
if (DEBUG) {
System.out.print(this);
int[] widthsCheck = new int[height];
int maxHeightCheck =0;
for(int i =0; i< width;i++){
int heightCheck = 0;
for(int j =0; j< height;j++){
if(grid[i][j])
{
heightCheck = j+1;
widthsCheck[j]++;
if(maxHeightCheck<j+1)
maxHeightCheck = j+1;
}
}
if(heightCheck!=heights[i])
throw new RuntimeException("Heights check failed");
}
if(!Arrays.equals(widthsCheck, widths))
throw new RuntimeException("Widths check failed");
if(maxHeightCheck != maxHeight)
throw new RuntimeException("Max Height check failed");
}
} | 8 |
@EventHandler
public void IronGolemWeakness(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getIronGolemConfig().getBoolean("IronGolem.Weakness.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getIronGolemConfig().getInt("IronGolem.Weakness.Time"), plugin.getIronGolemConfig().getInt("IronGolem.Weakness.Power")));
}
} | 6 |
@Override
public void unInvoke()
{
// undo the affects of this spell
final Environmental E=affected;
if(E==null)
return;
super.unInvoke();
if(canBeUninvoked())
{
if(E instanceof MOB)
{
final MOB mob=(MOB)E;
mob.tell(L("You are no longer soiled."));
final MOB following=((MOB)E).amFollowing();
if((following!=null)
&&(following.location()==mob.location())
&&(CMLib.flags().isInTheGame(mob,true))
&&(CMLib.flags().canBeSeenBy(mob,following)))
following.tell(L("@x1 is no longer soiled.",E.name()));
}
else
if((E instanceof Item)&&(((Item)E).owner() instanceof MOB))
((MOB)((Item)E).owner()).tell(L("@x1 is no longer soiled.",E.name()));
}
} | 9 |
public String getDefault_() {
return default_;
} | 0 |
public static Class<?> getInterfaceGenericType(Class<?> clazz) {
Type genericType = clazz.getGenericInterfaces()[0];
Class<?>[] classes = getActualClass(genericType);
if (classes.length == 0) {
return null;
} else {
return classes[0];
}
} | 4 |
public NetWork(int inputPopulation, int middlePopulation, int outputPopulation, double learningRate, double momentum) {
_inputz = new InputNode[inputPopulation];
for (int ii = 0; ii < _inputz.length; ii++) {
_inputz[ii] = new InputNode();
}
_middlez = new MiddleNode[middlePopulation];
for (int ii = 0; ii < _middlez.length; ii++) {
_middlez[ii] = new MiddleNode(learningRate, momentum);
}
_outputz = new OutputNode[outputPopulation];
for (int ii = 0; ii < _outputz.length; ii++) {
_outputz[ii] = new OutputNode(learningRate, momentum);
}
_arcz = new Arc[(inputPopulation * middlePopulation) + (middlePopulation * outputPopulation)];
for (int ii = 0; ii < _arcz.length; ii++) {
_arcz[ii] = new Arc();
}
int ii = 0;
for (int jj = 0; jj < _inputz.length; jj++) {
for (int kk = 0; kk < _middlez.length; kk++) {
_inputz[jj].connect(_middlez[kk], _arcz[ii++]);
}
}
for (int jj = 0; jj < _middlez.length; jj++) {
for (int kk = 0; kk < _outputz.length; kk++) {
_middlez[jj].connect(_outputz[kk], _arcz[ii++]);
}
}
} | 8 |
int parseInt(String s) throws NumberFormatException {
int radix;
int i;
if( s.startsWith("0x") || s.startsWith("0X") ) {
radix = 16;
i = 2;
} else if( s.startsWith("0") && s.length() > 1 ) {
radix = 8;
i = 1;
} else {
radix = 10;
i = 0;
}
int result = 0;
int len = s.length();
for( ; i<len; i++ ) {
if( result < 0 )
throw new NumberFormatException("Number too big for integer type: "+s);
result *= radix;
int digit = Character.digit(s.charAt(i),radix);
if( digit < 0 )
throw new NumberFormatException("Invalid integer type: "+s);
result += digit;
}
return result;
} | 7 |
private void putCardInFromStack() {
if(cardStackFrom != null && card != null) {
cardStackFrom.addCardRandomly(card);
cardStackFromPanel.setCurrentCount(cardStackFrom.getCount());
card = null;
}
} | 2 |
@EventHandler
public void PigZombieStrength(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.Strength.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getPigZombieConfig().getBoolean("PigZombie.Strength.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, plugin.getPigZombieConfig().getInt("PigZombie.Strength.Time"), plugin.getPigZombieConfig().getInt("PigZombie.Strength.Power")));
}
} | 6 |
private Window() {
// Sets the title for this frame.
this.setTitle("Race Car Game");
// Sets size of the frame, checks for full screen
if (false) // Full screen mode
{
// Disables decorations for this frame.
this.setUndecorated(true);
// Puts the frame to full screen.
this.setExtendedState(this.MAXIMIZED_BOTH);
} else // Window mode
{
// Size of the frame.
this.setSize(1200, 800);
// Puts frame to center of the screen.
this.setLocationRelativeTo(null);
// So that frame cannot be resizable by the user.
this.setResizable(false);
}
// Exit the application when user close frame.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Framework());
this.setVisible(true);
} | 1 |
private void startCollectionSelection() {
ImageButton editCollection = new ImageButton(parent, "Edit collection",
((int) posX + 85), ((int) posY + 150), 100, 25, 1) {
@Override
public void onMousePress(int x, int y) {
if (collectionSelected) {
editingCollection = true;
stopEditingCollection();
startCollectionEditing();
}
}
};
ImageButton deleteCollection = new ImageButton(parent,
"Delete collection", ((int) posX + 85), ((int) posY + 250),
100, 25, 1) {
@Override
public void onMousePress(int x, int y) {
if (collectionSelected) {
if (selectedCollection
.equals(parent.getCurrentCollection())) {
parent.setCurrentCollection(0);
}
parent.removeCollection(selectedCollection);
}
}
};
screenManager.addButton(editCollection);
screenManager.addButton(deleteCollection);
} | 3 |
private static float sqrt(int n){
float l = 0;
float r = n;
while(l<r){
float mid = l + (r-l)/2;
float curr = mid*mid;
if(curr < n){
l=(float) (mid+0.001);
} else if (curr == n) {
return mid;
} else {
r=(float) (mid-0.001);
}
}
return l;
} | 3 |
public Laptop(FabrykaPodzespolowLaptop fabrykaPodzespolowLaptop){
this.fabrykaPodzespolowLaptop = fabrykaPodzespolowLaptop;
skladanie();
} | 0 |
public boolean addAll(SimpleSet<? extends E> s) {
Iterator<? extends E> itr = s.iterator();
int temp = set.size();
while (itr.hasNext()) {
add(itr.next());
}
if(set.size()==temp){
return false;
}
return true;
} | 4 |
public void setFinal(final boolean flag) {
if (this.isDeleted) {
final String s = "Cannot change a field once it has been marked "
+ "for deletion";
throw new IllegalStateException(s);
}
int modifiers = fieldInfo.modifiers();
if (flag) {
modifiers |= Modifiers.FINAL;
} else {
modifiers &= ~Modifiers.FINAL;
}
fieldInfo.setModifiers(modifiers);
this.setDirty(true);
} | 2 |
static double incompleteBetaFraction2(double a, double b, double x) throws ArithmeticException {
double xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
double k1, k2, k3, k4, k5, k6, k7, k8;
double r, t, ans, z, thresh;
int n;
k1 = a;
k2 = b - 1.0;
k3 = a;
k4 = a + 1.0;
k5 = 1.0;
k6 = a + b;
k7 = a + 1.0;
k8 = a + 2.0;
pkm2 = 0.0;
qkm2 = 1.0;
pkm1 = 1.0;
qkm1 = 1.0;
z = x / (1.0 - x);
ans = 1.0;
r = 1.0;
n = 0;
thresh = 3.0 * MACHEP;
do {
xk = -(z * k1 * k2) / (k3 * k4);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = (z * k5 * k6) / (k7 * k8);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (qk != 0) {
r = pk / qk;
}
if (r != 0) {
t = Math.abs((ans - r) / r);
ans = r;
} else {
t = 1.0;
}
if (t < thresh) {
return ans;
}
k1 += 1.0;
k2 -= 1.0;
k3 += 2.0;
k4 += 2.0;
k5 += 1.0;
k6 += 1.0;
k7 += 2.0;
k8 += 2.0;
if ((Math.abs(qk) + Math.abs(pk)) > big) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) {
pkm2 *= big;
pkm1 *= big;
qkm2 *= big;
qkm1 *= big;
}
} while (++n < 300);
return ans;
} | 7 |
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.