1. JavaScript / Говнокод #16539

    +156

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    var day = new Date(values.date_b.substring(0, 10));
                var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
                var curDay = day.getDay();
                for(var i = 0; i < days.length; i++) {
                    if (days[i] == days[ day.getDay() ]) {
                        curDay = i;
                        break;
                    }
                }
                curDay = (curDay == 0) ? 7 : curDay;

    dr_Lev, 15 Августа 2014

    Комментарии (0)
  2. PHP / Говнокод #16538

    +154

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    <?php
    
    	/* Initialize Joomla framework */
    	define( '_JEXEC', 1 );
    	define('JPATH_BASE', dirname(__FILE__) );
    	define( 'DS', DIRECTORY_SEPARATOR );
    	/* Required Files */
    	require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
    	require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
    	/* To use Joomla's Database Class */
    	require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
    
    	$db =& JFactory::getDBO();
    	$query = $db->getQuery(true);
    	
    	if( $_POST['quest'] == 'getprotfolio' && array_key_exists('getreviews',$_POST) && array_key_exists('id',$_POST) ) {
    		
    		$query = 'SELECT catid FROM jos_k2_items WHERE id = '. $_POST['id'];
    		$db->setQuery($query);  
    		$catid = $db->loadResult();
    		
    		$query2 = 'SELECT * FROM jos_k2_items WHERE catid = '. $catid .' AND published = 1 AND trash = 0 AND id != '. $_POST['id'] .' ORDER BY rand() LIMIT 1';
    		$db->setQuery($query2);
    		$request = $db->loadObject();
    		$extra_fields = json_decode($request->extra_fields);
    
    		$quantitys = explode(",", $extra_fields[1]->value);
    		$tooltips = "";
    		$count = 0;
    		$xlabel = "";
    		foreach($quantitys as $quantity) {
    			if($count != 0) {
    				$tooltips .= ",";
    			}
    			$tooltips .= "'". $quantity . "'";
    			$count++;
    			$xlabel .= "'". $count . "',";
    		}
    		$xlabel = substr($xlabel, 0, -1);
    		$count--;	
    		
    		if($_POST['getreviews'] == 'true') {
    			$result = '<div class = "itemContainer"><div class = "item" id = "'. $request->id .'"><div class = "item-title">'. $request->title .'</div>';			
    			$result .= '<div class = "grid_4 proImage" style = "margin-top: 10px;"><div class = "project-bg"><img src="'. $extra_fields[2]->value .'" style = "width: 272px; height: auto;" /></div>';
    			$result .= '<div class = "underImg"><a class = "domen" href = "http://'. $extra_fields[0]->value .'" rel = "nofollow" target = "_blank">'. $extra_fields[0]->value .'</a><a href = "#" class = "getreview">Прочитать отзыв</a></div></div>' . $request->introtext . '<div class = "grid_8"><div class="title">Наши результаты:</div><ul><li>'. $extra_fields[3]->value .'</li><li>'. $extra_fields[4]->value . '</li></ul></div>';
    			$result .= '<div class = "grid_8 grafik"><div class = "title">График посещаемости сайта:</div><div class = "title-y"></div><canvas id="cvs" width="560" height="260">[No canvas support]</canvas></div>';		
    			$result .= '<a class = "another" href = "#"><span>Другой проект</span></a></div>';
    			$query3 = 'SELECT * FROM jos_k2_items WHERE published = 1 AND trash = 0 AND catid = 5';
    			$db->setQuery($query3);
    			$requests = $db->loadObjectList();
    			foreach($requests as $request) {
    				$extra = json_decode($request->extra_fields);
    				if($extra[1]->value == $extra_fields[0]->value) {
    					$result .= '<div class = "review grid_12"><div class = "photo"><img src = "'. $extra[2]->value .'" /></div>';
    					$result .= '<div class = "text"><div class = "arrow"></div><div class = "title">'. $request->title .'</div>';
    					$result .= '<strong>'. $extra[0]->value .'</strong>'. $request->introtext .'</div></div>';
    				}
    			}			
    			$result .= '<div class = "clr"></div><div class = "grid_12 another-project">Список проектов</div></div>';
    
    			//здесь получим и обработаем данные по 4 проектам
    			$query = 'SELECT * FROM jos_k2_items WHERE published = 1 AND trash = 0 AND catid = 6 AND trash = 0 AND id != '. $request->id .' ORDER BY rand() LIMIT 4';
    			$db->setQuery($query);
    			$requests = $db->loadObjectList();
    			$index = 0;			
    			$script = '<script>function newChart(){var line = new RGraph.Line("cvs", ['. $extra_fields[1]->value .'])
    				.Set("tooltips.css.class", "line_chart_tooltips_css")
    				.Set("tooltips", ['. $tooltips .'])
    				.Set("tooltips.hotspot.xonly", true)
    				.Set("filled", true)
    				.Set("fillstyle", "Gradient(rgba(192, 67, 197, 0.5):rgba(192, 67, 197, 0.5):rgba(255, 255, 255, 0):rgba(255, 255, 255, 0))")
    				.Set("linewidth", 2)
    				.Set("tickmarks", "circle")
    				.Set("colors", ["#c043c5"])
    				.Set("background.grid.dashed", true)
    				.Set("background.grid.autofit.numvlines", '. $count .')				
    				.Set("noaxes", true)						
    				.Set("ylabels", false)
    				.Set("gutter.bottom", 35)						
    				.Set("gutter.left", 50)
    				.Draw();
    			var xaxis = new RGraph.Drawing.XAxis("cvs", line.canvas.height - line.gutterBottom)
    				.Set("labels", ['. $xlabel .'])
    				.Set("labels.position", "edge")
    				.Set("numticks", 0)
    				.Set("colors", ["#dedede"])						
    				.Set("text.color", "#676666")
    				.Set("gutter.left", 50)						
    				.Draw();
    			var yaxis = new RGraph.Drawing.YAxis("cvs", 50)
    				.Set("scale.zerostart", false)
    				.Set("max", line.max)
    				.Set("numticks", 0)	
    				.Set("colors", ["#dedede"])
    				.Set("text.color", "#c043c5")
    				.Set("gutter.bottom", 35)
    				.Draw();
    			line.canvas.onmouseout = function () {
    				// Hide the tooltip
    				RGraph.HideTooltip();

    Frozen, 15 Августа 2014

    Комментарии (0)
  3. JavaScript / Говнокод #16537

    +159

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    недавно на хабре была статья "Платформер на Three.js"
    
    так вот автор уверяет, что
    "Читателям с нешкольным образованием или ветеранам игростроя этот псевдокод известен под названием «метод Эйлера», а также известно что этот метод — просто отстой."
    и приводит картинки из википедии, где им решают достаточно сложный дифур
    а вот свой "школьный" дифур он решил вот так
    
    if( в воздухе ) playerVelocity.y -= gravity * time;
    playerPosition += playerVelocity * time;
    
    "Как видим, запустив игру в firefox, мы получим одну динамику, а запустив её в chrome — совершенно иную. Поведение персонажа будет «плавать» в зависимости от интенсивности фоновых задач и расположения звёзд. Что же делать?"
    ответ-учиться программировать
    
    void update(float dt) {
    	pos += (velocity + force * dt * 0.5f) * dt;
    	velocity += force * dt;
    }
    
    оп-ля! все встало на свои места. теперь эйлер с  не фиксированным шагом НЕ ПЛАВАЕТ!

    FadeToBlack, 15 Августа 2014

    Комментарии (251)
  4. C# / Говнокод #16536

    +121

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    class Program
    {
    	static int x = 0;
    	
    	static int f()
    	{
    	x = x + 10;
    		return 1;
    	}
    	
    	public static void Main()
    	{
    		x += f();
    		System.Console.WriteLine(x);
    	}
    }

    Следите за руками! Чему же в итоге равно x?

    Проверить себя: http://ideone.com/v8rktM

    Источник: http://blogs.msdn.com/b/oldnewthing/archive/2014/08/14/10549885.aspx

    someone, 15 Августа 2014

    Комментарии (49)
  5. Java / Говнокод #16535

    +70

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    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

    jkhne4pijgberg, 15 Августа 2014

    Комментарии (2)
  6. C# / Говнокод #16534

    +134

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    for (var i = 0; i < numberPhone.Length; i++)
                    {
                        if (numberPhone[i] == ',')
                            return resultPhone;
                        if (Char.IsNumber(numberPhone[i]))
                        {
                            resultPhone += numberPhone[i];
                        }
                    }
                    return resultPhone;

    vladb9582, 14 Августа 2014

    Комментарии (10)
  7. PHP / Говнокод #16533

    +154

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    private function generate_accomodations_array($adults, $children, $ages) {
        $result = array();
        foreach($adults as $adult) {
          foreach($children as $child) {
            $param = array();
            if($child > 0) {
              for($age1=0; $age1<count($ages); $age1++) {
                if($child > 1) {
                  for($age2=$age1; $age2<count($ages); $age2++) {
                    $param = array($ages[$age1], $ages[$age2]);
                    $result[] = $this->generate_accomodations_row($adult, $child, $param);
                  }
                } else {
                  $param = array($ages[$age1]);
                  $result[] = $this->generate_accomodations_row($adult, $child, $param);
                }
              }
            } else {
              $result[] = $this->generate_accomodations_row($adult, $child, $param);
            }
          }
        }
        return $result;
      }
    
      private function generate_accomodations_row($adult = null, $child = null, $ages = null) {
        $result = array();
        if(!is_null($adult)) {
          $res_adult = array('adult' => $adult);
          $result = array_merge($result, $res_adult);
        }
        if(!is_null($child)) {
          $res_child = array('child' => $child);
          $result = array_merge($result, $res_child);
        }
        if(!is_null($ages)) {
          $res_ages = array();
          $i = 1;
          foreach($ages as $age) {
            $res_ages = array_merge(array('child-age'.$i++ => $age), $res_ages);
          }
          $result = array_merge($result, $res_ages);
        }
        if(!is_null($adult)) {
          for($i=0;$i<$adult;$i++) {
            $result['pegas_ages'][] = $this->adult_age;
          }
        }
        if(!is_null($ages)) {
          $result['pegas_ages'] = array_merge($result['pegas_ages'], $ages);
        }
        return $result;
      }

    govnocodegenerator, 14 Августа 2014

    Комментарии (0)
  8. Python / Говнокод #16528

    −88

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    class DataModel(dict):
        _SCHEME_VERSION = 0
        _transform = dict()
        _additional = dict()
        _migration = None
    
        def __init__(self, data=None, network=None, conf=None):
            if network and conf:
                _scheme = map(lambda x: x.strip(), conf.get(network).keys())
                _map =  map(lambda x: x.strip(), conf.get(network).values())
    
                self._scheme = int(conf._scheme)
    
                map(lambda x: setattr(self, x[0], data.get(x[1], None)),
                    [(_scheme[i], _map[i]) for i in xrange(0,len(_map))])
    
                if self._transform.get(network, False):
                    map(lambda x: setattr(self, x, getattr(self._transform[network], x)(getattr(self, x))),
                        [k for k in self._transform[network].__dict__.keys() if not k.startswith('__')])
            else:
                dict.__init__(self, data)
    
            if self.get('_scheme', 0)<self._SCHEME_VERSION and self._migration is not None:
                k = [int(k.split('_')[1]) for k in self._migration.__dict__.keys() if not k.startswith('__')]
                k.sort()
                [k.remove(x) for x in k if x<=self.get('_scheme', 0)]
                map(lambda x: getattr(self._migration, 'scheme_%s' % x)(self), k)
                self._scheme = self._SCHEME_VERSION
    
            map(lambda x: setattr(self, x, getattr(self._additional, x)(self)),
                [k for k in self._additional.__dict__.keys() if not k.startswith('__')])
    
        def __setattr__(self, name, val):
            if name in self.__dict__:
                self.__dict__[name]= val
            else:
                self[name] = val
    
        def __getattr__(self, name):
            if name in self.__dict__:
                return self.__dict__[name]
            else:
                return self[name]

    Mongo migration, written in Python, for human beings.

    vaxxxa, 14 Августа 2014

    Комментарии (1)
  9. PHP / Говнокод #16527

    +159

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    foreach ($val as $k => $v)
    		{
    			if (!is_array($v))
    			{
    				$val[$k] = htmlspecialcharsbx($v);
    			}
    			else
    			{
    				foreach ($v as $kp => $vp)
    				{
    					foreach ($vp as $kkp => $vvp)
    					{
    						if (!is_array($vvp))
    						{
    							$val[$k][$kp][$kkp] = htmlspecialcharsbx($vvp);
    						}
    						else
    						{
    							foreach ($vvp as $kvvp => $vvvp)
    							{
    								$val[$k][$kp][$kkp][$kvvp] = htmlspecialcharsbx($vvvp);
    							}
    						}
    					}
    				}
    			}
    		}

    clauclauclau, 14 Августа 2014

    Комментарии (108)
  10. 1C / Говнокод #16526

    −163

    1. 1
    2. 2
    3. 3
    4. 4
    Если ЗначениеЗаполнено(Сделка) И ЛЕВ(Сделка.Ссылка, 10) = "Заказ пост" Тогда
             //другой говнокод
    
    КонецЕсли;

    Правильная проверка типов

    alexinzaz, 14 Августа 2014

    Комментарии (40)