- 1
- 2
- 3
try{
throw Exception();
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+3
try{
throw Exception();
}
Мне в сонном бреду пришла мысль, а нахера обязательный catch?
finally везде необязательно.
try{ //исключения не пройдут
}
//вполне по крестоблядски
+1
public static CategoryAttribute Build(string category_name, string attribute_type, string attribute_name, object attribute_value)
{
try
{
CategoryAttribute document_attribute;
switch(attribute_type)
{
case "string":
case "double_as_string":
document_attribute = new CategoryAttribute(category_name, attribute_name, TypeEnum.String);
break;
case "string_as_date":
document_attribute = new CategoryAttribute(category_name, attribute_name, TypeEnum.DateTime);
break;
case "int":
case "double_as_int":
document_attribute = new CategoryAttribute(category_name, attribute_name, TypeEnum.Integer);
break;
case "double":
document_attribute = new CategoryAttribute(category_name, attribute_name, TypeEnum.Double);
break;
default:
throw new ApplicationException("Не верно настроен тип данных атрибута '" + attribute_name + "' категории '" + category_name + "'.");
}
if (attribute_value == null)
return document_attribute;// атрибут остался неопределенным
switch (document_attribute.Type)
{
case TypeEnum.String:
{
switch (attribute_type)
{
case "string":
{
if (!(attribute_value is string))
throw new ApplicationException("Тип данных '" + attribute_value.GetType() + "' входного значения атрибута '" + attribute_name
+ "' категории '" + category_name + "' не может быть приведен к требуему типу данных '" +
attribute_type + "'.");
document_attribute.sValue = attribute_value as string;
} break;
case "double_as_string":
{
if (!(attribute_value is double))
throw new ApplicationException("Тип данных '" + attribute_value.GetType() + "' входного значения атрибута '" + attribute_name
+ "' категории '" + category_name + "' не может быть приведен к требуему типу данных '" +
attribute_type + "'.");
document_attribute.sValue = ((double)attribute_value).ToString();
} break;
}
}
break;
case TypeEnum.Integer:
{
switch (attribute_type)
{
case "int":
{
if (!(attribute_value is int))
throw new ApplicationException("Тип данных '" + attribute_value.GetType() + "' входного значения атрибута '" + attribute_name
+ "' категории '" + category_name + "' не может быть приведен к требуему типу данных '" +
attribute_type + "'.");
document_attribute.iValue = (int)attribute_value;
} break;
case "double_as_int":
{
if (!(attribute_value is double))
throw new ApplicationException("Тип данных '" + attribute_value.GetType() + "' входного значения атрибута '" + attribute_name
+ "' категории '" + category_name + "' не может быть приведен к требуему типу данных '" +
attribute_type + "'.");
document_attribute.iValue = (int)(double)attribute_value;
} break;
}
}
break;
case TypeEnum.Double:
{
if (!(attribute_value is float || attribute_value is double || attribute_value is int || attribute_value is long))
throw new ApplicationException("Тип данных '" + attribute_value.GetType() + "' входного значения атрибута '" + attribute_name
+ "' категории '" + category_name + "' не может быть приведен к требуему типу данных '" + attribute_type + "'.");
document_attribute.dValue = (double)attribute_value;
}
break;
}
return document_attribute;
catch (Exception e)
{
//...
}
}
Создание объекта типа CategoryAttribute.
+8
if(user.pass = pass_to_hash(password)){
return done(null, user);
}else{
return done('incorrect password');
}
Факир был пьян, и запер дверь, забыв ее закрыть)
+5
namespace ConsoleApplication
{
public static class Program
{
private static void Main( string[] args )
{
new Random().Next( -100, 100 )
.Execute( x => Console.Write( $"{x} это " ) )
.IfElse( x => x % 2 == 0, () => Console.Write( "четное " ), () => Console.Write( "нечетное " ) )
.Execute( () => Console.Write( "число " ) )
.IfElse( x => x > 0, () => Console.Write( "больше " ), () => Console.Write( "меньше " ) )
.Execute( () => Console.Write( "нуля" ) )
.Execute( () => Console.WriteLine() );
}
}
}
вывод в консоли (прим.): "-88 это четное число меньше нуля"
Адские экстеншены
0
public function callCost($fromCity, $fromStreet, $fromHouse, $fromHousing, $fromBuilding, $fromPorch, $fromLat, $fromLon, $toCity, $toStreet, $toHouse, $toHousing, $toBuilding, $toPorch, $toLat, $toLon, $clientName, $phone, $priorTime, $customCarId, $customCar, $carType, $carGroupId, $tariffGroupId, $comment, $additional = '')
{
if ($json = $this->reqCache->getValue($fromLat . $fromLon . $toLat . $toLon . $phone . $priorTime . $tariffGroupId . $comment . $additional)) {
$data = json_decode($json);
return $data;
} else {
$tariffGroupId = $this->findTariffOnCarType($carType);
$additional = explode(';', $additional);
$route = new TaxiRouteAnalyzer($this->dbHost, $this->database, $this->dbLogin, $this->dbPass);
$this->writeLog($tariffGroupId);
$data = $route->analyzeRoute(1, $fromCity, $fromStreet, $fromHouse, $fromHousing, $fromLat, $fromLon, $toCity, $toStreet, $toHouse, $toHousing, $toLat, $toLon, $additional, $tariffGroupId, $this->isDay(), 1);
$res = json_encode($data);
$this->reqCache->setValue($fromLat . $fromLon . $toLat . $toLon . $phone . $priorTime . $tariffGroupId . $comment . $additional, $res, $this->cacheTime);
return $data;
}
}
человеку доверили сделать кэширование данных...
+1
var cloths = {
<?php foreach ($clothList as $cloth): ?>
"<?=$cloth->id()?>": {
"id": <?=$cloth->id()?>,
"name": "<?=$cloth->name()?>",
"public_name": "<?=str_replace('"', '\"', $cloth->public_name())?>"
},
<?php endforeach; ?>
"dummy": {}
};
+1
if (dlgOpen.ShowDialog() != DialogResult.OK) return;
txtLog.Clear();
string customXMLFileName = dlgOpen.FileName;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(customXMLFileName);
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
{
if (node.Name == "Surfaces")
{
foreach (XmlNode childNode in node.ChildNodes)
{
txtLog.AppendText(childNode.Name.ToString() + Environment.NewLine);
foreach (XmlNode _childNode in childNode.ChildNodes)
{
if (_childNode.Name == "SourceData")
{
foreach (XmlNode __childNode in _childNode.ChildNodes)
{
txtLog.AppendText(__childNode.Name.ToString() + Environment.NewLine);
if (__childNode.Name == "Breaklines")
{
foreach (XmlNode ___childNode in __childNode.ChildNodes)
{
txtLog.AppendText(___childNode.Name.ToString() + Environment.NewLine);
XmlNode dataNode = ___childNode.LastChild;
string txtData = dataNode.InnerText;
txtLog.AppendText(txtData + Environment.NewLine);
}
}
}
}
}
}
}
}
Невнимательное чтение MSDN привело к такому плачевному результату. А всего лишь хотелось прочитать значение дочерних нод Breaklines....
GetElementsByTagName в помощь....
+8
public static class StringExtensions
{
public static bool IsNulldOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
why
0
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <stdio.h>
std::vector<int> A, B, C;
void build(const std::vector<int> A, int k, int razmer){
int n = razmer;
B.resize(n);
C.resize(n);
B.front() = A.front();
C.back() = A.back();
k--;
for(int i1(1), i2(n - 2); i1 < n; i1++, i2--){
B[i1] = (i1 % k) ? std::max(A[i1], B[i1 - 1]) : A[i1];
C[i2] = ((i2 + 1) % k) ? std::max(A[i2], C[i2 + 1]) : A[i2];
}
}
int main(){
int m, count;
A.resize(100001);
scanf("%d", &m);
count = 0;
while(true){
scanf("%d", &A[count]);
if(A[count] == -1) break;
count++;
}
build(A, m, count);
int l = 0;
while(count - 1 >= m){
printf("%d\n", std::max(C[l], B[l + m - 1]));
l++;
}
return 0;
}
Код, реализующий поиск максимума по подотрезках последовательности чисел. Если непонятно, то тут строится дерево отрезков, и потом с ним происходит какая-то ебола. Красивое решение получается при использовании стандартного алгоритма поиска максимума в очереди за O(1) при помощи двух стеков.
+1
<script>
var link=window.location.href;
var arr = link.split("#");
document.write("<script> function fuk_flash(){");
if (arr[1] != "d4"){
document.write("appD4.setAttribute(\"style\", \"display:none\");");
}
if (arr[1] != "d5"){
document.write("appD5.setAttribute(\"style\", \"display:none\");");
}
if (arr[1] != "f"){
document.write("appF.setAttribute(\"style\", \"display:none\");");
}
document.write("}<\/script>");
</script>
<script>
window.onload=fuk_flash;
</script>
Когда на странице 3 флэшки, необходимо показывать только одну, исходя из атрибутов ссылки, и когда ни одна из них не показывает полосу загрузки (при своем немалом весе) после обращения к себе, и когда все более-менее адекватные решения провалились.
(Но проблема оказалась в том, что флэш находил в адресе страницы # и переставал грузиться)