- 1
- 2
- 3
- 4
- 5
- 6
- 7
function main() {
let arr = [1, 2, 3];
for (const v of arr.map(x => x + 1)) print(v);
print("done.");
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
function main() {
let arr = [1, 2, 3];
for (const v of arr.map(x => x + 1)) print(v);
print("done.");
}
Для тех кто не понял предыдущий пример.. я упростил для вас :)
0
%% Note: set and unset are not thread-safe.
-spec set(key(), value()) -> ok.
set(Key, Value) ->
case ets:lookup(?status_tab, Key) of
[{_, {set, _OldValue}}] ->
ets:insert(?status_tab, {Key, {set, Value}});
[{_, {unset, Pid}}] ->
MRef = monitor(process, Pid),
Pid ! {set, Value},
receive
{'DOWN', MRef, _, _, _} -> ok
end;
[] ->
case ets:insert_new(?status_tab, {Key, {set, Value}}) of
true ->
ok;
false ->
set(Key, Value)
end
end,
ok.
-spec unset(key()) -> ok.
unset(Key) ->
case ets:lookup(?status_tab, Key) of
[{_, {set, _OldValue}}] -> ets:delete(?status_tab, Key);
_ -> ok
end,
ok.
-spec read(key()) -> value().
read(Key) ->
case read_or_wait(Key) of
{set, Value} ->
Value;
{wait, MRef} ->
receive
{'DOWN', MRef, _, _, {cvar_set, Value}} ->
Value;
{'DOWN', MRef, _, _, noproc} ->
read(Key)
end
end.
-spec read_or_wait(key()) -> {set, value()} | {wait, reference()}.
read_or_wait(Key) ->
case ets:lookup(?status_tab, Key) of
[] ->
{Pid, MRef} = spawn_monitor(?MODULE, waker_entrypoint, [Key, self()]),
receive
{Pid, proceed} ->
{wait, MRef};
{'DOWN', MRef, _, _, Reason} ->
cvar_retry = Reason,
read_or_wait(Key)
end;
[{_, {set, Val}}] ->
{set, Val};
[{_, {unset, Pid}}] ->
{wait, monitor(process, Pid)}
end.
-spec waker_entrypoint(key(), pid()) -> no_return().
waker_entrypoint(Key, Parent) ->
case ets_insert_new({Key, {unset, self()}}) of
false ->
exit(cvar_retry);
true ->
Parent ! {self(), proceed},
receive
{set, Value} ->
ets_insert({Key, {set, Value}}),
exit({cvar_set, Value})
end
end.
−1
#!/usr/bin/python
import sys
cache = {}
def count(start, end):
if start < end:
if start not in cache:
cache[start] = count(start + 1, end) + count(start * 2, end) + count(start ** 2, end)
return cache[start]
elif start == end:
return 1
else:
return 0
print(count(int(sys.argv[1]), int(sys.argv[2])))
Подсчитать количество путей из a в b с помощью прибавления единицы, умножения на 2 и возведения в квадрат
Чем формально ограничены возможности преобразовать рекурсию в хвостовую? Вот такое ведь не преобразовать?
0
import java.util.Arrays;
import java.util.Optional;
public class AntiVirus{
private int scanIntensity = 0;
//this method is ready for you.
public void setScanIntensity(int level){
scanIntensity = level;
}
//write this method.
public String scanFile(File file,VirusDB database){
String[] signature = database.getSignatures(scanIntensity);
String fileData = file.getData().toLowerCase();
Optional<String> res = Arrays.stream(signature)
.map(s -> s.toLowerCase())
.filter(fileData::contains).findAny();
String scan = " is safe";
if(res.isPresent()) {
System.out.println(res.get());
System.out.println("scan: " + scan);
scan = " is not safe";
System.out.println("scan after: " + scan);
}
return file.getName() + scan;
}
}
Не понимаю, почему не работает.
Задача
https://www.codewars.com/kata/5b13027eedd62c5216000001
Test Results:
AVTest
checkRandomFiles
Log
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
dos
scan: is safe
scan after: is not safe
expected:<f4wpzFoQD is [not ]safe> but was:<f4wpzFoQD is []safe>
Stack Trace
Completed in 476ms
checkSameFilesWithDifferentIntensitySett ings
Log
virus
scan: is safe
scan after: is not safe
expected:<file1 is [not ]safe> but was:<file1 is []safe>
Stack Trace
Completed in 1ms
Completed in 496ms
+1
Ltac destruct_mint_ H :=
match type of H with
(MInt_ _ ?z ?t) =>
lazymatch goal with
|- ?GOAL =>
refine (match H in (MInt_ _ z0 t0) return (z = z0 -> t = t0 -> GOAL) with
| mint_nil _ =>
fun Heq_z Heq_tt_ =>
ltac:(destruct_mint_common Heq_tt_ Heq_z H)
| mint_cons _ te rest l r t H =>
fun Heq_z Heq_tt_ =>
ltac:(destruct_mint_common Heq_tt_ Heq_z H)
| mint_cons_l _ te rest l r z t Hz H =>
fun Heq_z Heq_tt_ =>
ltac:(destruct_mint_common Heq_tt_ Heq_z H)
| mint_cons_r _ te te' rest l r z t Hz Hcomm H =>
fun Heq_z Heq_tt_ =>
ltac:(destruct_mint_common Heq_tt_ Heq_z H)
end (eq_refl z) (eq_refl t))
end
end.
Наебавшись с inversion в механизированным доказательстве, закрыл я очи.
0
class Animal {
move(distanceInMeters = 0) {
print(`Animal moved ${distanceInMeters}m.`);
}
}
function main() {
const dog = new Animal();
dog.move(10);
const dog2 = Animal();
dog2.move(11);
}
Загадка дня... кто знает что первый вызов конструктора отличается от второго?
+2
template<typename F, typename... CurryArgs>
struct curry {
F func;
std::tuple<CurryArgs...> tup{};
curry(F f) : func(std::move(f)) {}
template<typename... CtorArgs>
curry(F f, CtorArgs &&... args) : func(std::move(f)), tup(std::forward<CtorArgs>(args)...) {}
template<typename Tup1, typename Tup2>
curry(F f, Tup1 && tup1, Tup2 && tup2) : func(std::move(f)), tup(std::tuple_cat(tup1, tup2)) {}
template<typename... Args>
auto operator()(Args &&... args)
{
constexpr size_t have_args = sizeof...(Args) + sizeof...(CurryArgs);
constexpr size_t need_args = detail::functor_traits<F>::args_count;
if constexpr (have_args > need_args) {
static_assert(!sizeof(std::tuple_element_t<0, std::tuple<Args...>>*),
"Too many arguments.");
} else if constexpr (have_args == need_args) {
return std::apply(func, std::tuple_cat(tup, std::tuple(std::forward<Args>(args)...)));
} else {
return curry<decltype(func), CurryArgs..., Args...>(func, tup, std::tuple(std::forward<Args>(args)...));
}
}
};
int main()
{
auto f = [](int a, float b, const std::string & c) -> int {
std::cout << "Functor! a = " << a << ", b = " << b << ", c = " << c << std::endl;
return a + static_cast<int>(b);
};
std::cout << f(16, 42.1f, "Hello") << std::endl;
auto c0 = curry(f);
auto c1 = c0(16);
auto c2 = c1(42.1f);
c0(16)(42.1f)("Hello");
c1(42.1f)("Hello");
c2("Hello");
c0(16, 42.1f)("Hello");
c0(16, 42.1f, "Hello");
c1(42.1f, "Hello");
}
Каррировали-каррировали, да выкаррировали.
https://wandbox.org/permlink/LPXFUNpWOREcB3wH
+3
std::cout << "Creating ptr1!" << std::endl;
auto ptr1 = make_nft<Cow>();
std::cout << "ptr1(" << &ptr1 << "): " << ptr1.get() << std::endl;
ptr1->MakeSound();
std::cout << "Creating ptr2!" << std::endl;
nft_ptr<Animal> ptr2;
std::cout << "ptr2(" << &ptr2 << "): " << ptr2.get() << std::endl;
std::cout << "Moving: ptr2 = std::move(ptr1)" << std::endl;
ptr2 = std::move(ptr1);
std::cout << "Moved: ptr1 = " << ptr1.get() << " ptr2 = " << ptr2.get()
<< std::endl;
https://github.com/zhuowei/nft_ptr
"C++ std::unique_ptr that represents each object as an NFT on the Ethereum blockchain."
+1
Class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
https://javadoc.io/doc/org.aspectj/aspectjweaver/1.8.10/org/aspectj/weaver/patterns/HasThisTypePatternTriedToSneakInSomeGene ricOrParameterizedTypePatternMatchingStu ffAnywhereVisitor.html
+2
/**
* Change the zoom level to the specified value. Specify 0.0 to reset the
* zoom level.
*
* @param zoomLevel The zoom level to be set.
*/
public void setZoomLevel(double zoomLevel);
Когда-то я думал, что zoom 100% это 1.0. И что на zoom нужно умножать. Но оказалось, что я анскильный.