- 1
https://youtu.be/hB6eY73sLV0?t=241
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+70
https://youtu.be/hB6eY73sLV0?t=241
Исполнение произвольного кода(в данном случае Flappy Bird) в Super Mario World. Запись инструкций в память происходит посредством прыжков в нужных координатах.
+70
List<Integer> positionList = new ArrayList<Integer>(positions.keySet());
Collections.sort(positionList, new Comparator<Integer>() {
@Override
public int compare(Integer lhs, Integer rhs) {
if (lhs > rhs) {
return 1;
} else if (lhs < rhs) {
return -1;
}
return 0;
}
});
Видать разработчику за кол-во написанных строк платили...
+70
public class ConcurrentStringStatsProvider implements StringStatsProvider {
private final ExecutorService executor;
private final ExecutorCompletionService<CharCounter> service;
private final int threadNum;
public ConcurrentStringStatsProvider() {
//http://stackoverflow.com/questions/13834692/threads-configuration-based-on-no-of-cpu-cores
threadNum = Runtime.getRuntime().availableProcessors() + 1;
executor = Executors.newFixedThreadPool(threadNum);
this.service = new ExecutorCompletionService<CharCounter>(executor);
}
@Override
public synchronized CharCounter countChars(String str) {
int length = str.length();
if (length == 0)
return new CharCounter();
int chunk = length / threadNum;
if (chunk == 0)
chunk = length;
for (int i = 0; i < threadNum; i++) {
int start = i * chunk;
int end = (i + 1) * chunk - 1;
if (end > length) {
end = length - 1;
}
service.submit(new SubstringTask(start, end, str));
if (end == length - 1)
break; //break early
}
CharCounter result = null;
while (true) {
Future<CharCounter> future = service.poll();
if (future == null) {
if (result != null && result.getTotalCount() == length)
break;
else
continue;
}
CharCounter subResult = null;
try {
subResult = future.get();
} catch (InterruptedException e) {
log.error("Failed to calculate. Interrupted: ", e);
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
log.error("Calculation error", e);
throw new IllegalStateException("Calculation error: ", e);
}
if (result == null) {
result = subResult;
} else if (result.equals(subResult)) {
break; //!!
} else {
service.submit(new MergeTask(result, subResult));
result = null;
}
}
return result;
}
private class SubstringTask implements Callable<CharCounter> {
private final int start;
private final int end;
private final String str;
public SubstringTask(int start, int end, String str) {
this.start = start;
this.end = end;
this.str = Objects.requireNonNull(str);
}
@Override
public CharCounter call() throws Exception {
return doJob();
}
private CharCounter doJob() {
CharCounter charCounter = new CharCounter(end - start + 1);
for (int i = start; i <= end; i++) {
charCounter.increment(str.charAt(i));
}
return charCounter;
}
}
private class MergeTask implements Callable<CharCounter> {
private final CharCounter cc1, cc2;
public MergeTask(CharCounter cc1, CharCounter cc2) {
this.cc1 = Objects.requireNonNull(cc1);
this.cc2 = Objects.requireNonNull(cc2);
}
@Override
public CharCounter call() throws Exception {
return CharCounter.merge(cc1, cc2);
Первое знакомство с ExecutorCompletionService, решал задачку подсчета количества символов в строке в несколько потоков.
+70
public static List<Defaulter> getDefaulterList() {
List<Defaulter> defaulters = new ArrayList<Defaulter>();
for (Map.Entry<Class<?>, Defaulter> defaulterEntry : hash.entrySet()) {
Defaulter def = defaulterEntry.getValue();
defaulters.add(def);
}
return defaulters;
}
Всё заменилось одной строкой:
return new ArrayList<Defaulter>(hash.values());
+70
QString windoliz_path(QString str)
{
/*
функция "виндолизирует" QTшные пути, для передачи в неQTшные части проги
(в QT-шные, кстати тоже можно, ибо QT вроде бы понимает и те и другие ;)
если вызвать вне винды ничо страшного, предпроцессор сделает всё за вас
и функция вернёт ту же строку что и получила. После вызова в виндах не
помешает сделать .toLocal8Bit()
//*/
#ifdef _WIN32 //если венда
char s = '\\'; //символ для замены
char t = '/'; //шаблон поиска
for (int i = str.size();i;i--) //повторить столько раз сколько символов в строке
{
if (str[i-1] == t) //если символ соответствует образцу поиска
{
str[i-1] = s; //меняем на образец замены
}
}
#endif //директива отметы условия "если венда"
return str;
}
Этот проект не перестаёт удивлять... апи не смотри, велосипеды пиши. Коммент сохранен авторский.
+70
* Calculates the minimum number of bits necessary to represent the given number. The
* number should be given in its unsigned form with the starting bits equal to 1 if it is
* signed. Repeatedly compares number to another unsigned int called x.
* x is initialized to 1. The value of x is shifted left i times until x is greater
* than number. Now i is equal to the number of bits the UNSIGNED value of number needs.
* The signed value will need one more bit for the sign so i+1 is returned if the number
* is signed, and i is returned if the number is unsigned.
* @param number the number to compute the size of
* @param bits 1 if number is signed, 0 if unsigned
*/
public static int minBits(int number, int bits)
{
int val = 1;
for (int x = 1; val <= number && !(bits > 32); x <<= 1)
{
val = val | x;
bits++;
}
if (bits > 32)
{
assert false : ("minBits " + bits + " must not exceed 32");
}
return bits;
}
Адоб, как обычно, порадовал (условие окончания цикла).
[color=blue]https://git-wip-us.apache.org/repos/asf/flex-sdk/repo?p=flex-sdk.git;a=blob;f=modules/swfutils/src/java/flash/swf/SwfEncoder.java;h=03a100dda92989d537b00b 96033d614c73c47801;hb=HEAD#l320[/code]
+70
public void testTranlateScript() throws Exception {
// Инициализируем бесконечный цикл переводов. Должен переводить пока не
// кончатся тексты, ну или пока не зависнет. Потом кинет Exception.
int i = 1;
while (true) {
int j = 1;
// Фильтруем по непереведенному на какой-то язык и нажимаем первую
// ссылку "Перевести". Нужно указывать алиас языка на который
// переводим в фильтре.
driver.findElement(By.id("content_filter_header")).click();
System.out.println(i
+ "."
+ j
+ " "
+ "начинаем настройку фильтра "
+ driver.findElement(By.id("content_filter_header"))
.toString());
j++;
new Select(driver.findElement(By.id("filter-lang-type")))
.selectByVisibleText("Не переведено на язык(и)");
driver.findElement(By.id("filter-lang-alias-en")).click();
System.out.println(i
+ "."
+ j
+ " "
+ "заканчиваем настройку фильтра "
+ driver.findElement(By.id("filter-lang-alias-en"))
.toString());
j++;
driver.findElement(By.name("btn_filter")).click();
System.out.println(i + "." + j + " "
+ "нажимаем на кнопку Применить "
+ driver.findElement(By.name("btn_filter")).toString());
j++;
driver.findElements(By.linkText("Перевести")).get(0).click();
System.out.println(i
+ "."
+ j
+ " "
+ "нажимаем на первую ссылку Перевести "
+ driver.findElements(By.linkText("Перевести")).get(0)
.toString());
j++;
// Ищем оригинальный текст и присваеваем его переменной
for (int second = 0;; second++) {
if (second >= 60)
fail("timeout");
try {
if (isElementPresent(By.id("original-text")))
break;
} catch (Exception e) {
}
Thread.sleep(1000);
}
// driver.findElement(By.id("original-text")).isDisplayed();
String text_to_translate = driver.findElement(
By.id("original-text")).getText();
System.out.println(i + "." + j + " " + "текст получен: '"
+ text_to_translate + "' "
+ driver.findElement(By.id("original-text")).toString());
j++;
if ((text_to_translate == null) || (text_to_translate.equals(""))) {
System.out.println(i + "." + j + " "
+ "Выход по break (пустой текст):"+ "'" + text_to_translate + "'");
j++;
break;
}
// Вот это по идее должно не допускать, пустые стринги в тех
// случаях, если не сработал локатор.
// Идем в гугл и переводим текст из переменной. Тут нужно
// указывать
// алиасы языков с которого и на который переводим.
driver.get("https://translate.google.com/#ru/en/"
+ text_to_translate);
// Ждем элемент с переведенным текстом и присваиваем его новой
// переменной.
driver.findElement(By.id("source")).isDisplayed();
String text_translated = driver.findElement(By.id("result_box"))
.getText();
// Возвращаемся на сайт и снова точно также фильтруем.
driver.get(baseUrl + "/admin/translate");
driver.findElement(By.id("content_filter_header")).click();
System.out.println(i
+ "."
+ j
+ " "
+ "снова начинаем настройку фильтра "
+ driver.findElement(By.id("content_filter_header"))
.toString());
j++;
new Select(driver.findElement(By.id("filter-lang-type")))
.selectByVisibleText("Не переведено на язык(и)");
driver.findElement(By.id("filter-lang-alias-en")).click();
System.out.println(i
+ "."
+ j
+ " "
+ "снова заканчиваем настройку фильтра "
+ driver.findElement(By.id("filter-lang-alias-en"))
http://pastebin.com/hQdwHepm
+70
public class MyFancyException extends Exception {
public MyFancyException(Throwable cause) {
super(cause);
}
static public <X extends Throwable> void foo() throws X {
try {
throw new MyFancyException(new Exception());
}
catch (MyFancyException ex) {
throw (X) ex.getCause();
}
}
public static void main(String[] args) throws IOException {
MyFancyException.<IOException>foo();
}
}
Прекрасный способ отстрелить себе ногу. Метод foo() может кинуть любое исключение, даже если его нет в списке throws
+70
{
final int p = page;
final boolean current = p == 1;
this.pagercell(writer, current, 1, "<<");
}
for (int p = page - this.size; p < page; p++) {
if (p >= 1) {
final boolean current = p == 1;
this.pagercell(writer, current, p);
}
}
{
final int p = page;
final boolean current = (p - this.size) < 1;
this.pagercell(writer, current, p - this.size, "<");
}
{
final int p = page;
final boolean current = p == page;
this.pagercell(writer, current, p);
}
{
final int p = page;
final boolean current = (p + this.size) > pages;
this.pagercell(writer, current, p + this.size, ">");
}
for (int p = page + 1; p <= (page + this.size); p++) {
if (p <= pages) {
final boolean current = p == pages;
this.pagercell(writer, current, p);
}
}
{
final int p = page;
final boolean current = p == pages;
this.pagercell(writer, current, pages, ">>");
}
веселый вывод постраничной навигации (кусок метода)
+70
qDebug() << QString("%1-%2").arg("%1").arg("foo");