- 1
bit = bit == 0 ? 0 : 1;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+145
bit = bit == 0 ? 0 : 1;
бит или не бит?
+145
private static List<Writer> getWriters(final String className, final Severity severity) {
final List<Writer> writers = new ArrayList<Writer>();
if ((className != null) && (severity != null)) {
final Writer writer = Log.writers.get(className + severity);
if ((writer != null) && !writers.contains(writer)) {
writers.add(writer);
}
}
if ((className != null)) {
final Writer writer = Log.writers.get(className);
if ((writer != null) && !writers.contains(writer)) {
writers.add(writer);
}
}
if ((severity != null)) {
final Writer writer = Log.writers.get(severity.name());
if ((writer != null) && !writers.contains(writer)) {
writers.add(writer);
}
}
{
final Writer writer = Log.writers.get(null);
if ((writer != null) && !writers.contains(writer)) {
writers.add(writer);
}
}
return writers;
}
public static void setWriter(final String className, final Severity severity, final Writer writer) {
final Writer w = writer == null ? new OutputStreamWriter(System.err) : writer;
if ((className != null) && (severity != null)) {
Log.writers.put(className + severity, w);
if (Log.writers.get(className) == null) {
Log.writers.put(className, w);
}
if (Log.writers.get(severity.name()) == null) {
Log.writers.put(className, w);
}
} else if (className != null) {
Log.writers.put(className, w);
} else if (severity != null) {
Log.writers.put(severity.name(), w);
} else {
Log.writers.put(null, w);
}
}
изобретаю велосипед
+79
public class LessOperator extends GreaterOperator {
public Object evaluateNode(ITreeNode node, List<NodeValuePair> list) throws CalculatorException {
return !(Boolean)super.evaluateNode(node, list);
}
}
Видимо тут программист решил сократить себе работу и реализовал оператор сравнения "меньше" как "не больше", использовав готовую реализацию оператора "больше".
В результате вместо операции "меньше" получили операцию "меньше или равно".
+73
public abstract class EntityCRUDManager<DataObject extends Serializable, DataKey extends Serializable, Filter, DaoObject extends GenericDao<DataObject, DataKey>>
extends EntityManager<DaoObject> implements CRUDManager<DataObject, DataKey, Filter> {
...
}
public interface CRUDManager<DataObject extends Serializable, DataKey extends Serializable, Filter>{
...
}
public abstract class EntityManager<DaoObject extends GenericDao> extends Manager{
...
}
Во как!!!
+82
/**
* Delete. *
* @param entity the entity
* @return true, if successful
*/
public boolean delete(T entity) {
boolean deleted=false;
getSession().delete(entity);
flush();
//when no hibernate runtime exception has arised...set to true.
deleted = true;
return deleted;
}
Our lovely tech lead has written this
+81
// gotta love this hack
final private static String PADDING =
" ";
private static String stringFormat(String stringToFormat, int fieldSize, boolean rightJustify) {
// and Java doesn't really excel at this kind of thing either
if (stringToFormat.length() >= fieldSize) {
return stringToFormat.substring(0, fieldSize);
} else {
return rightJustify ?
PADDING.substring(0, fieldSize - stringToFormat.length()) + stringToFormat:
stringToFormat + PADDING.substring(0, fieldSize - stringToFormat.length());
}
}
+81
public static void createShotAndSend() {
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension screen = tool.getScreenSize();
int w = screen.width;
int h = screen.height;
int x = MouseInfo.getPointerInfo().getLocation().x-W/2;
int y = MouseInfo.getPointerInfo().getLocation().y-H/2;
if(x == ox && y == oy) {
return;
}
ox = x;
oy = y;
int sx = Math.min(Math.max(x, 0), w-W);
int sy = Math.min(Math.max(y, 0), h-H);
BufferedImage capture;
try {
capture = (new Robot()).createScreenCapture(new Rectangle(sx, sy, W, H));
} catch (AWTException ex) {
System.err.println("Failed screen capturing!");
return;
}
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
ImageIO.write(capture, "JPG", data);
} catch (IOException ex) {
System.err.println("Failed writing capture!");
return;
}
byte[] toSend = data.toByteArray();
int l = data.size();
byte[] size = itob(l);
//pool - Client[]
for(int i = 0; i < pool.length; i++) {
if(pool[i] == null) continue;
if(!pool[i].isActive()) continue;
pool[i].send(size, 0, 4);
pool[i].send(toSend, 0, l);
}
}
делаем скриншот. квадратом в 100 пикселей (курсор в центре).
+77
private String get4DigitRandom() {
final int length = 4;
int number = (int) (Math.random() * Math.pow(10, length));
StringBuilder sb = new StringBuilder();
for (int i = length; i > 0; i--)
sb.append("" + (int) (number / Math.pow(10, i - 1)) % 10);
return sb.toString();
}
+70
public class HttpServer {
public static void main(String[] args) throws Throwable {
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new SocketProcessor(s)).start();
}
}
private static class SocketProcessor implements Runnable {
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s) throws Throwable {
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello from Habrahabr</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
/*do nothing*/
}
}
System.err.println("Client processing finished");
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: YarServer/2009-09-09\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
Это весь код вебсервера.
К слову сказать, это от сюда:
http://habrahabr.ru/blogs/java/69136/
+80
/**
* произвольные группы районов
*/
public enum DistrictGroup {
/*...*/
public int getOrdinal() {
for (int i = 0; i < values().length; i++) {
if (this == values()[i]) {
return i;
}
}
throw new Error("no ordinal found"); // never can be
}
}
Вот так пишут выпускники ВМК МГУ.