content
stringlengths
10
4.9M
<filename>pkg/gather/doc.go // Package gather contains platform specific methods for gathering console // logs. package gather
param = [{ 'bootstrap': True, 'max_depth': 10, 'max_features': 'sqrt', 'min_samples_leaf': 1, 'min_samples_split': 10, 'n_estimators': 749 }, { 'bootstrap': True, 'max_depth': 10, 'max_features': 'sqrt', 'min_samples_leaf': 1, 'min_samples_split': 10, 'n_estimators': 1062 }, { 'bootstrap': True, 'max_depth': 100, 'max_features': 'sqrt', 'min_samples_leaf': 1, 'min_samples_split': 2, 'n_estimators': 20 }, { 'bootstrap': True, 'max_depth': 10, 'max_features': 'sqrt', 'min_samples_leaf': 4, 'min_samples_split': 5, 'n_estimators': 645 }, { 'bootstrap': True, 'max_depth': 10, 'max_features': 'sqrt', 'min_samples_leaf': 4, 'min_samples_split': 10, 'n_estimators': 124 } ]
<filename>mdw-hub/src/com/centurylink/mdw/hub/servlet/TestCaseServlet.java package com.centurylink.mdw.hub.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.centurylink.mdw.common.service.ServiceException; import com.centurylink.mdw.services.ServiceLocator; import com.centurylink.mdw.services.TestingServices; import com.centurylink.mdw.test.TestCaseItem; /** * Serves up raw test cases and related resources. */ @WebServlet(urlPatterns={"/testCase/*", "/testResult/*"}, loadOnStartup=1) public class TestCaseServlet extends AssetContentServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TestCaseItem subItem = null; String path = request.getPathInfo().substring(1); String[] segments = path.split("/"); if (segments.length == 3) { TestingServices testingServices = ServiceLocator.getTestingServices(); try { subItem = testingServices.getTestCaseItem(path); } catch (ServiceException ex) { // todo log throw new IOException(ex.getMessage(), ex); } } if ("/testResult".equals(request.getServletPath())) { TestingServices testingServices = ServiceLocator.getTestingServices(); File resultsDir = testingServices.getTestResultsDir(); InputStream in = null; OutputStream out = response.getOutputStream(); try { File file = new File(resultsDir + request.getPathInfo()); if (!file.isFile()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } response.setContentType("text/plain"); in = new FileInputStream(file); int read = 0; byte[] bytes = new byte[1024]; while ((read = in.read(bytes)) != -1) out.write(bytes, 0, read); } finally { if (in != null) in.close(); } } else { if (subItem != null) { response.setContentType("application/json"); response.getWriter().println(subItem.getObject().toString(2)); } else { super.doGet(request, response); } } } }
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins.h" #include "src/code-stub-assembler.h" namespace v8 { namespace internal { class ArrayBuiltinCodeStubAssembler : public CodeStubAssembler { public: explicit ArrayBuiltinCodeStubAssembler(compiler::CodeAssemblerState* state) : CodeStubAssembler(state) {} typedef std::function<Node*(Node* o, Node* len)> BuiltinResultGenerator; typedef std::function<void(Node* a, Node* pK, Node* value)> CallResultProcessor; void GenerateIteratingArrayBuiltinBody( const char* name, const BuiltinResultGenerator& generator, const CallResultProcessor& processor, const Callable& slow_case_continuation) { Node* receiver = Parameter(IteratingArrayBuiltinDescriptor::kReceiver); Node* callbackfn = Parameter(IteratingArrayBuiltinDescriptor::kCallback); Node* this_arg = Parameter(IteratingArrayBuiltinDescriptor::kThisArg); Node* context = Parameter(IteratingArrayBuiltinDescriptor::kContext); Node* new_target = Parameter(IteratingArrayBuiltinDescriptor::kNewTarget); Variable k(this, MachineRepresentation::kTagged, SmiConstant(0)); Label non_array(this), slow(this, &k), array_changes(this, &k); // TODO(danno): Seriously? Do we really need to throw the exact error // message on null and undefined so that the webkit tests pass? Label throw_null_undefined_exception(this, Label::kDeferred); GotoIf(WordEqual(receiver, NullConstant()), &throw_null_undefined_exception); GotoIf(WordEqual(receiver, UndefinedConstant()), &throw_null_undefined_exception); // By the book: taken directly from the ECMAScript 2015 specification // 1. Let O be ToObject(this value). // 2. ReturnIfAbrupt(O) Node* o = CallStub(CodeFactory::ToObject(isolate()), context, receiver); // 3. Let len be ToLength(Get(O, "length")). // 4. ReturnIfAbrupt(len). Variable merged_length(this, MachineRepresentation::kTagged); Label has_length(this, &merged_length), not_js_array(this); GotoIf(DoesntHaveInstanceType(o, JS_ARRAY_TYPE), &not_js_array); merged_length.Bind(LoadJSArrayLength(o)); Goto(&has_length); Bind(&not_js_array); Node* len_property = GetProperty(context, o, isolate()->factory()->length_string()); merged_length.Bind( CallStub(CodeFactory::ToLength(isolate()), context, len_property)); Goto(&has_length); Bind(&has_length); Node* len = merged_length.value(); // 5. If IsCallable(callbackfn) is false, throw a TypeError exception. Label type_exception(this, Label::kDeferred); Label done(this); GotoIf(TaggedIsSmi(callbackfn), &type_exception); Branch(IsCallableMap(LoadMap(callbackfn)), &done, &type_exception); Bind(&throw_null_undefined_exception); { CallRuntime( Runtime::kThrowTypeError, context, SmiConstant(MessageTemplate::kCalledOnNullOrUndefined), HeapConstant(isolate()->factory()->NewStringFromAsciiChecked(name))); Unreachable(); } Bind(&type_exception); { CallRuntime(Runtime::kThrowTypeError, context, SmiConstant(MessageTemplate::kCalledNonCallable), callbackfn); Unreachable(); } Bind(&done); Node* a = generator(o, len); // 6. If thisArg was supplied, let T be thisArg; else let T be undefined. // [Already done by the arguments adapter] HandleFastElements(context, this_arg, o, len, callbackfn, processor, a, k, &slow); // 7. Let k be 0. // Already done above in initialization of the Variable k Bind(&slow); Node* target = LoadFromFrame(StandardFrameConstants::kFunctionOffset, MachineType::TaggedPointer()); TailCallStub( slow_case_continuation, context, target, new_target, Int32Constant(IteratingArrayBuiltinLoopContinuationDescriptor::kArity), receiver, callbackfn, this_arg, a, o, k.value(), len); } void GenerateIteratingArrayBuiltinLoopContinuation( const CallResultProcessor& processor) { Node* callbackfn = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kCallback); Node* this_arg = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kThisArg); Node* a = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kArray); Node* o = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kObject); Node* initial_k = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kInitialK); Node* len = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kLength); Node* context = Parameter(IteratingArrayBuiltinLoopContinuationDescriptor::kContext); // 8. Repeat, while k < len Variable k(this, MachineRepresentation::kTagged, initial_k); Label loop(this, &k); Label after_loop(this); Goto(&loop); Bind(&loop); { GotoUnlessNumberLessThan(k.value(), len, &after_loop); Label done_element(this); // a. Let Pk be ToString(k). Node* p_k = ToString(context, k.value()); // b. Let kPresent be HasProperty(O, Pk). // c. ReturnIfAbrupt(kPresent). Node* k_present = HasProperty(o, p_k, context); // d. If kPresent is true, then GotoIf(WordNotEqual(k_present, TrueConstant()), &done_element); // i. Let kValue be Get(O, Pk). // ii. ReturnIfAbrupt(kValue). Node* k_value = GetProperty(context, o, k.value()); // iii. Let funcResult be Call(callbackfn, T, «kValue, k, O»). // iv. ReturnIfAbrupt(funcResult). Node* result = CallJS(CodeFactory::Call(isolate()), context, callbackfn, this_arg, k_value, k.value(), o); processor(a, p_k, result); Goto(&done_element); Bind(&done_element); // e. Increase k by 1. k.Bind(NumberInc(k.value())); Goto(&loop); } Bind(&after_loop); Return(a); } void ForEachProcessor(Node* a, Node* p_k, Node* value) {} void SomeProcessor(Node* a, Node* p_k, Node* value) { Label false_continue(this), return_true(this); BranchIfToBooleanIsTrue(value, &return_true, &false_continue); Bind(&return_true); Return(TrueConstant()); Bind(&false_continue); } void EveryProcessor(Node* a, Node* p_k, Node* value) { Label true_continue(this), return_false(this); BranchIfToBooleanIsTrue(value, &true_continue, &return_false); Bind(&return_false); Return(FalseConstant()); Bind(&true_continue); } private: Node* VisitAllFastElementsOneKind(Node* context, ElementsKind kind, Node* this_arg, Node* o, Node* len, Node* callbackfn, const CallResultProcessor& processor, Node* a, Label* array_changed, ParameterMode mode) { Comment("begin VisitAllFastElementsOneKind"); Variable original_map(this, MachineRepresentation::kTagged); original_map.Bind(LoadMap(o)); VariableList list({&original_map}, zone()); Node* last_index = nullptr; BuildFastLoop( list, IntPtrOrSmiConstant(0, mode), TaggedToParameter(len, mode), [=, &original_map, &last_index](Node* index) { last_index = index; Label one_element_done(this), hole_element(this); // Check if o's map has changed during the callback. If so, we have to // fall back to the slower spec implementation for the rest of the // iteration. Node* o_map = LoadMap(o); GotoIf(WordNotEqual(o_map, original_map.value()), array_changed); // Check if o's length has changed during the callback and if the // index is now out of range of the new length. Node* tagged_index = ParameterToTagged(index, mode); GotoIf(SmiGreaterThanOrEqual(tagged_index, LoadJSArrayLength(o)), array_changed); // Re-load the elements array. If may have been resized. Node* elements = LoadElements(o); // Fast case: load the element directly from the elements FixedArray // and call the callback if the element is not the hole. DCHECK(kind == FAST_ELEMENTS || kind == FAST_DOUBLE_ELEMENTS); int base_size = kind == FAST_ELEMENTS ? FixedArray::kHeaderSize : (FixedArray::kHeaderSize - kHeapObjectTag); Node* offset = ElementOffsetFromIndex(index, kind, mode, base_size); Node* value = nullptr; if (kind == FAST_ELEMENTS) { value = LoadObjectField(elements, offset); GotoIf(WordEqual(value, TheHoleConstant()), &hole_element); } else { Node* double_value = LoadDoubleWithHoleCheck(elements, offset, &hole_element); value = AllocateHeapNumberWithValue(double_value); } Node* result = CallJS(CodeFactory::Call(isolate()), context, callbackfn, this_arg, value, tagged_index, o); processor(a, tagged_index, result); Goto(&one_element_done); Bind(&hole_element); // Check if o's prototype change unexpectedly has elements after the // callback in the case of a hole. BranchIfPrototypesHaveNoElements(o_map, &one_element_done, array_changed); Bind(&one_element_done); }, 1, mode, IndexAdvanceMode::kPost); Comment("end VisitAllFastElementsOneKind"); return last_index; } void HandleFastElements(Node* context, Node* this_arg, Node* o, Node* len, Node* callbackfn, CallResultProcessor processor, Node* a, Variable& k, Label* slow) { Label switch_on_elements_kind(this), fast_elements(this), maybe_double_elements(this), fast_double_elements(this); Comment("begin HandleFastElements"); // Non-smi lengths must use the slow path. GotoIf(TaggedIsNotSmi(len), slow); BranchIfFastJSArray(o, context, CodeStubAssembler::FastJSArrayAccessMode::INBOUNDS_READ, &switch_on_elements_kind, slow); Bind(&switch_on_elements_kind); // Select by ElementsKind Node* o_map = LoadMap(o); Node* bit_field2 = LoadMapBitField2(o_map); Node* kind = DecodeWord32<Map::ElementsKindBits>(bit_field2); Branch(Int32GreaterThan(kind, Int32Constant(FAST_HOLEY_ELEMENTS)), &maybe_double_elements, &fast_elements); ParameterMode mode = OptimalParameterMode(); Bind(&fast_elements); { Label array_changed(this, Label::kDeferred); Node* last_index = VisitAllFastElementsOneKind( context, FAST_ELEMENTS, this_arg, o, len, callbackfn, processor, a, &array_changed, mode); // No exception, return success Return(a); Bind(&array_changed); k.Bind(ParameterToTagged(last_index, mode)); Goto(slow); } Bind(&maybe_double_elements); Branch(Int32GreaterThan(kind, Int32Constant(FAST_HOLEY_DOUBLE_ELEMENTS)), slow, &fast_double_elements); Bind(&fast_double_elements); { Label array_changed(this, Label::kDeferred); Node* last_index = VisitAllFastElementsOneKind( context, FAST_DOUBLE_ELEMENTS, this_arg, o, len, callbackfn, processor, a, &array_changed, mode); // No exception, return success Return(a); Bind(&array_changed); k.Bind(ParameterToTagged(last_index, mode)); Goto(slow); } } }; TF_BUILTIN(FastArrayPush, CodeStubAssembler) { Variable arg_index(this, MachineType::PointerRepresentation()); Label default_label(this, &arg_index); Label smi_transition(this); Label object_push_pre(this); Label object_push(this, &arg_index); Label double_push(this, &arg_index); Label double_transition(this); Label runtime(this, Label::kDeferred); Node* argc = Parameter(BuiltinDescriptor::kArgumentsCount); Node* context = Parameter(BuiltinDescriptor::kContext); Node* new_target = Parameter(BuiltinDescriptor::kNewTarget); CodeStubArguments args(this, ChangeInt32ToIntPtr(argc)); Node* receiver = args.GetReceiver(); Node* kind = nullptr; Label fast(this); BranchIfFastJSArray(receiver, context, FastJSArrayAccessMode::ANY_ACCESS, &fast, &runtime); Bind(&fast); { // Disallow pushing onto prototypes. It might be the JSArray prototype. // Disallow pushing onto non-extensible objects. Comment("Disallow pushing onto prototypes"); Node* map = LoadMap(receiver); Node* bit_field2 = LoadMapBitField2(map); int mask = static_cast<int>(Map::IsPrototypeMapBits::kMask) | (1 << Map::kIsExtensible); Node* test = Word32And(bit_field2, Int32Constant(mask)); GotoIf(Word32NotEqual(test, Int32Constant(1 << Map::kIsExtensible)), &runtime); // Disallow pushing onto arrays in dictionary named property mode. We need // to figure out whether the length property is still writable. Comment("Disallow pushing onto arrays in dictionary named property mode"); GotoIf(IsDictionaryMap(map), &runtime); // Check whether the length property is writable. The length property is the // only default named property on arrays. It's nonconfigurable, hence is // guaranteed to stay the first property. Node* descriptors = LoadMapDescriptors(map); Node* details = LoadFixedArrayElement(descriptors, DescriptorArray::ToDetailsIndex(0)); GotoIf(IsSetSmi(details, PropertyDetails::kAttributesReadOnlyMask), &runtime); arg_index.Bind(IntPtrConstant(0)); kind = DecodeWord32<Map::ElementsKindBits>(bit_field2); GotoIf(Int32GreaterThan(kind, Int32Constant(FAST_HOLEY_SMI_ELEMENTS)), &object_push_pre); Node* new_length = BuildAppendJSArray(FAST_SMI_ELEMENTS, context, receiver, args, arg_index, &smi_transition); args.PopAndReturn(new_length); } // If the argument is not a smi, then use a heavyweight SetProperty to // transition the array for only the single next element. If the argument is // a smi, the failure is due to some other reason and we should fall back on // the most generic implementation for the rest of the array. Bind(&smi_transition); { Node* arg = args.AtIndex(arg_index.value()); GotoIf(TaggedIsSmi(arg), &default_label); Node* length = LoadJSArrayLength(receiver); // TODO(danno): Use the KeyedStoreGeneric stub here when possible, // calling into the runtime to do the elements transition is overkill. CallRuntime(Runtime::kSetProperty, context, receiver, length, arg, SmiConstant(STRICT)); Increment(arg_index); // The runtime SetProperty call could have converted the array to dictionary // mode, which must be detected to abort the fast-path. Node* map = LoadMap(receiver); Node* bit_field2 = LoadMapBitField2(map); Node* kind = DecodeWord32<Map::ElementsKindBits>(bit_field2); GotoIf(Word32Equal(kind, Int32Constant(DICTIONARY_ELEMENTS)), &default_label); GotoIfNotNumber(arg, &object_push); Goto(&double_push); } Bind(&object_push_pre); { Branch(Int32GreaterThan(kind, Int32Constant(FAST_HOLEY_ELEMENTS)), &double_push, &object_push); } Bind(&object_push); { Node* new_length = BuildAppendJSArray(FAST_ELEMENTS, context, receiver, args, arg_index, &default_label); args.PopAndReturn(new_length); } Bind(&double_push); { Node* new_length = BuildAppendJSArray(FAST_DOUBLE_ELEMENTS, context, receiver, args, arg_index, &double_transition); args.PopAndReturn(new_length); } // If the argument is not a double, then use a heavyweight SetProperty to // transition the array for only the single next element. If the argument is // a double, the failure is due to some other reason and we should fall back // on the most generic implementation for the rest of the array. Bind(&double_transition); { Node* arg = args.AtIndex(arg_index.value()); GotoIfNumber(arg, &default_label); Node* length = LoadJSArrayLength(receiver); // TODO(danno): Use the KeyedStoreGeneric stub here when possible, // calling into the runtime to do the elements transition is overkill. CallRuntime(Runtime::kSetProperty, context, receiver, length, arg, SmiConstant(STRICT)); Increment(arg_index); // The runtime SetProperty call could have converted the array to dictionary // mode, which must be detected to abort the fast-path. Node* map = LoadMap(receiver); Node* bit_field2 = LoadMapBitField2(map); Node* kind = DecodeWord32<Map::ElementsKindBits>(bit_field2); GotoIf(Word32Equal(kind, Int32Constant(DICTIONARY_ELEMENTS)), &default_label); Goto(&object_push); } // Fallback that stores un-processed arguments using the full, heavyweight // SetProperty machinery. Bind(&default_label); { args.ForEach( [this, receiver, context](Node* arg) { Node* length = LoadJSArrayLength(receiver); CallRuntime(Runtime::kSetProperty, context, receiver, length, arg, SmiConstant(STRICT)); }, arg_index.value()); args.PopAndReturn(LoadJSArrayLength(receiver)); } Bind(&runtime); { Node* target = LoadFromFrame(StandardFrameConstants::kFunctionOffset, MachineType::TaggedPointer()); TailCallStub(CodeFactory::ArrayPush(isolate()), context, target, new_target, argc); } } TF_BUILTIN(ArrayForEachLoopContinuation, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinLoopContinuation( [this](Node* a, Node* p_k, Node* value) { ForEachProcessor(a, p_k, value); }); } TF_BUILTIN(ArrayForEach, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinBody( "Array.prototype.forEach", [=](Node*, Node*) { return UndefinedConstant(); }, [this](Node* a, Node* p_k, Node* value) { ForEachProcessor(a, p_k, value); }, CodeFactory::ArrayForEachLoopContinuation(isolate())); } TF_BUILTIN(ArraySomeLoopContinuation, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinLoopContinuation( [this](Node* a, Node* p_k, Node* value) { SomeProcessor(a, p_k, value); }); } TF_BUILTIN(ArraySome, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinBody( "Array.prototype.some", [=](Node*, Node*) { return FalseConstant(); }, [this](Node* a, Node* p_k, Node* value) { SomeProcessor(a, p_k, value); }, CodeFactory::ArraySomeLoopContinuation(isolate())); } TF_BUILTIN(ArrayEveryLoopContinuation, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinLoopContinuation( [this](Node* a, Node* p_k, Node* value) { EveryProcessor(a, p_k, value); }); } TF_BUILTIN(ArrayEvery, ArrayBuiltinCodeStubAssembler) { GenerateIteratingArrayBuiltinBody( "Array.prototype.every", [=](Node*, Node*) { return TrueConstant(); }, [this](Node* a, Node* p_k, Node* value) { EveryProcessor(a, p_k, value); }, CodeFactory::ArrayEveryLoopContinuation(isolate())); } TF_BUILTIN(ArrayIsArray, CodeStubAssembler) { Node* object = Parameter(1); Node* context = Parameter(4); Label call_runtime(this), return_true(this), return_false(this); GotoIf(TaggedIsSmi(object), &return_false); Node* instance_type = LoadInstanceType(object); GotoIf(Word32Equal(instance_type, Int32Constant(JS_ARRAY_TYPE)), &return_true); // TODO(verwaest): Handle proxies in-place. Branch(Word32Equal(instance_type, Int32Constant(JS_PROXY_TYPE)), &call_runtime, &return_false); Bind(&return_true); Return(BooleanConstant(true)); Bind(&return_false); Return(BooleanConstant(false)); Bind(&call_runtime); Return(CallRuntime(Runtime::kArrayIsArray, context, object)); } TF_BUILTIN(ArrayIncludes, CodeStubAssembler) { Node* const array = Parameter(0); Node* const search_element = Parameter(1); Node* const start_from = Parameter(2); Node* const context = Parameter(3 + 2); Variable index_var(this, MachineType::PointerRepresentation()); Label init_k(this), return_true(this), return_false(this), call_runtime(this); Label init_len(this), select_loop(this); index_var.Bind(IntPtrConstant(0)); // Take slow path if not a JSArray, if retrieving elements requires // traversing prototype, or if access checks are required. BranchIfFastJSArray(array, context, FastJSArrayAccessMode::INBOUNDS_READ, &init_len, &call_runtime); Bind(&init_len); // JSArray length is always an Smi for fast arrays. CSA_ASSERT(this, TaggedIsSmi(LoadObjectField(array, JSArray::kLengthOffset))); Node* const len = LoadAndUntagObjectField(array, JSArray::kLengthOffset); GotoIf(IsUndefined(start_from), &select_loop); // Bailout to slow path if startIndex is not an Smi. Branch(TaggedIsSmi(start_from), &init_k, &call_runtime); Bind(&init_k); CSA_ASSERT(this, TaggedIsSmi(start_from)); Node* const untagged_start_from = SmiToWord(start_from); index_var.Bind( Select(IntPtrGreaterThanOrEqual(untagged_start_from, IntPtrConstant(0)), [=]() { return untagged_start_from; }, [=]() { Node* const index = IntPtrAdd(len, untagged_start_from); return SelectConstant(IntPtrLessThan(index, IntPtrConstant(0)), IntPtrConstant(0), index, MachineType::PointerRepresentation()); }, MachineType::PointerRepresentation())); Goto(&select_loop); Bind(&select_loop); static int32_t kElementsKind[] = { FAST_SMI_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS, FAST_ELEMENTS, FAST_HOLEY_ELEMENTS, FAST_DOUBLE_ELEMENTS, FAST_HOLEY_DOUBLE_ELEMENTS, }; Label if_smiorobjects(this), if_packed_doubles(this), if_holey_doubles(this); Label* element_kind_handlers[] = {&if_smiorobjects, &if_smiorobjects, &if_smiorobjects, &if_smiorobjects, &if_packed_doubles, &if_holey_doubles}; Node* map = LoadMap(array); Node* elements_kind = LoadMapElementsKind(map); Node* elements = LoadElements(array); Switch(elements_kind, &return_false, kElementsKind, element_kind_handlers, arraysize(kElementsKind)); Bind(&if_smiorobjects); { Variable search_num(this, MachineRepresentation::kFloat64); Label ident_loop(this, &index_var), heap_num_loop(this, &search_num), string_loop(this, &index_var), undef_loop(this, &index_var), not_smi(this), not_heap_num(this); GotoIfNot(TaggedIsSmi(search_element), &not_smi); search_num.Bind(SmiToFloat64(search_element)); Goto(&heap_num_loop); Bind(&not_smi); GotoIf(WordEqual(search_element, UndefinedConstant()), &undef_loop); Node* map = LoadMap(search_element); GotoIfNot(IsHeapNumberMap(map), &not_heap_num); search_num.Bind(LoadHeapNumberValue(search_element)); Goto(&heap_num_loop); Bind(&not_heap_num); Node* search_type = LoadMapInstanceType(map); GotoIf(IsStringInstanceType(search_type), &string_loop); Goto(&ident_loop); Bind(&ident_loop); { GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(WordEqual(element_k, search_element), &return_true); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&ident_loop); } Bind(&undef_loop); { GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(WordEqual(element_k, UndefinedConstant()), &return_true); GotoIf(WordEqual(element_k, TheHoleConstant()), &return_true); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&undef_loop); } Bind(&heap_num_loop); { Label nan_loop(this, &index_var), not_nan_loop(this, &index_var); BranchIfFloat64IsNaN(search_num.value(), &nan_loop, &not_nan_loop); Bind(&not_nan_loop); { Label continue_loop(this), not_smi(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIfNot(TaggedIsSmi(element_k), &not_smi); Branch(Float64Equal(search_num.value(), SmiToFloat64(element_k)), &return_true, &continue_loop); Bind(&not_smi); GotoIfNot(IsHeapNumber(element_k), &continue_loop); Branch(Float64Equal(search_num.value(), LoadHeapNumberValue(element_k)), &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&not_nan_loop); } Bind(&nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(TaggedIsSmi(element_k), &continue_loop); GotoIfNot(IsHeapNumber(element_k), &continue_loop); BranchIfFloat64IsNaN(LoadHeapNumberValue(element_k), &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&nan_loop); } } Bind(&string_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(TaggedIsSmi(element_k), &continue_loop); GotoIfNot(IsStringInstanceType(LoadInstanceType(element_k)), &continue_loop); // TODO(bmeurer): Consider inlining the StringEqual logic here. Node* result = CallStub(CodeFactory::StringEqual(isolate()), context, search_element, element_k); Branch(WordEqual(BooleanConstant(true), result), &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&string_loop); } } Bind(&if_packed_doubles); { Label nan_loop(this, &index_var), not_nan_loop(this, &index_var), hole_loop(this, &index_var), search_notnan(this); Variable search_num(this, MachineRepresentation::kFloat64); GotoIfNot(TaggedIsSmi(search_element), &search_notnan); search_num.Bind(SmiToFloat64(search_element)); Goto(&not_nan_loop); Bind(&search_notnan); GotoIfNot(IsHeapNumber(search_element), &return_false); search_num.Bind(LoadHeapNumberValue(search_element)); BranchIfFloat64IsNaN(search_num.value(), &nan_loop, &not_nan_loop); // Search for HeapNumber Bind(&not_nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedDoubleArrayElement(elements, index_var.value(), MachineType::Float64()); Branch(Float64Equal(element_k, search_num.value()), &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&not_nan_loop); } // Search for NaN Bind(&nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); Node* element_k = LoadFixedDoubleArrayElement(elements, index_var.value(), MachineType::Float64()); BranchIfFloat64IsNaN(element_k, &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&nan_loop); } } Bind(&if_holey_doubles); { Label nan_loop(this, &index_var), not_nan_loop(this, &index_var), hole_loop(this, &index_var), search_notnan(this); Variable search_num(this, MachineRepresentation::kFloat64); GotoIfNot(TaggedIsSmi(search_element), &search_notnan); search_num.Bind(SmiToFloat64(search_element)); Goto(&not_nan_loop); Bind(&search_notnan); GotoIf(WordEqual(search_element, UndefinedConstant()), &hole_loop); GotoIfNot(IsHeapNumber(search_element), &return_false); search_num.Bind(LoadHeapNumberValue(search_element)); BranchIfFloat64IsNaN(search_num.value(), &nan_loop, &not_nan_loop); // Search for HeapNumber Bind(&not_nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); // Load double value or continue if it contains a double hole. Node* element_k = LoadFixedDoubleArrayElement( elements, index_var.value(), MachineType::Float64(), 0, INTPTR_PARAMETERS, &continue_loop); Branch(Float64Equal(element_k, search_num.value()), &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&not_nan_loop); } // Search for NaN Bind(&nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); // Load double value or continue if it contains a double hole. Node* element_k = LoadFixedDoubleArrayElement( elements, index_var.value(), MachineType::Float64(), 0, INTPTR_PARAMETERS, &continue_loop); BranchIfFloat64IsNaN(element_k, &return_true, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&nan_loop); } // Search for the Hole Bind(&hole_loop); { GotoIfNot(UintPtrLessThan(index_var.value(), len), &return_false); // Check if the element is a double hole, but don't load it. LoadFixedDoubleArrayElement(elements, index_var.value(), MachineType::None(), 0, INTPTR_PARAMETERS, &return_true); index_var.Bind(IntPtrAdd(index_var.value(), IntPtrConstant(1))); Goto(&hole_loop); } } Bind(&return_true); Return(TrueConstant()); Bind(&return_false); Return(FalseConstant()); Bind(&call_runtime); Return(CallRuntime(Runtime::kArrayIncludes_Slow, context, array, search_element, start_from)); } TF_BUILTIN(ArrayIndexOf, CodeStubAssembler) { Node* array = Parameter(0); Node* search_element = Parameter(1); Node* start_from = Parameter(2); Node* context = Parameter(3 + 2); Node* intptr_zero = IntPtrConstant(0); Node* intptr_one = IntPtrConstant(1); Variable len_var(this, MachineType::PointerRepresentation()), index_var(this, MachineType::PointerRepresentation()), start_from_var(this, MachineType::PointerRepresentation()); Label init_k(this), return_found(this), return_not_found(this), call_runtime(this); Label init_len(this); index_var.Bind(intptr_zero); len_var.Bind(intptr_zero); // Take slow path if not a JSArray, if retrieving elements requires // traversing prototype, or if access checks are required. BranchIfFastJSArray(array, context, FastJSArrayAccessMode::INBOUNDS_READ, &init_len, &call_runtime); Bind(&init_len); { // JSArray length is always an Smi for fast arrays. CSA_ASSERT(this, TaggedIsSmi(LoadObjectField(array, JSArray::kLengthOffset))); Node* len = LoadAndUntagObjectField(array, JSArray::kLengthOffset); len_var.Bind(len); Branch(WordEqual(len_var.value(), intptr_zero), &return_not_found, &init_k); } Bind(&init_k); { // For now only deal with undefined and Smis here; we must be really careful // with side-effects from the ToInteger conversion as the side-effects might // render our assumptions about the receiver being a fast JSArray and the // length invalid. Label done(this), init_k_smi(this), init_k_other(this), init_k_zero(this), init_k_n(this); Branch(TaggedIsSmi(start_from), &init_k_smi, &init_k_other); Bind(&init_k_smi); { // The fromIndex is a Smi. start_from_var.Bind(SmiUntag(start_from)); Goto(&init_k_n); } Bind(&init_k_other); { // The fromIndex must be undefined then, otherwise bailout and let the // runtime deal with the full ToInteger conversion. GotoIfNot(IsUndefined(start_from), &call_runtime); start_from_var.Bind(intptr_zero); Goto(&init_k_n); } Bind(&init_k_n); { Label if_positive(this), if_negative(this), done(this); Branch(IntPtrLessThan(start_from_var.value(), intptr_zero), &if_negative, &if_positive); Bind(&if_positive); { index_var.Bind(start_from_var.value()); Goto(&done); } Bind(&if_negative); { index_var.Bind(IntPtrAdd(len_var.value(), start_from_var.value())); Branch(IntPtrLessThan(index_var.value(), intptr_zero), &init_k_zero, &done); } Bind(&init_k_zero); { index_var.Bind(intptr_zero); Goto(&done); } Bind(&done); } } static int32_t kElementsKind[] = { FAST_SMI_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS, FAST_ELEMENTS, FAST_HOLEY_ELEMENTS, FAST_DOUBLE_ELEMENTS, FAST_HOLEY_DOUBLE_ELEMENTS, }; Label if_smiorobjects(this), if_packed_doubles(this), if_holey_doubles(this); Label* element_kind_handlers[] = {&if_smiorobjects, &if_smiorobjects, &if_smiorobjects, &if_smiorobjects, &if_packed_doubles, &if_holey_doubles}; Node* map = LoadMap(array); Node* elements_kind = LoadMapElementsKind(map); Node* elements = LoadElements(array); Switch(elements_kind, &return_not_found, kElementsKind, element_kind_handlers, arraysize(kElementsKind)); Bind(&if_smiorobjects); { Variable search_num(this, MachineRepresentation::kFloat64); Label ident_loop(this, &index_var), heap_num_loop(this, &search_num), string_loop(this, &index_var), not_smi(this), not_heap_num(this); GotoIfNot(TaggedIsSmi(search_element), &not_smi); search_num.Bind(SmiToFloat64(search_element)); Goto(&heap_num_loop); Bind(&not_smi); Node* map = LoadMap(search_element); GotoIfNot(IsHeapNumberMap(map), &not_heap_num); search_num.Bind(LoadHeapNumberValue(search_element)); Goto(&heap_num_loop); Bind(&not_heap_num); Node* search_type = LoadMapInstanceType(map); GotoIf(IsStringInstanceType(search_type), &string_loop); Goto(&ident_loop); Bind(&ident_loop); { GotoIfNot(UintPtrLessThan(index_var.value(), len_var.value()), &return_not_found); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(WordEqual(element_k, search_element), &return_found); index_var.Bind(IntPtrAdd(index_var.value(), intptr_one)); Goto(&ident_loop); } Bind(&heap_num_loop); { Label not_nan_loop(this, &index_var); BranchIfFloat64IsNaN(search_num.value(), &return_not_found, &not_nan_loop); Bind(&not_nan_loop); { Label continue_loop(this), not_smi(this); GotoIfNot(UintPtrLessThan(index_var.value(), len_var.value()), &return_not_found); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIfNot(TaggedIsSmi(element_k), &not_smi); Branch(Float64Equal(search_num.value(), SmiToFloat64(element_k)), &return_found, &continue_loop); Bind(&not_smi); GotoIfNot(IsHeapNumber(element_k), &continue_loop); Branch(Float64Equal(search_num.value(), LoadHeapNumberValue(element_k)), &return_found, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), intptr_one)); Goto(&not_nan_loop); } } Bind(&string_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len_var.value()), &return_not_found); Node* element_k = LoadFixedArrayElement(elements, index_var.value()); GotoIf(TaggedIsSmi(element_k), &continue_loop); GotoIfNot(IsString(element_k), &continue_loop); // TODO(bmeurer): Consider inlining the StringEqual logic here. Callable callable = CodeFactory::StringEqual(isolate()); Node* result = CallStub(callable, context, search_element, element_k); Branch(WordEqual(BooleanConstant(true), result), &return_found, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), intptr_one)); Goto(&string_loop); } } Bind(&if_packed_doubles); { Label not_nan_loop(this, &index_var), search_notnan(this); Variable search_num(this, MachineRepresentation::kFloat64); GotoIfNot(TaggedIsSmi(search_element), &search_notnan); search_num.Bind(SmiToFloat64(search_element)); Goto(&not_nan_loop); Bind(&search_notnan); GotoIfNot(IsHeapNumber(search_element), &return_not_found); search_num.Bind(LoadHeapNumberValue(search_element)); BranchIfFloat64IsNaN(search_num.value(), &return_not_found, &not_nan_loop); // Search for HeapNumber Bind(&not_nan_loop); { GotoIfNot(UintPtrLessThan(index_var.value(), len_var.value()), &return_not_found); Node* element_k = LoadFixedDoubleArrayElement(elements, index_var.value(), MachineType::Float64()); GotoIf(Float64Equal(element_k, search_num.value()), &return_found); index_var.Bind(IntPtrAdd(index_var.value(), intptr_one)); Goto(&not_nan_loop); } } Bind(&if_holey_doubles); { Label not_nan_loop(this, &index_var), search_notnan(this); Variable search_num(this, MachineRepresentation::kFloat64); GotoIfNot(TaggedIsSmi(search_element), &search_notnan); search_num.Bind(SmiToFloat64(search_element)); Goto(&not_nan_loop); Bind(&search_notnan); GotoIfNot(IsHeapNumber(search_element), &return_not_found); search_num.Bind(LoadHeapNumberValue(search_element)); BranchIfFloat64IsNaN(search_num.value(), &return_not_found, &not_nan_loop); // Search for HeapNumber Bind(&not_nan_loop); { Label continue_loop(this); GotoIfNot(UintPtrLessThan(index_var.value(), len_var.value()), &return_not_found); // Load double value or continue if it contains a double hole. Node* element_k = LoadFixedDoubleArrayElement( elements, index_var.value(), MachineType::Float64(), 0, INTPTR_PARAMETERS, &continue_loop); Branch(Float64Equal(element_k, search_num.value()), &return_found, &continue_loop); Bind(&continue_loop); index_var.Bind(IntPtrAdd(index_var.value(), intptr_one)); Goto(&not_nan_loop); } } Bind(&return_found); Return(SmiTag(index_var.value())); Bind(&return_not_found); Return(NumberConstant(-1)); Bind(&call_runtime); Return(CallRuntime(Runtime::kArrayIndexOf, context, array, search_element, start_from)); } class ArrayPrototypeIterationAssembler : public CodeStubAssembler { public: explicit ArrayPrototypeIterationAssembler(compiler::CodeAssemblerState* state) : CodeStubAssembler(state) {} protected: void Generate_ArrayPrototypeIterationMethod(IterationKind iteration_kind) { Node* receiver = Parameter(0); Node* context = Parameter(3); Variable var_array(this, MachineRepresentation::kTagged); Variable var_map(this, MachineRepresentation::kTagged); Variable var_type(this, MachineRepresentation::kWord32); Label if_isnotobject(this, Label::kDeferred); Label create_array_iterator(this); GotoIf(TaggedIsSmi(receiver), &if_isnotobject); var_array.Bind(receiver); var_map.Bind(LoadMap(receiver)); var_type.Bind(LoadMapInstanceType(var_map.value())); Branch(IsJSReceiverInstanceType(var_type.value()), &create_array_iterator, &if_isnotobject); Bind(&if_isnotobject); { Callable callable = CodeFactory::ToObject(isolate()); Node* result = CallStub(callable, context, receiver); var_array.Bind(result); var_map.Bind(LoadMap(result)); var_type.Bind(LoadMapInstanceType(var_map.value())); Goto(&create_array_iterator); } Bind(&create_array_iterator); Return(CreateArrayIterator(var_array.value(), var_map.value(), var_type.value(), context, iteration_kind)); } }; TF_BUILTIN(ArrayPrototypeValues, ArrayPrototypeIterationAssembler) { Generate_ArrayPrototypeIterationMethod(IterationKind::kValues); } TF_BUILTIN(ArrayPrototypeEntries, ArrayPrototypeIterationAssembler) { Generate_ArrayPrototypeIterationMethod(IterationKind::kEntries); } TF_BUILTIN(ArrayPrototypeKeys, ArrayPrototypeIterationAssembler) { Generate_ArrayPrototypeIterationMethod(IterationKind::kKeys); } TF_BUILTIN(ArrayIteratorPrototypeNext, CodeStubAssembler) { Handle<String> operation = factory()->NewStringFromAsciiChecked( "Array Iterator.prototype.next", TENURED); Node* iterator = Parameter(0); Node* context = Parameter(3); Variable var_value(this, MachineRepresentation::kTagged); Variable var_done(this, MachineRepresentation::kTagged); // Required, or else `throw_bad_receiver` fails a DCHECK due to these // variables not being bound along all paths, despite not being used. var_done.Bind(TrueConstant()); var_value.Bind(UndefinedConstant()); Label throw_bad_receiver(this, Label::kDeferred); Label set_done(this); Label allocate_key_result(this); Label allocate_entry_if_needed(this); Label allocate_iterator_result(this); Label generic_values(this); // If O does not have all of the internal slots of an Array Iterator Instance // (22.1.5.3), throw a TypeError exception GotoIf(TaggedIsSmi(iterator), &throw_bad_receiver); Node* instance_type = LoadInstanceType(iterator); GotoIf( Uint32LessThan( Int32Constant(LAST_ARRAY_ITERATOR_TYPE - FIRST_ARRAY_ITERATOR_TYPE), Int32Sub(instance_type, Int32Constant(FIRST_ARRAY_ITERATOR_TYPE))), &throw_bad_receiver); // Let a be O.[[IteratedObject]]. Node* array = LoadObjectField(iterator, JSArrayIterator::kIteratedObjectOffset); // Let index be O.[[ArrayIteratorNextIndex]]. Node* index = LoadObjectField(iterator, JSArrayIterator::kNextIndexOffset); Node* orig_map = LoadObjectField(iterator, JSArrayIterator::kIteratedObjectMapOffset); Node* array_map = LoadMap(array); Label if_isfastarray(this), if_isnotfastarray(this), if_isdetached(this, Label::kDeferred); Branch(WordEqual(orig_map, array_map), &if_isfastarray, &if_isnotfastarray); Bind(&if_isfastarray); { CSA_ASSERT(this, Word32Equal(LoadMapInstanceType(array_map), Int32Constant(JS_ARRAY_TYPE))); Node* length = LoadObjectField(array, JSArray::kLengthOffset); CSA_ASSERT(this, TaggedIsSmi(length)); CSA_ASSERT(this, TaggedIsSmi(index)); GotoIfNot(SmiBelow(index, length), &set_done); Node* one = SmiConstant(Smi::FromInt(1)); StoreObjectFieldNoWriteBarrier(iterator, JSArrayIterator::kNextIndexOffset, SmiAdd(index, one)); var_done.Bind(FalseConstant()); Node* elements = LoadElements(array); static int32_t kInstanceType[] = { JS_FAST_ARRAY_KEY_ITERATOR_TYPE, JS_FAST_SMI_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_SMI_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_DOUBLE_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_DOUBLE_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FAST_SMI_ARRAY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_SMI_ARRAY_VALUE_ITERATOR_TYPE, JS_FAST_ARRAY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_ARRAY_VALUE_ITERATOR_TYPE, JS_FAST_DOUBLE_ARRAY_VALUE_ITERATOR_TYPE, JS_FAST_HOLEY_DOUBLE_ARRAY_VALUE_ITERATOR_TYPE, }; Label packed_object_values(this), holey_object_values(this), packed_double_values(this), holey_double_values(this); Label* kInstanceTypeHandlers[] = { &allocate_key_result, &packed_object_values, &holey_object_values, &packed_object_values, &holey_object_values, &packed_double_values, &holey_double_values, &packed_object_values, &holey_object_values, &packed_object_values, &holey_object_values, &packed_double_values, &holey_double_values}; Switch(instance_type, &throw_bad_receiver, kInstanceType, kInstanceTypeHandlers, arraysize(kInstanceType)); Bind(&packed_object_values); { var_value.Bind(LoadFixedArrayElement(elements, index, 0, SMI_PARAMETERS)); Goto(&allocate_entry_if_needed); } Bind(&packed_double_values); { Node* value = LoadFixedDoubleArrayElement( elements, index, MachineType::Float64(), 0, SMI_PARAMETERS); var_value.Bind(AllocateHeapNumberWithValue(value)); Goto(&allocate_entry_if_needed); } Bind(&holey_object_values); { // Check the array_protector cell, and take the slow path if it's invalid. Node* invalid = SmiConstant(Smi::FromInt(Isolate::kProtectorInvalid)); Node* cell = LoadRoot(Heap::kArrayProtectorRootIndex); Node* cell_value = LoadObjectField(cell, PropertyCell::kValueOffset); GotoIf(WordEqual(cell_value, invalid), &generic_values); var_value.Bind(UndefinedConstant()); Node* value = LoadFixedArrayElement(elements, index, 0, SMI_PARAMETERS); GotoIf(WordEqual(value, TheHoleConstant()), &allocate_entry_if_needed); var_value.Bind(value); Goto(&allocate_entry_if_needed); } Bind(&holey_double_values); { // Check the array_protector cell, and take the slow path if it's invalid. Node* invalid = SmiConstant(Smi::FromInt(Isolate::kProtectorInvalid)); Node* cell = LoadRoot(Heap::kArrayProtectorRootIndex); Node* cell_value = LoadObjectField(cell, PropertyCell::kValueOffset); GotoIf(WordEqual(cell_value, invalid), &generic_values); var_value.Bind(UndefinedConstant()); Node* value = LoadFixedDoubleArrayElement( elements, index, MachineType::Float64(), 0, SMI_PARAMETERS, &allocate_entry_if_needed); var_value.Bind(AllocateHeapNumberWithValue(value)); Goto(&allocate_entry_if_needed); } } Bind(&if_isnotfastarray); { Label if_istypedarray(this), if_isgeneric(this); // If a is undefined, return CreateIterResultObject(undefined, true) GotoIf(WordEqual(array, UndefinedConstant()), &allocate_iterator_result); Node* array_type = LoadInstanceType(array); Branch(Word32Equal(array_type, Int32Constant(JS_TYPED_ARRAY_TYPE)), &if_istypedarray, &if_isgeneric); Bind(&if_isgeneric); { Label if_wasfastarray(this); Node* length = nullptr; { Variable var_length(this, MachineRepresentation::kTagged); Label if_isarray(this), if_isnotarray(this), done(this); Branch(Word32Equal(array_type, Int32Constant(JS_ARRAY_TYPE)), &if_isarray, &if_isnotarray); Bind(&if_isarray); { var_length.Bind(LoadObjectField(array, JSArray::kLengthOffset)); // Invalidate protector cell if needed Branch(WordNotEqual(orig_map, UndefinedConstant()), &if_wasfastarray, &done); Bind(&if_wasfastarray); { Label if_invalid(this, Label::kDeferred); // A fast array iterator transitioned to a slow iterator during // iteration. Invalidate fast_array_iteration_prtoector cell to // prevent potential deopt loops. StoreObjectFieldNoWriteBarrier( iterator, JSArrayIterator::kIteratedObjectMapOffset, UndefinedConstant()); GotoIf(Uint32LessThanOrEqual( instance_type, Int32Constant(JS_GENERIC_ARRAY_KEY_ITERATOR_TYPE)), &done); Node* invalid = SmiConstant(Smi::FromInt(Isolate::kProtectorInvalid)); Node* cell = LoadRoot(Heap::kFastArrayIterationProtectorRootIndex); StoreObjectFieldNoWriteBarrier(cell, Cell::kValueOffset, invalid); Goto(&done); } } Bind(&if_isnotarray); { Node* length = GetProperty(context, array, factory()->length_string()); Callable to_length = CodeFactory::ToLength(isolate()); var_length.Bind(CallStub(to_length, context, length)); Goto(&done); } Bind(&done); length = var_length.value(); } GotoUnlessNumberLessThan(index, length, &set_done); StoreObjectField(iterator, JSArrayIterator::kNextIndexOffset, NumberInc(index)); var_done.Bind(FalseConstant()); Branch( Uint32LessThanOrEqual( instance_type, Int32Constant(JS_GENERIC_ARRAY_KEY_ITERATOR_TYPE)), &allocate_key_result, &generic_values); Bind(&generic_values); { var_value.Bind(GetProperty(context, array, index)); Goto(&allocate_entry_if_needed); } } Bind(&if_istypedarray); { Node* buffer = LoadObjectField(array, JSTypedArray::kBufferOffset); GotoIf(IsDetachedBuffer(buffer), &if_isdetached); Node* length = LoadObjectField(array, JSTypedArray::kLengthOffset); CSA_ASSERT(this, TaggedIsSmi(length)); CSA_ASSERT(this, TaggedIsSmi(index)); GotoIfNot(SmiBelow(index, length), &set_done); Node* one = SmiConstant(1); StoreObjectFieldNoWriteBarrier( iterator, JSArrayIterator::kNextIndexOffset, SmiAdd(index, one)); var_done.Bind(FalseConstant()); Node* elements = LoadElements(array); Node* base_ptr = LoadObjectField(elements, FixedTypedArrayBase::kBasePointerOffset); Node* external_ptr = LoadObjectField(elements, FixedTypedArrayBase::kExternalPointerOffset, MachineType::Pointer()); Node* data_ptr = IntPtrAdd(BitcastTaggedToWord(base_ptr), external_ptr); static int32_t kInstanceType[] = { JS_TYPED_ARRAY_KEY_ITERATOR_TYPE, JS_UINT8_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_UINT8_CLAMPED_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_INT8_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_UINT16_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_INT16_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_UINT32_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_INT32_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FLOAT32_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_FLOAT64_ARRAY_KEY_VALUE_ITERATOR_TYPE, JS_UINT8_ARRAY_VALUE_ITERATOR_TYPE, JS_UINT8_CLAMPED_ARRAY_VALUE_ITERATOR_TYPE, JS_INT8_ARRAY_VALUE_ITERATOR_TYPE, JS_UINT16_ARRAY_VALUE_ITERATOR_TYPE, JS_INT16_ARRAY_VALUE_ITERATOR_TYPE, JS_UINT32_ARRAY_VALUE_ITERATOR_TYPE, JS_INT32_ARRAY_VALUE_ITERATOR_TYPE, JS_FLOAT32_ARRAY_VALUE_ITERATOR_TYPE, JS_FLOAT64_ARRAY_VALUE_ITERATOR_TYPE, }; Label uint8_values(this), int8_values(this), uint16_values(this), int16_values(this), uint32_values(this), int32_values(this), float32_values(this), float64_values(this); Label* kInstanceTypeHandlers[] = { &allocate_key_result, &uint8_values, &uint8_values, &int8_values, &uint16_values, &int16_values, &uint32_values, &int32_values, &float32_values, &float64_values, &uint8_values, &uint8_values, &int8_values, &uint16_values, &int16_values, &uint32_values, &int32_values, &float32_values, &float64_values, }; var_done.Bind(FalseConstant()); Switch(instance_type, &throw_bad_receiver, kInstanceType, kInstanceTypeHandlers, arraysize(kInstanceType)); Bind(&uint8_values); { Node* value_uint8 = LoadFixedTypedArrayElement( data_ptr, index, UINT8_ELEMENTS, SMI_PARAMETERS); var_value.Bind(SmiFromWord32(value_uint8)); Goto(&allocate_entry_if_needed); } Bind(&int8_values); { Node* value_int8 = LoadFixedTypedArrayElement( data_ptr, index, INT8_ELEMENTS, SMI_PARAMETERS); var_value.Bind(SmiFromWord32(value_int8)); Goto(&allocate_entry_if_needed); } Bind(&uint16_values); { Node* value_uint16 = LoadFixedTypedArrayElement( data_ptr, index, UINT16_ELEMENTS, SMI_PARAMETERS); var_value.Bind(SmiFromWord32(value_uint16)); Goto(&allocate_entry_if_needed); } Bind(&int16_values); { Node* value_int16 = LoadFixedTypedArrayElement( data_ptr, index, INT16_ELEMENTS, SMI_PARAMETERS); var_value.Bind(SmiFromWord32(value_int16)); Goto(&allocate_entry_if_needed); } Bind(&uint32_values); { Node* value_uint32 = LoadFixedTypedArrayElement( data_ptr, index, UINT32_ELEMENTS, SMI_PARAMETERS); var_value.Bind(ChangeUint32ToTagged(value_uint32)); Goto(&allocate_entry_if_needed); } Bind(&int32_values); { Node* value_int32 = LoadFixedTypedArrayElement( data_ptr, index, INT32_ELEMENTS, SMI_PARAMETERS); var_value.Bind(ChangeInt32ToTagged(value_int32)); Goto(&allocate_entry_if_needed); } Bind(&float32_values); { Node* value_float32 = LoadFixedTypedArrayElement( data_ptr, index, FLOAT32_ELEMENTS, SMI_PARAMETERS); var_value.Bind( AllocateHeapNumberWithValue(ChangeFloat32ToFloat64(value_float32))); Goto(&allocate_entry_if_needed); } Bind(&float64_values); { Node* value_float64 = LoadFixedTypedArrayElement( data_ptr, index, FLOAT64_ELEMENTS, SMI_PARAMETERS); var_value.Bind(AllocateHeapNumberWithValue(value_float64)); Goto(&allocate_entry_if_needed); } } } Bind(&set_done); { StoreObjectFieldNoWriteBarrier( iterator, JSArrayIterator::kIteratedObjectOffset, UndefinedConstant()); Goto(&allocate_iterator_result); } Bind(&allocate_key_result); { var_value.Bind(index); var_done.Bind(FalseConstant()); Goto(&allocate_iterator_result); } Bind(&allocate_entry_if_needed); { GotoIf(Int32GreaterThan(instance_type, Int32Constant(LAST_ARRAY_KEY_VALUE_ITERATOR_TYPE)), &allocate_iterator_result); Node* elements = AllocateFixedArray(FAST_ELEMENTS, IntPtrConstant(2)); StoreFixedArrayElement(elements, 0, index, SKIP_WRITE_BARRIER); StoreFixedArrayElement(elements, 1, var_value.value(), SKIP_WRITE_BARRIER); Node* entry = Allocate(JSArray::kSize); Node* map = LoadContextElement(LoadNativeContext(context), Context::JS_ARRAY_FAST_ELEMENTS_MAP_INDEX); StoreMapNoWriteBarrier(entry, map); StoreObjectFieldRoot(entry, JSArray::kPropertiesOffset, Heap::kEmptyFixedArrayRootIndex); StoreObjectFieldNoWriteBarrier(entry, JSArray::kElementsOffset, elements); StoreObjectFieldNoWriteBarrier(entry, JSArray::kLengthOffset, SmiConstant(Smi::FromInt(2))); var_value.Bind(entry); Goto(&allocate_iterator_result); } Bind(&allocate_iterator_result); { Node* result = Allocate(JSIteratorResult::kSize); Node* map = LoadContextElement(LoadNativeContext(context), Context::ITERATOR_RESULT_MAP_INDEX); StoreMapNoWriteBarrier(result, map); StoreObjectFieldRoot(result, JSIteratorResult::kPropertiesOffset, Heap::kEmptyFixedArrayRootIndex); StoreObjectFieldRoot(result, JSIteratorResult::kElementsOffset, Heap::kEmptyFixedArrayRootIndex); StoreObjectFieldNoWriteBarrier(result, JSIteratorResult::kValueOffset, var_value.value()); StoreObjectFieldNoWriteBarrier(result, JSIteratorResult::kDoneOffset, var_done.value()); Return(result); } Bind(&throw_bad_receiver); { // The {receiver} is not a valid JSArrayIterator. CallRuntime(Runtime::kThrowIncompatibleMethodReceiver, context, HeapConstant(operation), iterator); Unreachable(); } Bind(&if_isdetached); { Node* message = SmiConstant(MessageTemplate::kDetachedOperation); CallRuntime(Runtime::kThrowTypeError, context, message, HeapConstant(operation)); Unreachable(); } } } // namespace internal } // namespace v8
def _opt_select(nodes, c_puct=C_PUCT): total_count = 0 for i in range(nodes.shape[0]): total_count += nodes[i][1] action_scores = np.zeros(nodes.shape[0]) for i in range(nodes.shape[0]): action_scores[i] = nodes[i][0] + c_puct * nodes[i][2] * \ (np.sqrt(total_count) / (1 + nodes[i][1])) equals = np.where(action_scores == np.max(action_scores))[0] if equals.shape[0] > 0: return np.random.choice(equals) return equals[0]
/** * SerDeValue class: * This is used so that the value to serialize is specified * as a property, so that the type information gets included in * the serialized String. */ private static class SerDeValue { // Name of the field used in the intermediate JSON representation private static final String VALUE_FIELD = "__value__"; @JsonProperty(VALUE_FIELD) private final Object value; @JsonCreator private SerDeValue(@JsonProperty(VALUE_FIELD) Object value) { this.value = value; } private Object getValue() { return value; } }
<filename>src/core/abstracts/exchange-with-credit.abstract.ts import { UpdateResult } from "typeorm"; export abstract class IExchangeWithCreditRepository<T>{ abstract createExchangeWithCredit(exchange: T): Promise<T> abstract getIdByExchange(exchange: T): Promise<Number> abstract updateExchangeBooks(id: number, exchange: T): Promise<UpdateResult> abstract exchangeNotificationBuyer(token: string): Promise<T[]> abstract exchangeNotificationOwner(token: string): Promise<T[]> abstract findCreditExchangeById(id: number): Promise<T> }
THE DANGERS OF MYSTICISM By Aleister Crowley Publication in Class C With comments by Frater Apollonius 4°=7 A∴A∴ Affectionately inscribed to Arthur Edward Waite Do what thou wilt shall be the whole of the Law. In its splintering, the original Order of the Golden Dawn had produced several groups that turned the group more deeply into a mystical Christianity. All the bickering the brought on the splintering was brought to a height when Crowley was given an inner order initiation by Mathers and a host of self-righteous members rebuked Mathers for accepting a bi- sexual man amongst their rank. The work of the lodge itself had devolved into mere pageantry with a group politic that had members buying Grades for prestige. A.E. Waite was one of the leaders in this revolt; seen by Crowley as the most pompous of the lot, with the possible exception of W.B. Yeats. A CURIOUS IDEA is being sedulously disseminated, and appears to be gaining ground, that mysticism is the “Safe” Path to the Highest, and magic the dangerous Path to the Lowest. There is an important point being made here; Many who take the path of Magick, end up completely insane as many others who take the path start out that way. The dangers of this path are potent and really should’ve have been brought out here. But more importantly, there really is no safe path. One of the reasons why the Western Mystery Tradition has been so secretive is that its teachings and techniques are not fullproof. The danger of failing can be worse than not having tried to begin with. So the ‘safe’ path is exoteric religion; but of course, there, you’ll also find certain failure in attainment. So is this really safe? That is, assuming there is some vital need for attainment. And if there isn’t, what value beyond vanity can attainment have? There are several comments to be made on this assertion. One may doubt whether anything worth doing at all is free from danger, and one may wonder what danger can threaten the man whose object is his own utter ruin. One may also smile a little grimly at the integrity of those who try to include all Magic under Black Magic, as is the present trick of the Mystic Militant here on earth. Do not underestimate the militancy of the Mystic. This one relies on a sometimes overt and sometimes covert philosophy of intolerant morality. Either you are in agreement with these ideals and their overall ideology or you are evil and/or seduced by evil; the charge may also address your intellectual competence. In comparison, the Magickian’s philosophy seems a-moral at best, though a virtuous moral code of ethical behavior is pursued beyond the Mystic’s ability to recognize. Any attempt to overcome the Mystic’s cognitive dissonance will usually prove futile. Now, as one who may claim to a slight acquaintance with the literature of both paths, and to have been honoured by personal exposition from the adepts of both paths, I believe that I may be able to bring them fairly into the balance. This is the magical theory, that the first departure from the Infinite must be equilibrated and so corrected. So the “great magician,” Mayan, the maker of Illusion, the Creator, must be met in combat. Then “if Satan be divided against Satan, how shall his kingdom stand?” Both vanish: the illusion is no more. Mathematically, 1 + (–1) = 0. And this path is symbolised in the Taro under the figure of the Magus, the card numbered 1, the first departure from 0, but referred to Beth, 2, Mercury, the god of Wisdom, Magic and Truth. The Mystic interprets this “combat” motif in a denotative manner; readily pre-disposed to the exoteric approach to religion. For him or her, the Demiurge must be defeated and manifestation should be returned to the Infinite. But really, do we need to go back to unmanifested existence?! The error was in non-manifested existence to become existent?! The unmanifest (IT) becoming existent is an illusion?! Yes, this is the ego-loser philosophy; their literal and fundamentalist interpretation perfectly expressed. The 1-1=0 formula is the formula of the ego-loser, who seeks to view oneself as infinitessimal (“I am a bug” –The Dalai Lama) and in his or her condescension, pretends that there is no hierarchy of life forms. For the Mystic, dissolution is desireable and sought after; not so for the Magickian. For the Magickian, the “shock of worlds” and all the myriad possibilities of manifestation are sacraments and manifestation is seen as the fullest expression of the divine. It is not to be eschewed, but embraced and adored. It may be true, as Crowley clearly wrote, that some may prefer this Mystic dissolution. Indeed, for some, there is no interest in Magick and evolution. So as per the Gnostic Mass, one may Will one’s dissolution into the infinite. But the equilibration inherently implies a duality that then must be established in order for there to be a balance and a manifestation that can maintain itself outside the infinite in a finite and individualized form. The correction should not be seen as a response to error, but as an adjustment to the first emerging imbalance; the momentum pushing forwards in an involutionary direction. This is presented in the myths of falling angels and guardian angels; Nephilim and the Daughters of Men. The subtlety of the myths has been compromised by the Manichaean predisposition of the Monotheists, which really in presenting an omnipotent evil, is not really Monotheistic at all. Let’s consider the following excerpt from Liber Aleph: Tahuti, or Thoth, confirmed the Word of Dionysus by continuing it; for He shewed how by the Mind it was possible to direct the Operations of the Will. By Criticism and by recorded Memory Man avoideth Error, and the Repetition of Error. But the true Word of Tahuti was A M O U N, whereby He made Men to understand their secret Nature, that is, their unity with their True Selves, or, as they then phrased it, with God. And he discovered unto them the Way of this Attainment, and its relation with the Formula of INRI. Also by his Mystery of Number he made plain the Path for His Successor to declare the Nature of the whole Universe in its Form and in its Structure, as it were an Analysis thereof, doing for Matter what the Buddha was decreed to do for Mind. “Spirit and matter” readily implies their equivalence, which means to me that the idea of ‘illusion’ is not to be taken literally or denotatively. Rather its connotation refers more to the idea of ignorance; consistent with the philosophy of the Supramental Yoga of the Mother and Sri Aurobindo. The maya is not the actual nature of the Universe, but our limited apprehension of this Universe. Per the Supramentalists, when ‘the life of the cells’ are brought to full consciousness, one can then fully apprehend materiality and they further claim, accidents and injury become impossibilities; implying a certain command over one’s physical structure. This is also a part of the congelation of the soul; evolution involves the continual reorganization of complexity in an integral structure. This means the Soul is an aggregate of individual beings (mitochondria on the physical level) that all connect with the Aethyr; the Logos. Tahuti is then said to have done “for matter what the Buddha has been decreed to do for the mind.” Indeed, Tahuti is the god of truth and illusion; connected with the Trickster archetype, which should tell us to not make such a delimited and simplified doctrine (the ego-loser doctrine) of the maya (as certain sects of Hinduism have done). We cannot take this literally at all, but must recognize the very subtle nature of this idea. And I don’t know that the idea in its subtle nature is even comprehensible for anyone who has not championed the Abyss. So for us to make this over- simplified doctrine that all is illusion and the only truth is in annihilation; absorption in the infinite, and that all manifestation is but a deceit is a gross error that with the upholding of such a doctrine, one cannot see the worlds of possibilities and the ‘Great Work’ of human evolution. Indeed, work is labor and the effect of desire, which the Buddha and the ego-loser schools should be eschewed. And this Magus has the twofold aspect of the Magician himself and also of the “Great Magician” described in Liber 418 (Equinox, No. V., Special Supplement, p. 144).1 The ‘Great Magician” is a metaphor for each of us, creating our own delusionary worlds wherein we do not see the divinity in ourselves. This demiurge is for each of us, ourselves. We are not trapped in our bodies and at any time, we can click our heels three times and say “there’s no place like home”…another metaphor. I don’t want this to be confused with the idea of returning to godhead and escaping this world. We simply need to bring this aggregate mind, first to unity; a complete perfecting of its integral structure brought on by the rousing to consciousness of every cell in the body, and then to the greater vision of Not-I or (-1) in the formula of the Mage. Here is the passage from Liber 418: And this is the mystery that I declare unto thee: that from the Crown itself spring the three great delusions; Aleph is madness, and Beth is falsehood, and Gimel is glamour. (Aleph is incapacity to apprehend — the absence of any steady truth. A = ∆, the volatile; Beth is the assertion of false relations, even in the illusion of the dyad. B = s; And Gimel is the clouding of aspiration by the marsh miasma of desire G = r. Such are the evil and averse counterparts of the three highest faculties of the Soul: Aleph, the inspiration of the soul in ecstasy; Beth, the virtue of Truthfulness without care of other issues; and Gimel, the direct link of the human with the divine Consciousness.) And these three be greater than all, for they are beyond the words that I speak unto thee; how much more therefore are they beyond the words that thou transmittest unto men. Behold! the Veil of the Æthyr sundereth, and is torn, like a sail by the breath of the tempest, and thou shalt see him as from afar off. This is that which is written, “Confound her understanding with darkness,” for thou canst not speak this thing (The Seer was being warned all the time that he was seeing only a Guard.). It is the figure of the Magus of the Taro (Atu I. This is Mayan, the Great Magician, he who has created the Dyad B = 2 and thus made possible the conception of Opposition, and hence of “Evil”. He is to be distinguished from Chokma, the creative Mercury who transmits the Essence of Kether as a Logos, that Kether may become intelligible to Himself through Binah. This lower Mercury asserts the Dyad as Reality, and denies alike Kether and the Ain. Hence its issue is in Materialism.); The material and the spiritual are two ends of the same coin. That one should be divided against the other would be utter ruin. But the Manichaean-natured Mystic eschews the material as illusion; a trap that must be overcome that the human being identify only with the spiritual. Indeed, this is the true and rabit materialist. and in his right arm the torch of the flames blazing upwards; in his left the cup of poison, a cataract into Hell. And upon his head the evil talisman, blasphemy and blasphemy and blasphemy, in the form of a circle. That is the greatest blasphemy of all.* On his feet hath he the scythes and swords and sickles; daggers; knives; every sharp thing,—a millionfold, and all in one. And before him is the Table that is a Table of wickedness, the 42- fold Table. This Table is connected with the 42 Assessors of the Dead, for they are the Accursers, whom the soul must baffle; and with the 42-fold name of God, for this is the Mystery of Iniquity, that there was ever a beginning at all. And this Magus casteth forth, by the might of his four weapons, veil after veil; a thousand shining colours, ripping and tearing the Æthyr, so that it is like jagged saws, or like broken teeth in the face of a young girl, or like disruption, or madness. There is a horrible grinding sound, maddening. This is the mill in which the Universal Substance, which is ether, was ground down into matter. * I.e., that the circle should be thus profaned. This evil circle is of three concentric rings. Now the formula of the mystic is much simpler. Mathematically, is is 1 – 1 = 0. He is like a grain of salt cast into the sea; the process of dissolution is obviously easier than the shock of worlds which the magician contemplates. “Sit down, and feel yourself as dust in the presence of God; nay, as less than dust, as nothing,” is the all-sufficient simplicity of his method. Unfortunately, many people cannot do this. And when you urge your inability, the mystic is only too likely to shrug his shoulders and be done with you. Yes, once one violates the applied sanctity of the Mystic’s way and fails to recognize its viability for oneself, the Mystic loses respect and either may angrily turn aside, or become condescending towards. The 1-1=0 formula is the formula of the ego-loser, who seeks to view oneself as infinitessimal (“I am a bug” –The Dalai Lama) and in his or her condescension, pretends that there is no hierarchy of life forms. For the Mystic, dissolution is desirable and sought after; not so for the Magickian. For the Magickian, the “shock of worlds” and all the myriad possibilities of manifestation are sacraments and manifestation is seen as the fullest expression of the divine. It is not to be eschewed, but embraced and adored. The equation that involves subtraction is the equation of the ego-loser seeking to lose him or herself to gain dissolution into the infinite. The equation of the Magickian is an equation of addition or of the law of attraction; the two ends of the magnetic pole coming together to create a strong structure. This is seeing manifested life as the sacrament of the divine. It opens the door to the “sea of possibilities” (to quote my personal goddess and savior <smirk> Patti Smith). “Spare the child and spoil the rod; I have not sold myself to god.” Crowley notes that the method of the Mystic is “all-sufficient” and it is an effective means for a certain attainment. For those who naturally eschew this world and life in general, the Buddha’s instructions are 100% perfect. For those who see this world as a stepping stone to a greater set of worlds and possibilities, the adding equation will do much better. And really, one must make a choice. AL: I.57 Invoke me under my stars! Love is the law, love under will. Nor let the fools mistake love; for there are love and love. There is the dove, and there is the serpent. Choose ye well! He, my prophet, hath chosen, knowing the law of the fortress, and the great mystery of the House of God. All these old letters of my Book are aright; but * is not the Star. This also is secret: my prophet shall reveal it to the wise. Crowley’s comment on this verse from AL is interesting: Nuit commands mankind to invoke Her, that is, to fulfill their utmost Selfhood, under Her stars, that is, by the study of all other Points of View beside one’s own. The method of Magick: Love the mode in which Will operates. The method of Magick in this – and in all – Work is: “love under will.” The word love (Agaph in Greek) has the value of 93, like that of Qelhma, will. This implies that love and will are in truth one and the same, two phases of one theme. Love is thus shown as the means by which will may be brought to success. Men are warned against error in this matter of love. There are two main modes of love, the symbol of one being the dove, of the other the serpent. These symbols and their meanings in ethics, with their bearing on “the law of the fortress, and the great mystery of the House of God” are explained by me fully elsewhere. The problem is the ego-loser mentality is what has infected all the exoteric religions and they have become masochistic and enslaving in nature. They feed today, upon ignorance and superstition; destroying even educated minds. Many people cannot choose the ascetic life of self-denial and abstinence from worldly cares. There are those few who prefer their solitude and want to remain ‘shut-up’ (cf. chapter 89; Liber 333) from the world. They are those who: ‘drop out’ from life and simply tune into themselves and lose the interconnectivity that is the field of love. This gets hyped up into being some sort of high virtue that attempts to leave everyone else feeling that they have not virtue for their wordly cares. But the artist and athlete (amongst others) knows this to be arrogant and misleading. There is great virtue in reaching for the world and grabbing life with both hands. The passions lead to the thrill of victory, the agony of defeat and the great works of art and science. The ascetic cowers from life and hides in ignomy; there is no virtue there. He or she is just waiting to die to ferment the final death of the ego; having died a thousand times before. AL:III.57 Despise also all cowards; professional soldiers who dare not fight, but play; all fools despise! Crowley’s comment on this verse from AL is interesting: We do not want “professional soldiers,” hired bravos sworn to have no souls of their own. They “dare not fight;” for how should a man dare to fight unless his cause be a love mightier than his love of life? Therefore they “play;” they have sold themselves; their Will is no more theirs; life is no longer a serious thing to them; therefore they wander wastrel in clubs and boudoirs and greenrooms; bridge, billiards, polo, pettie coats puff out their emptiness; scratched for the Great Race of Life, they watch the Derby instead. Brave such may be; they may well be (in a sense) classed with the rat; but brainless and idle they must be, who have no goal beyond the grave, where, at the best, chance flings fast-withering flowers of false and garish glory. They serve to defend things vital to their country; they are the skull that keeps the brain from harm? Oh foolish brain! Wet thou not wiser to defend thyself, rather than trust to brittle bone that hinders thee from growth? Let every man bear arms, swift to resent oppression, generous and ardent to draw sword in any cause, if justice or freedom summon him! “All fools despise.” In this last phrase the word “fools” is evidently not to be taken in its deeper mystical sense, the context plainly bearing reference to ordinary life. But the “fool” is still as described in the Tarot Trump. He is an epicene creature, soft and sottish, with an imbecile laugh and a pretty taste in fancy waistcoats. He lacks virility, like the ox which is the meaning of the letter Aleph which describes the Trump, and his value is Zero, its number. He is air, formless and incapable of resistance, carrier of sounds which mean nothing to it, swept up into destructive rages of senseless violence from its idleness, incalculably moved by every pressure or pull. One-fifth is the fuel of fire, the corruption of rust; the rest is inert, the soul of explosives, with a trace of that stifling and suffocating gas which is yet food for vegetable, as it is poison to animal, life. We have here a picture of the average man, of a fool; he has no will of his own, is all things to all men, is void, a repeater of words of whose sense he knows nought, a drifter, both idle and violent, compact partly of fierce passions that burn up both himself and the other, but mostly of inert and characterless nonentity, with a little heaviness, dullness, and stupefaction for his only positive qualities. Such are the ‘fools’ whom we despise. The man of Thelema is vertebrate, organized, purposeful, steady, self-controlled, virile; he uses the air as the food of his blood; so also, were he deprived of fools he could no live. We need our atmosphere, after all; it is only when the fools become violent madmen that we need our cloak of silence to wrap us, and our staff to stay us as we ascend our mountain-ridge; and it is only if we go down into the darkness of mines to dig us treasure of earth that we need fear to choke on their poisonous breath. This path is symbolised by the “Fool” of the Tarot, who is alike the Mystic and the Infinite. But apart from this question, it is by no means certain that the formula is as simple as it seems. How is the mystic to assure himself that “God” is really “God” and not some demon masquerading in His image? How is it that the ego would want to destroy itself or become ‘lost’. The Paratman becomes idolized and anthrompomorphosized, as well as objectified; the Mystic’s god has to become everyone’s god. In his or her Bhakti delusion this god becomes the only god, the very description of failure in the Abyss. We find Gerson sacrificing Huss to his “God”; we find a modern journalist who has done more than dabble in mysticism writing, “This mystic life at its highest is undeniably selfish”; we find another writing like the old lady who ended her criticism of the Universe, “There’s only Jock an’ me’ll be saved; an’ I’m no that sure o’ Jock”; we find another who at the age of ninety-nine foams at the mouth over an alleged breach of her alleged copyright; we find another so sensitive that the mention of his name by the present writer induces an attack of epileptic mania; if such are really “united with” or “absorbed in” God, what of God? Though the mystical method is clearly dangerous and deceiving, we should note that on the other hand, mysticism is still a necessary component of Magick. However, we know from history that Jean Charlier de Gerson and John Huss were theological opponents during the “great schism” of the Roman church, and Huss was executed for heresy by order of the Council of Constance in 1415. Upon reading the history of this schism, we see human nature at work and in this case, showing through one of the chief dangers of mysticism, they mistook their own individual suns for the Sun that lords over the sky. And it seems to me that most mytics do this as its the natural tendency of the art; they mistake Paratman for the “one God” in their monotheistic and Manichaean reflex. There is also a reference to A.E. Waite’s A Book of Mystery and Vision, which was reviewed by Crowley in the Equinox. In this, Crowley quite eloquently reveals the very nature of the superstitious thinking process of the mystic; the inherent cognitive dissonance that allows for contradictory thinking processes…as it’s all rather solipsistic. We are told in Galations that the fruits of the Spirit are peace, love, joy, long-suffering, gentleness, goodness, faith, meekness, temperence; and somewhere else, “By their fruits ye shall know them.” Of these evil-doers then we must either think that they are dishonest, and have never attained at all, or that they have united themselves with a devil. Evil is objectified by the Mystic as it is but the half of the one coin that is their objectified image of God. Anyone that cannot see what to them is so obvious, must be evil. Such are “Brethren of the Left Hand Path,” described so thoroughly in Liber 418 (Equinox, No. V., Special Supplement, pp. 119 sqq.).2 The notated excerpt from Liber 418 is as follows: And now the peacock’s head is again changed into a woman’s head sparkling and coruscating with its own light of gems. But I look upwards, seeing that she is called the footstool of the Holy One, even as Binah is called His throne. And the whole Æthyr is full of the most wonderful bands of light,—a thousand different curves and whorls, even as it was before, when I spake mysteries of the Holy Qabalah, and so could not describe it. The Holy One is the Great Magickian (Paratman). And his feet are below the hells; that is the manifestation on Earth is the Magickian engaged in life and with the world he creates in manifested actuality (not seduced by Maya). Oh, I see vast plains beneath her feet, enormous deserts studded with great rocks; and I see little lonely souls, running helplessly about, minute black creatures like men (Again the Black Brothers.). And they keep up a very curious howling, that I can compare to nothing that I have ever heard; yet it is strangely human. And the voice says: These are they that grasped love and clung thereto, praying ever at the knees of the great goddess. These are they that have shut themselves up in fortresses of Love. Each plume of the peacock is full of eyes, that are at the same time 4 7. And for this is the number 28 reflected down into Netzach; and that 28 is Kaph Cheth (Kach), power. For she is Sakti, the eternal energy of the Concealed One. And it is her eternal energy that hath made this eternal change. And this explaineth the call of the Æthyrs, the curse that was pronounced in the beginning being but the creation of Sakti. And this mystery is reflected in the legend of the Creation, where Adam represents the Concealed One, for Adam is Temurah of MAD, the Enochian word for God, and Eve, whom he created for love, is tempted by the snake, Nechesh, who is Messiah her child. And the snake is the magical power, which hath destroyed the primordial equilibrium. * The fourth of the mystic numbers of Jupiter is 136. The Mystic will take exception from the Black Brothers, not recognizing himself in them. He is too well consoled by the love of his own vision in the mirror. These are the mystics, the Shut Ups of cap. 89 of Liber 333. They have sought love and eschewed its opposite in their Manichean moralization. Their worship of Paratman and the negation of they themselves (ego-losers) have brought them to the lonely towers of the Abyss. They have cut themselves off from humanity, yet serve it despite their Wills; but as slaves to their do-gooder vanities. And in these vanities they find righteousness; self-righteousness, the most arrogant and condescending of vices. The Mystic mistakes the lack of outward manifestation of spirit in the Mage as an indicator of evil in his Manichaean heresy. But this is too simplistic; there are those Adepts that Liber LXV quite appropriately shows, who shroud their light with the darkness, but are not cut off from the world; the world is the darkness they shroud themselves with, and why he may be called a “materialist”…indeed he or she loves and honors the world as his or her teacher. LXV:I.18. So also the light that is absorbed. One absorbs little, and is called white and glistening; one absorbs all and is called black. LXV:I.19. Therefore, O my darling, art thou black. LXV:I.20. O my beautiful, I have likened thee to a jet Nubian slave, a boy of melancholy eyes. LXV:I.21. O the filthy one! the dog! they cry against thee. Because thou art my beloved. Of these the most characteristic sign is their exclusiveness. “We are the men.” “Ours is the only Way.” “All Buddhists are wicked,” the insanity of spiritual pride. In today’s society, most of these exotericists conform their rhetoric to their PC mentality; thinking they have risen above this sectarian bigotry. But really, they have merely sublimated their arrogance in a condescending attitude of self-righteousness. The Magician is not nearly so liable to fall into this fearful mire of pride as the mystic; he is occupied with things outside himself, and can correct his pride. Indeed, he is constantly being corrected by Nature. He, the Great One, cannot run a mile in four minutes! The mystic is solitary and shut up, lacks wholesome combat. The Mystic fails to recognize that love and war are two sides of the same coin. The Mystic has made a false virtue of peace and a false scapegoat of war. How can the Mystic understand war when the Mystic has not even been able to understand the nature of human interaction? We are all schoolboys, and the football field is a perfect prophylactic of swelled head. When the mystic meets an obstacle, he “makes believe” about it. He says it is “only illusion.” This is the ego-loser failing to recognize even one’s own humility. Manifestation will remain an illusion for the Mystic, until he or she holds one’s hand in the fire. (pun intended) He has the morphino-maniac’s feeling of bien-être, the delusions of the general paralytic. This “bien-etre’ is the do-gooder insulating his or her condescension while dishing out pity for those he or she feels is truly inferior; always afraid to meet life head on and find one’s superior. He loses the power of looking any fact in the face; he feeds himself on his own imagination; he persuades himself of his own attainment. If contradicted on the subject, he is cross and spiteful and cattish. If I criticise Mr X, he screams, and tries to injure me behind my back; if I say that Madame Y is not exactly St Teresa, she writes a book to prove that she is. His scientific proofs are wrapped in poetic distraction and his poetry reads like a scientific formula. Such persons “swollen with wind, and the rank mist they draw, Rot inwardly, and foul contagion spread,” as Milton wrote of a less dangerous set of spiritual guides. For their unhappy followers and imitators, no words of pity suffice. The whole universe is for thembut ”theglassoftheirfool’sface”; only, unlike Sir Palamedes,theyadmireit. Moraland spiritual Narcissi, they perish in the waters of illusion. A friend of mine, a solicitor in Naples, has told me strange tales of where such self-adoration ends. And the subtlety of the devil is shown particularly in the method by which neophytes are caught by the Black Brothers. There is an exaggerated awe, a solemnity of diction, a vanity of archaic phrases, a false veil of holiness upon the unclean shrine. Stilted affectation masquerades as dignity; a rag-bag of mediævalism apes profundity; jargon passes for literature; phylacteries increase about the hem of the perfect prig, prude, and Pharisee. Some may proclaim that this essay was written to do nothing more than exacerbate Crowley’s rivalry with Waite. But to reduce this to being simply Crowley’s disguised ranting against Waite is a mistake. Crowley is taking what he’s learned from Waite and others (his connections with many mystics and mages are many) and writing an articulate and generalized conclusion based on what he has learned. Corollary to this attitude is the lack of all human virtue. The greatest magician, when he acts in his human capacity, acts as a man should. In paraticular, he has learnt kind-heartedness and sympathy. Unselfishness is very often his long suit. Just this the mystic lacks. Trying to absorb the lower planes into the higher, he neglects the lower, a mistake no magician could make. The Mystic is quite competent at speaking of virtue, but rarely do his feet go where his mouth would have you believe. He or she may call these virtues, “fruits of the spirit” with a self-righteous demeanor, but his or her separation from the world takes one away from the conflicts where such virtues would actually be brought into practice. No virtue is ever manifested. The Nun Gertrude, when it came to her turn to wash up the dishes, used to explain that she was very sorry, but at that particular moment she was being married, with full choral service, to the Saviour. Hundreds of mystics shut themselves up completely and for ever. Not only is their wealth- producing capacity lost to society, but so is their love and good-will, and worst of all, so is their example and precept. Christ, at the height of his career, found time to wash the feet of his disciples; any Master who does not do this on every plane is a Black Brother. The Hindus honour no man who becomes “Sannyasi” (nearly our “hermit”) until he has faithfuly fulfilled all his duties as a man and a citizen. Celibacy is immoral, and the celibate shirks one of the greatest difficulties of the Path. The point really is that if you can’t live in this world of contending forces and master this plane; understanding its ways, how can you possibly expect to master the higher planes? There is a difference between servitude (slavery) and servantry (love under will). Some say though, that what is right for one may not be so for another; but this lends itself very readily to a solipsistic paradigm. Rather, Crowley is saying that those who shut themselves up from the world,shirkfromthegreatestdifficulty;dealingwithothers,whichrequiresinterconnectivity. EvenonCrowley’s ‘Magickal Retirements’, he would often hold up in a hotel and go downstairs to the cafe for his meals and meet with friends. Beware of all those who shirk the lower difficulties: it’s a good bet that they shirk the higher difficulties too. Of the special dangers of the path there is here no space to write; each student finds at each step temptations reflecting his own special weakness. I have therefore dealt solely with the dangersinseparablefromthepathitself,dangersinherentinitsnature. Notforonemoment would I ask the weakest to turn back or turn aside from that path, but I would ask even the strongest to apply these correctives: first, the sceptical or scientific attitude, both in outlook and method; second, a healthy life, meaning by that what the athlete and the explorer mean; third, hearty human companionship, and devotion to life, work, and duty. Let him remember that an ounce of honest pride is better than a ton of false humility, although an ounce of true humility is worth an ounce of honest pride; the man who works has no time to bother with either. And let him remember Christ’s statement of the Law “to love God with all thy heart, and thy neighbour as thyself.” Know that thy neighbor is as much a God as you are and only then can you love him as yourself. Love is the law, love under will.
// Convert images to thumbnails. public class ThumbnailTransformer implements Drafty.Transformer { protected List<PromisedReply<Void>> components = null; public PromisedReply<Void> completionPromise() { if (components == null) { return new PromisedReply<>((Void) null); } return PromisedReply.allOf(components.toArray(new PromisedReply[]{})); } @Override public Drafty.Node transform(Drafty.Node node) { if (!node.isStyle("IM")) { return node; } Object val; node.putData("width", UiUtils.REPLY_THUMBNAIL_DIM); node.putData("height", UiUtils.REPLY_THUMBNAIL_DIM); // Trying to use in-band image first: we don't need the full image at "ref" to generate a tiny thumbnail. if ((val = node.getData("val")) != null) { // Inline image. try { byte[] bits = Base64.decode((String) val, Base64.DEFAULT); Bitmap bmp = BitmapFactory.decodeByteArray(bits, 0, bits.length); bmp = UiUtils.scaleSquareBitmap(bmp, UiUtils.REPLY_THUMBNAIL_DIM); bits = UiUtils.bitmapToBytes(bmp, "image/jpeg"); node.putData("val", Base64.encodeToString(bits, Base64.NO_WRAP)); node.putData("size", bits.length); node.putData("mime", "image/jpeg"); } catch (Exception ex) { node.clearData("val"); node.clearData("size"); } } else if ((val = node.getData("ref")) instanceof String) { node.clearData("ref"); final PromisedReply<Void> done = new PromisedReply<>(); if (components == null) { components = new LinkedList<>(); } components.add(done); Picasso.get().load(Cache.getTinode().toAbsoluteURL((String) val).toString()).into(new Target() { @Override public void onBitmapLoaded(Bitmap bmp, Picasso.LoadedFrom from) { bmp = UiUtils.scaleSquareBitmap(bmp, UiUtils.REPLY_THUMBNAIL_DIM); byte[] bits = UiUtils.bitmapToBytes(bmp, "image/jpeg"); node.putData("val", Base64.encodeToString(bits, Base64.NO_WRAP)); node.putData("size", bits.length); node.putData("mime", "image/jpeg"); try { done.resolve(null); } catch (Exception ignored) {} } @Override public void onBitmapFailed(Exception e, Drawable errorDrawable) { node.clearData("size"); node.clearData("mime"); try { done.resolve(null); } catch (Exception ignored) {} } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { /* do nothing */ } }); } return node; } }
#pragma once #include "swVec3.h" class swRay { public: swRay() = default; swRay(const swVec3 &o, const swVec3 &d, float t = 0, float nt = 0, float xt = FLT_MAX) : orig(o), dir(d), tm(t), minT(nt), maxT(xt) {} swVec3 origin() const { return orig; } swVec3 direction() const { return dir; } float time() const { return tm; } public: swVec3 orig; swVec3 dir; float tm{0.0f}, minT{0.0f}, maxT{FLT_MAX}; };
/** * Hash, Counting, Bucket * * Runtime: 10 ms, faster than 62.55% of Java online submissions for Top K Frequent Elements. * Memory Usage: 41.7 MB, less than 42.94% of Java online submissions for Top K Frequent Elements. */ public int[] topKFrequent(int[] nums, int k) { /* key: number value: count of number in nums */ HashMap<Integer, Integer> frequentMap = new HashMap<>(); for (int num : nums) { frequentMap.put(num, frequentMap.getOrDefault(num, 0) + 1); } /* index: count of num value: list of num */ List<List<Integer>> buckets = new ArrayList<>(nums.length + 1); for (int i = 0; i <= nums.length; i++) { buckets.add(new ArrayList<>()); } for (Map.Entry<Integer, Integer> entry : frequentMap.entrySet()) { int num = entry.getKey(); int countOfNum = entry.getValue(); buckets.get(countOfNum).add(num); } List<Integer> ret = new ArrayList<>(k); for (int i = buckets.size() - 1; i >= 0 && ret.size() < k; i--) { if (!buckets.get(i).isEmpty()) { ret.addAll(buckets.get(i)); } } return ret.stream().mapToInt(i -> i).toArray(); }
/** * Unit tests for AbstractCommandNode. * */ public final class AbstractSoyCommandNodeTest extends TestCase { public void testGetTagString() { DummyNode dn = new DummyNode(8, "blah blah"); assertEquals("{dummy blah blah}", dn.getTagString()); assertEquals("{dummy blah blah}", dn.toSourceString()); dn = new DummyNode(8, "{blah} blah"); assertEquals("{{dummy {blah} blah}}", dn.getTagString()); assertEquals("{{dummy {blah} blah}}", dn.toSourceString()); dn = new DummyNode(8, "blah {blah}"); assertEquals("{{dummy blah {blah} }}", dn.getTagString()); assertEquals("{{dummy blah {blah} }}", dn.toSourceString()); } private static class DummyNode extends AbstractCommandNode { public DummyNode(int id, String commandText) { super(id, SourceLocation.UNKNOWN, "dummy", commandText); } @Override public Kind getKind() { throw new UnsupportedOperationException(); } @Override public DummyNode copy(CopyState copyState) { throw new UnsupportedOperationException(); } } }
<reponame>dbrodie/rex #[derive(Copy, Clone, Debug)] pub enum Style { Default, Selection, Hint, StatusBar, InputLine, InputLineError, MenuShortcut, MenuEntry, MenuTitle } #[derive(Copy, Clone, Debug)] pub enum KeyPress { Key(char), Shortcut(char), Left, Right, Up, Down, PageUp, PageDown, Home, End, Backspace, Delete, Tab, Insert, Enter, Esc } #[derive(Copy, Clone, Debug)] pub enum Event { KeyPressEvent(KeyPress), Resize(usize, usize), } pub trait Frontend { fn clear(&self); fn present(&self); fn print_style(&self, x: usize, y: usize, style: Style, s: &str); fn print_char_style(&self, x: usize, y: usize, style: Style, c: char); fn print_slice_style(&self, x: usize, y: usize, style: Style, chars: &[char]); fn set_cursor(&mut self, x: isize, y: isize); fn height(&self) -> usize; fn width(&self) -> usize; fn poll_event(&mut self) -> Event; }
/* * Copyright (c) 2000-2006 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * @OSF_FREE_COPYRIGHT@ */ #include <pexpert/pexpert.h> #include <pexpert/protos.h> #include <pexpert/device_tree.h> #include <kern/debug.h> #if CONFIG_EMBEDDED #include <libkern/section_keywords.h> #endif static int DEBUGFlag; #if CONFIG_EMBEDDED SECURITY_READ_ONLY_LATE(static uint32_t) gPEKernelConfigurationBitmask; #else static uint32_t gPEKernelConfigurationBitmask; #endif int32_t gPESerialBaud = -1; int debug_cpu_performance_degradation_factor = 1; void pe_init_debug(void) { boolean_t boot_arg_value; if (!PE_parse_boot_argn("debug", &DEBUGFlag, sizeof(DEBUGFlag))) { DEBUGFlag = 0; } gPEKernelConfigurationBitmask = 0; if (!PE_parse_boot_argn("assertions", &boot_arg_value, sizeof(boot_arg_value))) { #if MACH_ASSERT boot_arg_value = TRUE; #else boot_arg_value = FALSE; #endif } gPEKernelConfigurationBitmask |= (boot_arg_value ? kPEICanHasAssertions : 0); if (!PE_parse_boot_argn("statistics", &boot_arg_value, sizeof(boot_arg_value))) { #if DEVELOPMENT || DEBUG boot_arg_value = TRUE; #else boot_arg_value = FALSE; #endif } gPEKernelConfigurationBitmask |= (boot_arg_value ? kPEICanHasStatistics : 0); #if SECURE_KERNEL boot_arg_value = FALSE; #else if (!PE_i_can_has_debugger(NULL)) { boot_arg_value = FALSE; } else if (!PE_parse_boot_argn("diagnostic_api", &boot_arg_value, sizeof(boot_arg_value))) { boot_arg_value = TRUE; } #endif gPEKernelConfigurationBitmask |= (boot_arg_value ? kPEICanHasDiagnosticAPI : 0); int factor = 1; boolean_t have_bootarg = PE_parse_boot_argn("cpu-factor", &factor, sizeof(factor)); if (have_bootarg) { debug_cpu_performance_degradation_factor = factor; } else { DTEntry root; if (DTLookupEntry(NULL, "/", &root) == kSuccess) { void *prop = NULL; uint32_t size = 0; if (DTGetProperty(root, "target-is-fpga", &prop, &size) == kSuccess) { debug_cpu_performance_degradation_factor = 10; } } } } void PE_enter_debugger(const char *cause) { if (DEBUGFlag & DB_NMI) { Debugger(cause); } } uint32_t PE_i_can_has_kernel_configuration(void) { return gPEKernelConfigurationBitmask; } /* extern references */ extern void vcattach(void); /* Globals */ void (*PE_putc)(char c); void PE_init_printf(boolean_t vm_initialized) { if (!vm_initialized) { PE_putc = cnputc; } else { vcattach(); } } uint32_t PE_get_random_seed(unsigned char *dst_random_seed, uint32_t request_size) { DTEntry entryP; uint32_t size = 0; void *dt_random_seed; if ((DTLookupEntry(NULL, "/chosen", &entryP) == kSuccess) && (DTGetProperty(entryP, "random-seed", (void **)&dt_random_seed, &size) == kSuccess)) { unsigned char *src_random_seed; unsigned int i; unsigned int null_count = 0; src_random_seed = (unsigned char *)dt_random_seed; if (size > request_size) { size = request_size; } /* * Copy from the device tree into the destination buffer, * count the number of null bytes and null out the device tree. */ for (i = 0; i < size; i++, src_random_seed++, dst_random_seed++) { *dst_random_seed = *src_random_seed; null_count += *src_random_seed == (unsigned char)0; *src_random_seed = (unsigned char)0; } if (null_count == size) { /* All nulls is no seed - return 0 */ size = 0; } } return size; } unsigned char appleClut8[256 * 3] = { // 00 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xCC, 0xFF, 0xFF, 0x99, 0xFF, 0xFF, 0x66, 0xFF, 0xFF, 0x33, 0xFF, 0xFF, 0x00, 0xFF, 0xCC, 0xFF, 0xFF, 0xCC, 0xCC, 0xFF, 0xCC, 0x99, 0xFF, 0xCC, 0x66, 0xFF, 0xCC, 0x33, 0xFF, 0xCC, 0x00, 0xFF, 0x99, 0xFF, 0xFF, 0x99, 0xCC, 0xFF, 0x99, 0x99, 0xFF, 0x99, 0x66, // 10 0xFF, 0x99, 0x33, 0xFF, 0x99, 0x00, 0xFF, 0x66, 0xFF, 0xFF, 0x66, 0xCC, 0xFF, 0x66, 0x99, 0xFF, 0x66, 0x66, 0xFF, 0x66, 0x33, 0xFF, 0x66, 0x00, 0xFF, 0x33, 0xFF, 0xFF, 0x33, 0xCC, 0xFF, 0x33, 0x99, 0xFF, 0x33, 0x66, 0xFF, 0x33, 0x33, 0xFF, 0x33, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xCC, // 20 0xFF, 0x00, 0x99, 0xFF, 0x00, 0x66, 0xFF, 0x00, 0x33, 0xFF, 0x00, 0x00, 0xCC, 0xFF, 0xFF, 0xCC, 0xFF, 0xCC, 0xCC, 0xFF, 0x99, 0xCC, 0xFF, 0x66, 0xCC, 0xFF, 0x33, 0xCC, 0xFF, 0x00, 0xCC, 0xCC, 0xFF, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x99, 0xCC, 0xCC, 0x66, 0xCC, 0xCC, 0x33, 0xCC, 0xCC, 0x00, // 30 0xCC, 0x99, 0xFF, 0xCC, 0x99, 0xCC, 0xCC, 0x99, 0x99, 0xCC, 0x99, 0x66, 0xCC, 0x99, 0x33, 0xCC, 0x99, 0x00, 0xCC, 0x66, 0xFF, 0xCC, 0x66, 0xCC, 0xCC, 0x66, 0x99, 0xCC, 0x66, 0x66, 0xCC, 0x66, 0x33, 0xCC, 0x66, 0x00, 0xCC, 0x33, 0xFF, 0xCC, 0x33, 0xCC, 0xCC, 0x33, 0x99, 0xCC, 0x33, 0x66, // 40 0xCC, 0x33, 0x33, 0xCC, 0x33, 0x00, 0xCC, 0x00, 0xFF, 0xCC, 0x00, 0xCC, 0xCC, 0x00, 0x99, 0xCC, 0x00, 0x66, 0xCC, 0x00, 0x33, 0xCC, 0x00, 0x00, 0x99, 0xFF, 0xFF, 0x99, 0xFF, 0xCC, 0x99, 0xFF, 0x99, 0x99, 0xFF, 0x66, 0x99, 0xFF, 0x33, 0x99, 0xFF, 0x00, 0x99, 0xCC, 0xFF, 0x99, 0xCC, 0xCC, // 50 0x99, 0xCC, 0x99, 0x99, 0xCC, 0x66, 0x99, 0xCC, 0x33, 0x99, 0xCC, 0x00, 0x99, 0x99, 0xFF, 0x99, 0x99, 0xCC, 0x99, 0x99, 0x99, 0x99, 0x99, 0x66, 0x99, 0x99, 0x33, 0x99, 0x99, 0x00, 0x99, 0x66, 0xFF, 0x99, 0x66, 0xCC, 0x99, 0x66, 0x99, 0x99, 0x66, 0x66, 0x99, 0x66, 0x33, 0x99, 0x66, 0x00, // 60 0x99, 0x33, 0xFF, 0x99, 0x33, 0xCC, 0x99, 0x33, 0x99, 0x99, 0x33, 0x66, 0x99, 0x33, 0x33, 0x99, 0x33, 0x00, 0x99, 0x00, 0xFF, 0x99, 0x00, 0xCC, 0x99, 0x00, 0x99, 0x99, 0x00, 0x66, 0x99, 0x00, 0x33, 0x99, 0x00, 0x00, 0x66, 0xFF, 0xFF, 0x66, 0xFF, 0xCC, 0x66, 0xFF, 0x99, 0x66, 0xFF, 0x66, // 70 0x66, 0xFF, 0x33, 0x66, 0xFF, 0x00, 0x66, 0xCC, 0xFF, 0x66, 0xCC, 0xCC, 0x66, 0xCC, 0x99, 0x66, 0xCC, 0x66, 0x66, 0xCC, 0x33, 0x66, 0xCC, 0x00, 0x66, 0x99, 0xFF, 0x66, 0x99, 0xCC, 0x66, 0x99, 0x99, 0x66, 0x99, 0x66, 0x66, 0x99, 0x33, 0x66, 0x99, 0x00, 0x66, 0x66, 0xFF, 0x66, 0x66, 0xCC, // 80 0x66, 0x66, 0x99, 0x66, 0x66, 0x66, 0x66, 0x66, 0x33, 0x66, 0x66, 0x00, 0x66, 0x33, 0xFF, 0x66, 0x33, 0xCC, 0x66, 0x33, 0x99, 0x66, 0x33, 0x66, 0x66, 0x33, 0x33, 0x66, 0x33, 0x00, 0x66, 0x00, 0xFF, 0x66, 0x00, 0xCC, 0x66, 0x00, 0x99, 0x66, 0x00, 0x66, 0x66, 0x00, 0x33, 0x66, 0x00, 0x00, // 90 0x33, 0xFF, 0xFF, 0x33, 0xFF, 0xCC, 0x33, 0xFF, 0x99, 0x33, 0xFF, 0x66, 0x33, 0xFF, 0x33, 0x33, 0xFF, 0x00, 0x33, 0xCC, 0xFF, 0x33, 0xCC, 0xCC, 0x33, 0xCC, 0x99, 0x33, 0xCC, 0x66, 0x33, 0xCC, 0x33, 0x33, 0xCC, 0x00, 0x33, 0x99, 0xFF, 0x33, 0x99, 0xCC, 0x33, 0x99, 0x99, 0x33, 0x99, 0x66, // a0 0x33, 0x99, 0x33, 0x33, 0x99, 0x00, 0x33, 0x66, 0xFF, 0x33, 0x66, 0xCC, 0x33, 0x66, 0x99, 0x33, 0x66, 0x66, 0x33, 0x66, 0x33, 0x33, 0x66, 0x00, 0x33, 0x33, 0xFF, 0x33, 0x33, 0xCC, 0x33, 0x33, 0x99, 0x33, 0x33, 0x66, 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x33, 0x00, 0xFF, 0x33, 0x00, 0xCC, // b0 0x33, 0x00, 0x99, 0x33, 0x00, 0x66, 0x33, 0x00, 0x33, 0x33, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xCC, 0x00, 0xFF, 0x99, 0x00, 0xFF, 0x66, 0x00, 0xFF, 0x33, 0x00, 0xFF, 0x00, 0x00, 0xCC, 0xFF, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0x99, 0x00, 0xCC, 0x66, 0x00, 0xCC, 0x33, 0x00, 0xCC, 0x00, // c0 0x00, 0x99, 0xFF, 0x00, 0x99, 0xCC, 0x00, 0x99, 0x99, 0x00, 0x99, 0x66, 0x00, 0x99, 0x33, 0x00, 0x99, 0x00, 0x00, 0x66, 0xFF, 0x00, 0x66, 0xCC, 0x00, 0x66, 0x99, 0x00, 0x66, 0x66, 0x00, 0x66, 0x33, 0x00, 0x66, 0x00, 0x00, 0x33, 0xFF, 0x00, 0x33, 0xCC, 0x00, 0x33, 0x99, 0x00, 0x33, 0x66, // d0 0x00, 0x33, 0x33, 0x00, 0x33, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xCC, 0x00, 0x00, 0x99, 0x00, 0x00, 0x66, 0x00, 0x00, 0x33, 0xEE, 0x00, 0x00, 0xDD, 0x00, 0x00, 0xBB, 0x00, 0x00, 0xAA, 0x00, 0x00, 0x88, 0x00, 0x00, 0x77, 0x00, 0x00, 0x55, 0x00, 0x00, 0x44, 0x00, 0x00, 0x22, 0x00, 0x00, // e0 0x11, 0x00, 0x00, 0x00, 0xEE, 0x00, 0x00, 0xDD, 0x00, 0x00, 0xBB, 0x00, 0x00, 0xAA, 0x00, 0x00, 0x88, 0x00, 0x00, 0x77, 0x00, 0x00, 0x55, 0x00, 0x00, 0x44, 0x00, 0x00, 0x22, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0xEE, 0x00, 0x00, 0xDD, 0x00, 0x00, 0xBB, 0x00, 0x00, 0xAA, 0x00, 0x00, 0x88, // f0 0x00, 0x00, 0x77, 0x00, 0x00, 0x55, 0x00, 0x00, 0x44, 0x00, 0x00, 0x22, 0x00, 0x00, 0x11, 0xEE, 0xEE, 0xEE, 0xDD, 0xDD, 0xDD, 0xBB, 0xBB, 0xBB, 0xAA, 0xAA, 0xAA, 0x88, 0x88, 0x88, 0x77, 0x77, 0x77, 0x55, 0x55, 0x55, 0x44, 0x44, 0x44, 0x22, 0x22, 0x22, 0x11, 0x11, 0x11, 0x00, 0x00, 0x00 };
/** * Message from client > server requesting events about job progress. */ @JsonTypeName("job-progress-listen") public static class ListenProgress extends Payload { private final JobId id; @JsonCreator public ListenProgress(@JsonProperty("id") JobId id) { super(); this.id = id; } public JobId getId() { return id; } }
<reponame>LotuxPunk/K9<gh_stars>0 package com.vandendaelen.k9.objects.blocks; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import java.util.Random; public class BlockOres extends BlockBase { private Item toDrop; private int minDropAmount = 1; private int maxDropAmount = 0; public BlockOres(String name, Material material) { this(name, material, null, 1, 1); } public BlockOres(String name, Material material, Item toDrop) { this(name, material, toDrop, 1, 1); } public BlockOres(String name, Material material, Item toDrop, int dropAmount) { this(name, material, toDrop, dropAmount, dropAmount); } public BlockOres(String name, Material material, Item toDrop, int minDropAmount, int maxDropAmount) { super(name,material); this.toDrop = toDrop; this.minDropAmount = minDropAmount; this.maxDropAmount = maxDropAmount; } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return toDrop == null ? Item.getItemFromBlock(this):toDrop; } @Override public int quantityDropped(Random random) { if(this.minDropAmount > this.maxDropAmount) { int i = this.minDropAmount; this.minDropAmount = this.maxDropAmount; this.maxDropAmount = i; } return this.minDropAmount + random.nextInt(this.maxDropAmount - this.minDropAmount + 1); } @Override public int quantityDroppedWithBonus(int fortune, Random random) { if (fortune > 0 && Item.getItemFromBlock(this) != this.getItemDropped(this.getDefaultState(), random, fortune)) { int i = random.nextInt(fortune + 2) - 1; if (i < 0) { i = 0; } return this.quantityDropped(random) * (i + 1); } else { return this.quantityDropped(random); } } }
def causal_estimation(cpi, rate): data = cpi.join(rate.rename(columns={'Uruguay': 'usd_uyu'})) data = data.rename( columns={'Uruguay': 'cpi_uy', 'United States': 'cpi_usa'}) data['raw_q'] = data.cpi_uy / data.cpi_usa data['instant_mean_coef'] = data.usd_uyu / data.raw_q data['mean_coef'] = data.instant_mean_coef.expanding().mean() data['causal_estimation'] = data.raw_q * data.mean_coef data['relative_error'] = ( data.usd_uyu - data.causal_estimation) / data.causal_estimation data['relative_error_std'] = data.relative_error.expanding().std() data['relative_error_mean'] = data.relative_error.expanding().mean() data[ 'relative_error_low'] = data.relative_error_mean - 2 * data.relative_error_std data[ 'relative_error_high'] = data.relative_error_mean + 2 * data.relative_error_std data['causal_est_low'] = data.causal_estimation * ( 1 + data.relative_error_low) data['causal_est_high'] = data.causal_estimation * ( 1 + data.relative_error_high) return data
// CopyFromModel copies model data to entity func (p *Backup) CopyFromModel(m *model.Backup) { p.ID = m.ID p.ProjectID = m.ProjectID p.FileName = m.FileName p.StorageFilePath = m.StorageFilePath p.Time = m.Time p.Type = m.Type p.Length = m.Length }
import express from 'express'; import { body } from 'express-validator'; import { signupUserHandler } from '../../controller/account/signup.controller'; import validation from '../../middleware/validationResult'; const router = express.Router(); router.post( '/api/v1/users/signup', [ body('username').isLength({ min: 1, max: 20 }).escape(), body('email').isLength({ max: 30 }).isEmail().escape(), body('password').isLength({ min: 2, max: 20 }).escape(), ], validation, signupUserHandler ); export { router as signupRouter };
n, k = map(int, input().split()) s = list(input()) group_num = 1 tmp_char = s[0] for index in range(1, len(s)): if s[index] == tmp_char: continue else: tmp_char = s[index] group_num += 1 group_num = max(1, group_num - (k-1)*2) if group_num >= 3: group_num -= 2 elif group_num == 2: group_num = 1 happy = len(s) - group_num print(happy)
<reponame>andipaetzold/zwiftmap import { Chip } from "@react-md/chip"; import { MenuItemInputToggle } from "@react-md/form"; import { List, SimpleListItem } from "@react-md/list"; import { FilterListSVGIcon } from "@react-md/material-icons"; import { Menu } from "@react-md/menu"; import { BELOW_INNER_LEFT_ANCHOR, useToggle } from "@react-md/utils"; import { useSessionSettings } from "../../../../hooks/useSessionSettings"; import { ZwiftEventType } from "../../../../services/events"; import { EVENT_TYPES } from "../../../../services/events/constants"; export function EventFilterButton() { const [sessionSettings, setSessionSettings] = useSessionSettings(); const { eventFilter: state } = sessionSettings; const [menuVisible, , hideMenu, toggleMenu] = useToggle(false); const handleCheckedState = ( checked: boolean, eventType: ZwiftEventType, e: React.MouseEvent<HTMLLIElement> ) => { e.stopPropagation(); if (checked) { setSessionSettings({ ...sessionSettings, eventFilter: { eventTypes: [...state.eventTypes, eventType] }, }); } else { setSessionSettings({ ...sessionSettings, eventFilter: { eventTypes: state.eventTypes.filter((type) => type !== eventType), }, }); } }; return ( <> <SimpleListItem> <Chip id="filter-chip" onClick={(e) => { e.stopPropagation(); toggleMenu(); }} rightIcon={<FilterListSVGIcon />} > Filter </Chip> <Menu id="filter-menu" controlId="filter-chip" aria-labelledby="filter-chip" visible={menuVisible} onRequestClose={hideMenu} anchor={BELOW_INNER_LEFT_ANCHOR} portal > <List> {Object.entries(EVENT_TYPES).map(([eventType, name]) => ( <MenuItemInputToggle key={eventType} id={`filter-${eventType}`} disabled={ state.eventTypes.length === 1 && state.eventTypes.includes(eventType as ZwiftEventType) } checked={state.eventTypes.includes(eventType as ZwiftEventType)} onCheckedChange={(checked, e) => { handleCheckedState(checked, eventType as ZwiftEventType, e); }} type="switch" > {name} </MenuItemInputToggle> ))} </List> </Menu> </SimpleListItem> </> ); }
<reponame>hunshikan/corant /* * Copyright (c) 2013-2018, Bingo.Chen (<EMAIL>). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.corant.shared.conversion; import static org.corant.shared.util.Objects.defaultObject; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.function.Function; import org.corant.shared.normal.Names; import org.corant.shared.util.Systems; /** * corant-shared * * @author bingo 下午5:49:59 * */ public class ConverterHints { public static final int CVT_MAX_NEST_DEPT = 3; public static final String CVT_NEST_DEPT_KEY = "converter.max.nest.dept"; public static final String CVT_NUMBER_RADIX_KEY = "converter.number.radix"; public static final String CVT_NUMBER_UNSIGNED_KEY = "converter.number.unsigned"; public static final String CVT_TEMPORAL_FMT_PTN_KEY = "converter.temporal.formatter.pattern"; public static final String CVT_TEMPORAL_FMT_KEY = "converter.temporal.formatter"; public static final String CVT_TEMPORAL_EPOCH_KEY = "converter.temporal.of-epoch"; public static final String CVT_TEMPORAL_STRICTLY_KEY = "converter.temporal.strictly"; public static final String CVT_BYTES_PRIMITIVE_STRICTLY_KEY = "converter.bytes-primitive.strictly"; public static final String CVT_ZONE_ID_KEY = "converter.zone-id"; public static final String CVT_LOCAL_KEY = "converter.local"; public static final String CVT_CHARSET = "converter.charset"; public static final String CVT_CLS_LOADER_KEY = "converter.class-loader"; public static final String CVT_FREE_AFTER_CONVERTED = "converter.free-after-converted"; public static final String CVT_CASE_SENSITIVE = "converter.case-sensitive"; private static final Map<String, ?> sys_hints = Collections.unmodifiableMap(resolveSysProHints());// static? public static boolean containsKey(Map<String, ?> hints, String key) { return hints != null && hints.containsKey(key) || sys_hints.containsKey(key); } public static <T> T getHint(Map<String, ?> hints, String key) { return getHint(hints, key, null); } @SuppressWarnings("unchecked") public static <T> T getHint(Map<String, ?> hints, String key, T altVal) { T hint = null; if (key != null && hints != null) { Object obj = hints.get(key); if (obj != null) { hint = (T) obj; } } return (T) defaultObject(hint, () -> defaultObject(sys_hints.get(key), altVal)); } static Map<String, Object> resolveSysProHints() { Map<String, Object> map = new HashMap<>(); resolveSysProHints(map, CVT_NEST_DEPT_KEY, Integer::valueOf); resolveSysProHints(map, CVT_ZONE_ID_KEY, ZoneId::of); resolveSysProHints(map, CVT_LOCAL_KEY, Locale::forLanguageTag); resolveSysProHints(map, CVT_TEMPORAL_FMT_PTN_KEY, s -> s); resolveSysProHints(map, CVT_TEMPORAL_FMT_KEY, s -> map.get(CVT_LOCAL_KEY) != null ? DateTimeFormatter.ofPattern(s, (Locale) map.get(CVT_LOCAL_KEY)) : DateTimeFormatter.ofPattern(s)); resolveSysProHints(map, CVT_TEMPORAL_EPOCH_KEY, ChronoUnit::valueOf); resolveSysProHints(map, CVT_TEMPORAL_STRICTLY_KEY, Boolean::valueOf); resolveSysProHints(map, CVT_BYTES_PRIMITIVE_STRICTLY_KEY, Boolean::valueOf); return map; } static void resolveSysProHints(Map<String, Object> map, String key, Function<String, Object> func) { String useKey = Names.CORANT_PREFIX.concat(key); String value = Systems.getProperty(useKey); if (value != null) { map.put(key, func.apply(value)); } } }
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class test_frame extends Frame implements ActionListener { calculatrice cal; TextField tf; public test_frame() { //initialise l'applet setSize(300,300); MenuItem mi ; setLayout(new BorderLayout()); //ajoute un tf tf= new TextField(); add(tf , BorderLayout.NORTH); //ajoute la calculatrice addWindowListener(new Fermeture()); MenuBar mb = new MenuBar(); setMenuBar(mb); Menu m1 = new Menu("fichier"); mb.add(m1); mi = new MenuItem("quiter"); mi.addActionListener(this); m1.add(mi); cal =new calculatrice(); add(cal , BorderLayout.CENTER); cal.init(); cal.start(); } public static void main(String[] args) { // TODO Auto-generated method stub test_frame tf = new test_frame(); tf.show(); } public void paint (Graphics g) { //affiche l'applet } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub System.exit(0); } }
/** * Access to Import controller * @return Returns the Import() instance */ func (me *COHESITYMANAGEMENTSDK_IMPL) Import() mimport.MIMPORT { if (me.mimport) == nil { me.mimport = mimport.NewMIMPORT(me.config) } return me.mimport }
Changing public service delivery: learning in co-creation Co-creation – where citizens and public organizations work together to deal with societal issues – is increasingly considered as a fertile solution for various public service delivery problems. During co-creation, citizens are not mere consumers, but are actively engaged in building resilient societies. In this study, we analyze if and how state and governance traditions influence learning and policy change within a context of co-creation. We combine insights from the co-creation and learning literature. The empirical strategy is a comparative case study of co-creation examples within the welfare domain in childcare (Estonia), education (Germany) and community work (the Netherlands). We show that state and governance traditions may form an explanation for whether co-creation, learning and policy change occurs. Our paper suggests that this seems to be related to whether there is a tradition of working together with citizens and a focus on rule following or not. Introduction Co-creation can be described as the involvement of citizens in the initiation and/or the design of public services to develop beneficial outcomes (Voorberg, Bekkers, & Tummers, 2015, p. 1347. In co-creation initiatives, citizens are regarded as relevant partners, who have specific resources and competences which are valuable for (re)designing public service delivery (e.g. Alford, 2009;Bason, 2010;Bovaird, 2007;Parrado, Van Ryzin, Bovaird, & Löffler, 2013). Public officials and politicians are increasingly taking up co-creation with citizens as a way to address many of the public sector's problems. This seems to mark a paradigm shift, in which the dominant consideration of citizens as passive consumers of public services has changed toward a consideration of citizens as co-creators. Citizens are given the opportunity to participate in the joint framing of what relevant services and service outcomes are and how they should be organized. The rise of co-creation can also be considered a learning process, in which actors learn how to use each other's competences to develop new ways to confront public sector challenges (e.g. aging, unemployment, decline KEYWORDS co-creation; learning; policy change; state and governance traditions of legitimacy of public institutions). Despite its growing relevance, the role of learning in co-creation processes and the influence it might have on policy change has not received much academic attention yet (for an exception, see: Cassia & Magno, 2011). There is much that we still do not know about 'who learns' , 'what is being learned' and 'why it is being learned' in co-creation (Bennett & Howlett, 1992). These are important issues, since the co-creation framework forces contemporary public organizations and public officials to consider alternative sources of knowledge, information and experiences, which are bypassing established venues (Brandsen & Honingh, 2015). This study's aim is to understand whether co-creation and the learning process behind it has led to a change in the frames of the involved stakeholders (primarily citizens and public officials) and consequently, to policy change. We examine how the co-creation project's institutional and policy context may affect this process of frame adaptation and policy change. We expect that this is the case, since how and whether frame adaptation will occur depends on the institutional setting (Schön & Rein, 1995). So far, the literature on co-creation and co-production has left the influence of macro-level elements relatively unexplored, partly due to a lack of international comparative research (Brandsen & Honingh, 2015;Voorberg et al. 2015; see for an exception Pestoff, 2006). We address this gap in the literature by exploring two interrelated questions regarding co-creation: Does co-creation lead to frame adaptation and policy change? And how can this be explained by the state and governance traditions in which co-creation is embedded? The empirical analysis contributes to the literature by focusing on specific macro-level institutional elements, i.e. state and governance traditions, in three different countries characterized by different state and governance traditions (Estonia, Germany and the Netherlands). The remainder of this paper is structured as follows: in Section 2, we develop a theoretical framework. We elaborate on the concept of co-creation and why this implies changes in public service delivery. We also discuss how learning can be understood as a process of frame reflection and frame adaptation. Additionally, we analyze how the institutional context affects policy change and frame adaptation. In Section 3, we explain our research strategy. This is followed by a discussion of the results in Section 4 and a brief conclusion as well as suggestions for further research. Co-creation with citizens and the importance of learning The definition of co-creation as the involvement of citizens in the initiation and/or the design process of public services in order to (co)create beneficial outcomes (Voorberg et al., 2015(Voorberg et al., , p. 1347) emphasizes the 'initiation and/or design process' and implies a more fundamental role for citizens in public services. This role implies more than asking citizens just to participate in the production of public services. This idea has been illustrated in the literature by Ugo Rossi (2004), who described how the historic city center of Naples (Italy) was restored due to a citizen initiative. The municipality recognized this initiative as a token of urgency given by the local community and decided to participate in the initiative. As such, it shows how co-creation changed conventional ideas about who is responsible for public service delivery and how decisions are made about the allocation of public resources. As Rossi noted, the success of this initiative was influenced by citizens' and public officials' willingness to learn from each other. The municipality of Naples showed this willingness by deciding to take the citizen initiative seriously and gave citizens ownership over the reconstruction process. Other examples where citizens have taken up the role of initiators in public service delivery involve participation in childcare services (Pestoff, 2006) and participation into budgeting procedures of municipalities (e.g. Ackerman, 2004;Maiello, Viegas, Frey, & Ribeiro, 2013). The importance of learning as an inherent part of co-creation has been recognized for almost two decades in the marketing literature. Prahalad and Ramaswamy (2000), for example, have argued that involving consumers in the production process implies that companies should strive for an active dialog with them and mobilize consumer communities to create tailor-made products. Also in the public sector, the importance of learning in co-creation is gaining more attention. Public officials are urged to consider citizen 'lay knowledge' as a valuable source of insight into how to (re-)design public services (e.g. Cornwell & Campbell, 2012;Guston, 1999;Hardey, 1999;Peters, Stanley, Rose, & Salmon, 1998). Nonetheless, a broader notion of learning has not received much academic attention yet and learning in (public) co-creation is a relative unexplored concept. This paper aims to open the 'black box' of co-creation, by focusing on whether and how co-creation facilitates this learning process. In the next section we analyze what learning in co-creation may imply. Learning in co-creation: a process of frame adaptation During co-creation, multiple actors participate in mutually dependent relationships (e.g. Bovaird, 2007;Lelieveldt, Dekker, Voelker, & Torenvlied, 2009). We can therefore argue that learning in co-creation is a social process, in which shared convictions about problems and solutions are the result of a dialog between actors. In accordance with Dunlop and Radaelli (2013), we define learning as the updating of beliefs. Approaching learning as a social process implies that updating of beliefs is the result of sense making about the meaning and interpretation of facts and events (Weick, 1995). To determine whether learning has taken place, we analyze whether stakeholders' frames about what the problem is and how it should be solved are indeed updated to new, shared convictions about problems and solutions. We define frames as images, influencing the convictions and actions around a policy matter by offering a problem definition, causal explanation, target group and a solution (Benford & Snow, 2000;Fischer, 2003;Schön & Rein, 1995). According to Schön and Rein (1995), learning involves a process of critical reflection and of changing actors' individual frames. Benford and Snow (2000), p. 616, 617 distinguish three kinds of frames. These are (1) diagnostic framing, referring to the causes of a specific policy problem, the effects and the target group the problem involves, (2) prognostic framing, referring to the identification of possible and relevant solutions and approaches and (3) motivational framing, which provides a rationale for engaging in collective action. Co-creation creates a new division of roles in public service provision, where citizens become partners to public officials. This implies that co-creation can be considered a prognostic frame: co-creation as an option to deal with a specific policy challenge involves a change in the traditional division of labor between citizens and public official. The question is whether this frame is being adopted and shared by the various stakeholders. If this is the case, we can predict that a policy change will probably occur. Downloaded by at 02:27 28 October 2017 Dunlop and Radaelli (2013) stressed that the combination of different individuals in learning processes and the control of these individuals ('learners') over the objectives of learning leads to different types of knowledge production. In other words, different sets of actors lead to different kinds of learning results and therefore, also to different forms of policy change. To Hall (1993) policy change involves a change in 'the overarching goals that guide policy in a particular field, the techniques or policy instruments used to attain those goals, and the precise settings of these instruments' (p. 278). As such he considers policy change as a reliable indicator for learning. He distinguishes three levels of policy change. First order change refers to an incremental modification of the existing objectives and instruments of policy. This modification involves an adaptation of current policy to current times, without changing overarching policy goals. Second order change refers to a major change of instruments of policy 'without radically altering the hierarchy of goals behind policy' (Hall, 1993 p. 282). As such, second order change involves a change in ideas of how policy objectives should be accomplished, but not which policy objectives should be accomplished. Finally, third order change involves a policy paradigm shift. A paradigm shifts occurs when there are radical changes in the hierarchy of policy objectives, the instruments used to achieve those changes and the discourses used to legitimize these changes. Third order change is more radical than first and second order change. In this study, we examine whether co-creation causes policy learning (in terms of prognostic frame adaptation) and whether this may lead to different levels of change. We treat learning and policy change as separate concepts, which enables us to see whether indeed policy change is an indicator for learning. State and governance traditions Since frame adaptation is always 'situated' in a certain institutional context, it can be the case that dominant state and governance traditions influence learning processes. Co-creation and co-production scholars have predominantly researched how and which institutional elements influence co-creation, such as having a risk-averse administrative culture (Maiello et al., 2013). Institutional elements may influence the prognostic frames of involved actors in terms of how suitable co-creation is as an approach to deal with specific policy challenges. As mentioned before, due to the lack of knowledge about how contextual elements on the macro-level influence co-creation, we focus our comparison on state and governance traditions. In line with Painter and Peters (2010), we treat state and governance traditions as a set of grown ideas and established practices that often act as structures that influence the policy style and substance of public administration in a country. The influence of state and governance traditions may explain why governments respond very differently to conceptually identical challenges (Pollitt & Bouckaert, 2011). Parting from the literature, the factors that define state and governance traditions can be categorized along two dimensions (Lijphart, 2012): sharing of authority and the culture of governance. The first dimension refers to sharing of authority with non-governmental parties, ranging from a consultative to an authoritative style. A government that can be characterized as consultative or consensual on this dimension is one where multiple collaboration structures have grown between government and social partners, civil society and private actors. One that can be characterized as authoritative is one where decisions are made predominantly by governmental bodies. In this regard, Pollitt and Bouckaert (2011) speak about majoritarian countries, whereby the majority of the electorate, as represented, for instance, by parliament (50 + 1) can determine policy directions in an authoritative manner, based on this majority. This may lead to sweeping changes in policy and reforms. In contrast, in consensual countries, decision-making takes place in consultation with partners who do not necessarily belong to this majority. The second dimension refers to the dominant normative convictions about how government should act. We label this dimension as the culture of governance. A state can be characterized as either 'Rechtsstaat' oriented or as 'Public Interest' oriented (Pierre, 1995). In Rechtsstaat-oriented states, stately efforts are focused on the preparation, promulgation and enforcement of laws. These states are characterized by a culture of governance aimed at maintaining legal correctness and legal control (e.g. Germany). The 'public interest' model (e.g. Anglo-Saxon countries, like the UK) accords a less dominant role to rules and regulations in society. Government acts rather as a referee, safeguarding equal distribution of resources and deciding which party (for instance competing interests groups) serves the public interest best. In such Public Interest cultures, pragmatism and flexibility is favored over the technical and legal expertise that is dominant in 'Rechtsstaat' countries (Pollitt & Bouckaert, 2011 p. 62). We will analyze how these different state and governance traditions influence learning and policy change in co-creation. Figure 1 shows a heuristic overview of the main concepts. In the next section, we present the research methods to study this. Research strategy Given the limited empirical knowledge about the relations between state and governance traditions, co-creation, policy learning and policy change, a case study is an appropriate method for the study. Case studies allow us to analyze whether and how state and governance traditions influence learning and policy change in-depth. This study is as a co-variational international comparative case study. The study is co-variational, since we selected the cases based on the independent variable, i.e. state and governance traditions. As such, this study is aimed at exploring how a specific cause (X) may affect a certain outcome (Y) (Blatter & Haverland, 2012;Yin, 2009 We selected two cases with similar state and governance traditions (Germany and the Netherlands), and one case with a most different state and governance tradition (Seawright & Gerring, 2008) (Estonia). Estonia (with its communist background) is characterized by an authoritative state tradition. The culture of governance is formally a Rechtsstaat-based legal and governing system but just as in Finland (Pollitt & Bouckaert, 2011), the culture of governance is changing from a Rechtstaat to a more plural one (Sarapuu, 2012). In most social policy areas, the role of the state is described by familial responsibility rather than by a legal one (Tõnurist & De Tavernier, 2017). We argue, therefore, that its governance culture is closer to a 'public interest' culture, in comparison to the culture in Germany and the Netherlands. An overview of the state and governance traditions is shown in Table 1. A second set of selection criteria was used to ensure that our cases were as similar as possible on other important elements. First, all selected cases involved co-creation, in which citizens took the initiative. Second, all selected cases involved co-creation within the welfare domain. Third, all selected cases represent co-creation projects that had been running for at least one year. We acknowledge that since we examined only one case per country, the external validity of the findings is limited. However, our study aims at exploring how and whether there is a plausible relation between learning and policy change due to the institutional context. Hence, our aim is analytical generalization, focusing on an enhanced theoretical understanding of co-creation by exploring what makes sense in a reasoned way. To enhance the internal validity, we operationalized the concepts in the model into an interview protocol. This protocol was used as a template to conduct our interviews among the involved actors in all our co-creation cases across the three selected countries (see Table 2). We interviewed 10 key actors in each case. Following Brandsen and Honingh (2015) we made a distinction between citizens (people who are voluntarily involved in co-creation) and public officials (people who are involved in co-creation on a professional basis and represent a public organization). All interviews were recorded and transcribed. Table 2 summarizes the concepts that were used as a coding scheme to analyze the data. The interviews were analyzed and concepts were coded and classified into categories related to plausible relations between co-creation, policy change and state and governance traditions. These were then compared to the concepts in Table 2. To increase the internal validity further, we also analyzed relevant policy documents published by both the co-creation projects themselves and the involved municipalities. These documents are listed in Appendix 1. Third, we organized focus groups of twenty academic experts in the field of co-creation/co-production to analyze our findings (held on 11 September 2014). Results For each country, we include (a) a short introduction to the case, (b) whether and which kind of policy change occurred, (c) whether new prognostic frames can be detected with the key stakeholders, and (d) whether these observations can be explained by the surrounding state and governance traditions. Case introduction The Estonian example, Maarja Küla (Maarja Village) was initiated in 2001 by a group of parents of children with learning disabilities and school staff of Tartu Maarja School. The parents were concerned that after finishing Tartu Maarja School, the youths with learning disabilities had very few opportunities and little support outside of their families. Maarja Küla was established to provide an inclusive living environment and development track (with educational and working opportunities) for young adults with learning disabilities. The value of the service was acknowledged after some time by the state with support to Maarja Küla and similar services being developed across Estonia with support from the government. The German case, Dialog macht Schule (DmS), was founded as a non-profit organization in 2008. It offers a civic educational program targeted at public schools in German neighborhoods where the majority of school-aged children have a migration background and also live in socially disadvantaged communities. Their model consists of introducing open dialog sessions focused on civic education into the school curriculum. The sessions are moderated by university students or recent graduates, who also have a migration background, and who have been trained by DmS to moderate the dialog sessions. During these sessions, themes such as identity, culture, nationalism, racism and other political and civic ideas are discussed. The aim is to create a space where students can learn to formulate their own opinions on political issues, and through that process, develop their political awareness and civic participation skills. The Dutch case, Starters4Communities (S4C), was initiated in 2013 by a social entrepreneur whose goal was to combine the talents of young, highly educated students and citizen initiatives. She noticed a lot of citizen initiatives in the east of Amsterdam aimed at increasing the livability within the city. However, these initiatives often failed because they lacked staff with administrative skills and/or did not have sustainable business plans. She also noticed that a lot of graduated youngsters were having trouble finding access to the labor market because they had no or little relevant work experience. S4C brings the young students and the initiatives together. By combining the skills of these youngsters and the enthusiasm of the civil initiators, the civil initiatives are being uplifted and the students receive valuable work experience. The municipality of Amsterdam recognized the potential of S4C for their own policy objectives and is now actively connected to this initiative. Policy change In Estonia, the shift toward co-creating services for disabled children can be considered a third order change, involving a paradigm change regarding who deserves care, how children's disabilities and future development prospects are defined and how children with disabilities should be taken care of (Ministry of Social Affairs, 2010, 2011). Before the 1990s, disabled children usually placed in residential institutional care since birth. If families chose to diverge from this system, they would not receive any state support . In time, it became less common for people to think of disabled children as unintelligent or less deserving of equal treatment. As a result instead of putting children in institutions, children were placed in group-or family-based homes . As one of the parents involved with Maarja Küla put it: 'the overall special child care situation in Estonia at the end of 1990s was rather depressing and dark' . This created pressure for the families involved, who sought out alternatives for childcare provision. By supporting this movement to alternative youth care provision, the government changed its policy on youth care provision and started to actively educate public officials in these alternative services. In Germany, the co-creation initiative demanded a second level change in how the goals of integration policy are achieved. The co-creation initiative of Dialogue macht Schule aims at strengthening the civic education of all school-aged students in schools where a large proportion of the students have a migration background (i.e. who have immigrated to Germany or whose parents or grandparents immigrated to Germany). In German cities, about 40% of students with a migration background are concentrated in underperforming schools, whereas only 6% of non-migrant students are in such schools (Morris-Lange et al., 2013). Consequently, migrant students are underperforming compared with native German students and have more trouble finding a job. Civic education has been proposed as a new strategy for achieving successful 'migrant integration' . The purpose not to assimilate migrant cultures into the host one but to foster individual commitments to the underlying social and citizen values of a democracy. Students learn 'how to express themselves eloquently' (German citizen). Such skills are expected to help these students succeed in the labor market and in society. However, the required policy change was only partly realized. Although enjoying the support of many school principals and teachers, as the Berlin Department for Education, the program has faced resistance among the teachers' union and some schools. The ultimate goal -introducing Dialogue macht Schule as a permanent part of the curriculum -has not been realized yet. In the Netherlands, the shift toward co-creation can also be considered a second level change in public service provision. The Dutch King stated that the Netherlands has turned into a participation society, implying that every citizen is asked to contribute to the wellbeing of themselves and others within their direct environment (State of the Throne, 2013). The underlying idea behind this shift is that the current welfare state is unaffordable and needs to be reformed: public organizations should take a step back and allow citizen initiatives to come up with smart solutions. Starters4Communities offers one such smart solution. The basic idea is that well-educated young people help existing civil initiatives become more sustainable by making business plans and organize external communication. Instead of providing these initiatives, government policy changed to financially supporting these initiatives and connecting people, organizations and other resources. This changed role has become part of the official policy of the municipality of Amsterdam (Gemeente Amsterdam Stadsdeel Oost, 2014). As a result Starters4Communities represents a fundamental shift in how public services are delivered and who is responsible for what part of service provision. Change of prognostic frames The cases indicate a clear relation between the change in the prognostic frames of involved actors and whether policy change indeed occurred. In Estonia, the prognostic frames of both citizens and public officials changed. Citizens became increasingly convinced that the conventional way of providing youth care services was not suitable to address the needs of disabled children. One of the initiators explained: By the time we started Maarja Küla, there was a common belief shared in the community of the disabled people and their family members that social services and especially teaching methods of children with disabilities (shunning them away from society) were unacceptable. Parents became increasingly aware that these children have a need for personalized care and more substantive daytime activities (Praxis, 2011). Involved public officials (and also politicians) also changed their prognostic frames by deciding to (financially) support alternative ways of providing youth care services. As one public official mentioned: 'I think Maarja Küla was an important breaking point as an institution that was motivated to involve different stakeholders and to fill the gap that was missing in Estonia'. In Germany, the involved public officials' prognostic frames were only partially adapted in favor of the co-creation initiative. In recent years, the discourse on the integration of migrants has intensified in Germany (SVR, 2012). Integration has been mainly understood as the extent to which incomers adopt the mainstream socioeconomic, legal and cultural norms of the host community . German public opinion has been concerned about whether migrants and their children adopt the host country's cultural norms, or maintain allegiance to those of their homeland. Diagnostic frames about the issue at hand have changed somewhat: there are teachers and headmasters who really see a need for this kind of civic and personal education -many of them simply cannot reach their students on any level in the classroom because they are so separated from them, so they are desperate for solutions and have really welcomed Dialogue Macht Schule into their classrooms. (German public official). Schools are believed to provide an important arena to address integration problems. The respondents indicated that Dialogue macht Schule has changed Downloaded by at 02:27 28 October 2017 ideas about how this problem should be dealt with. For instance, regarding how integration should be approached, respondents indicate that it is not assimilation of cultural traits by the migrant community, but an adoption of the underlying values of a liberal democracy (i.e. a partial change in diagnostic frames). However, public officials differ in opinion whether Dialogue macht Schule should be fully incorporated within the school system, noting that ' oppose to letting non-professional staff into the classroom' (German public official). This shows that prognostic frames about how to address integration in schools are only partially changed. In the Netherlands, public officials indicated that prognostic frames have changed, and in particular, those of high-level public officials. From a policy perspective, prognostic frames were changed in favor of co-creation (Municipality of Amsterdam, 2013 , 2014). This is also confirmed by our interviews. As one public official mentioned: 'We don't organize anything, that's the big change with the past. We change from 'taking care for' to 'make sure that' . Instead of taking care for people we only facilitate ' . However, public officials also indicated that not everyone shows this change of prognostic frames. One mentioned: 'Responses are different. Especially people in the 'line' of the organization are like, first, show me what you got' (Dutch public official). Furthermore, some public officials are not convinced that co-creation is a better way to provide welfare services than the professional institutions: 'What I see is nice and useful but it's not going to be better, when you chase away the professionals and replace them with volunteers'. Interestingly, the involved citizens did not show a clear change in their prognostic frames either. They thought of co-creation as a collaborative relationship with existing organizations but one in which public officials remain responsible for the quality and safety protocols. As one participating citizen mentioned: 'The supervisors are professionals. They know the criteria. Of course you need to comply with the conditions. That's their job'. So in this case, high-level public officials (and public policy documents) show clear changes in prognostic frames, but 'street' public officials and citizens did not. Now that we have explored the relationship between frame adaptation and policy change, we examine in the next section how this can be explained by surrounding state and governance traditions. Dimension 1: authority sharing Estonia has been independent from the Soviet Union Since 1991. As a result, the parliamentary structure and the tradition sharing of authority with non-governmental parties is relatively young and still carries traces of the authoritative state tradition that was dominant under the Soviet regime (Praxis, 2011;. One of the interviewed public officials described: I think that our democratic system is still quite young: on the one hand, the government is not accustomed to being in dialog with citizens, reacting to them. On the other hand, citizens are not used to talk about tutelage in social policy, fight for their rights, get their message across -basically influence the government, reach an agreement and then defend it. This authoritative tradition allowed a third level policy change to be implemented in quite a short time period; governmental action was not 'hampered' by institutional barriers of consultation and negotiation with other stakeholders. As one of the initiators of Maarja Küla said: 'Siiri Oviir, the then minister of social affairs, removed the obstacles in about 20 min that stood away in the development of the village in 2003' (Estonian citizen). So once prognostic frames were changed about how youth care should be provided, adapting the corresponding policy was relatively 'simple' . In contrast, the German administration acts according to rule-bound and legalistic procedures. Moreover, there are strong interdependencies between the many government levels. The implementation of federal legislation in most policy areas is delegated to the state (Länder) level, where in turn, it is often delegated further to local authorities. Regarding the Dialogue Macht Schule program, there is 'a clear separation between formal education that takes place in school and non-formal education, like what Dialogue Macht Schule is teaching, which should remain outside school' (German public official). This can explain why the initiators of co-creation have encountered difficulties in convincing stakeholders to adopt the initiative as an integral part of school curriculum (education policy is made at the federal level but implemented locally). The program mainly co-operated with the city district level but they only have limited policy-making power. Consequently Dialogue Macht Schule needed to lobby on many different administrative levels in order to convince administrators of the usefulness of the program. This is a gradual and time-consuming process. The Netherlands have a tradition of consensus gaining with social partners. This implies that Dutch governmental bodies are used to collaborating with non-governmental bodies, resulting in special budgets and funds being available for innovation and collaboration (Gemeente Amsterdam Stadsdeel Oost, 2013 ). As a result, the structures for collaboration needed to make co-creation work were already present. As one public official mentioned: ' Alliances were already there they are becoming real good neighborhoods if citizens wants to invest in it' . This could explain why some public officials adapted their prognostic frames toward co-creation. That said, while collaborating with other parties is not new in Dutch policy, working so closely with citizens in a relatively informal manner is new (see dimension 2). Dimension 2: culture of governance The Estonian culture of governance can be characterized as Public Interest (although it works differently than in Anglo-Saxon countries). Law -at least in the field of social policyis more in the background compared to the Rechtsstaat states. As a result, government acts as the referee deciding which party serves the public interest at best and other parties make efforts to win the support of government. One of the initiators of Maarja Küla described: ' At the end of the 1990s a lot of things were still in flux and we wanted to prove to the government that we could do things in a different way' . This relatively informal character means that projects depend on the continued favor of government to maintain political and financial support. Where in Rechtsstaat states policy is relatively stable, in Public Interest states, interest groups need to keep fighting for attention and financial support from government. As one citizen mentioned: 'Maarja Küla is in effect in 'competition' with similar initiatives and other social projects for the same funds' . Germany can be characterized by a Rechtsstaat culture of governance. This implies that the division of responsibilities among actors for public service delivery is governed by formalized rules and procedures. As a result, public officials' flexibility in decision-making is restricted. In the case studied here, this implies that changes in a policy area as fundamental as education can only occur slowly and are constrained by the regulatory framework. For example, several school headmasters said they would like to hire teachers who are more willing to work on programs like Dialogue Macht Schule, but this is not possible because schools have little control over hiring staff: 'these decisions are made at the state level according to a strict hierarchy' . Consequently, changing the curriculum and introducing an alternative way of education provision is slow and requires changes of prognostic frames of both administrative and political actors, which then need to be formalized into regulation. As one German official mentioned: 'Only now are we seeing a gradual expansion of extracurricular activities and changes in this attitude' (German public official). The Netherlands is also characterized by a Rechtsstaat culture of governance. Combined with a tradition of consensus gaining, it means that collaboration structures in the Netherlands are institutionalized and formalized in laws and regulation. Consequently, policy is relatively difficult to change. As one citizen argued: 'I think that the administrative context is rather sloth. Decision-making is just too slow' . As a result, professional organizations have gained an authoritative position when it comes to knowledge and expertise, which is formalized in rules and regulation and they do not want to 'surrender' this historically gained position to citizens. They argue that public service quality will decrease if co-creation is embraced as the new way of public service delivery: ' not going to be better, of that I am convinced. If you just replace professionals, it's not going to be more effective'. Because of this formalized way of collaborating, the involved public officials reacted in two different ways. Some of them argued that public officials feel restricted by the rules and the bureaucratic procedures to seek alternative ways of service provision that are not based on a regulative framework. As one of the citizens mentioned: 'What I heard from civil servants is: I really want to, but I can't, due to all that bureaucracy. And if I want it I have to consult with others, and they all want something else' . On the other hand, this perceived excess of rules and regulations is considered by some public officials as a reason to consider co-creation as a viable new way of public service delivery, as these projects are not yet 'locked-in' administrative procedures. As one of the officials argued: 'those new initiatives don't have those evaluative frameworks yet' . So the Rechtsstaat culture offers an explanation for why some actors changed their prognostic frames in favor of co-creation, while others held on to the more conventional ones, although in a more nuanced way than in the German case. The cases indicate that state and governance traditions may affect how and whether co-creation changes prognostic frames and policy change. The Estonian case shows that an authoritative state tradition may help actors implement co-creation and change policy in favor of co-creation in a top-down manner. The German and the Dutch case show that having a consensus gaining tradition means many actors are responsible for different parts of public service delivery and that decision-making and implementation processes are slower. Combined with the Rechtstaat culture of governance, which sees collaboration structures as institutionalized and formalized, policy change is slow and locked in administrative rules and regulations. This was different in Estonia where regulative frameworks are less rigid that in Germany and the Netherlands. However, this also shows that welfare policy in Estonia is less stable than in the two other countries, which creates competition between co-creation initiatives. Conclusion Co-creation is increasingly seen as a viable way to address contemporary challenges in public service delivery (Voorberg et al., 2015). As such, frames about what the fundamental problems are and how these should be dealt with are changing. This frame adaptation is a learning process between public officials and citizens. Given the lack of academic attention in the co-creation and co-production literature to this learning process and its relation to policy change, we have addressed this issue. The study took into account the state and governance traditions in which co-creation and learning processes take place to address the following research questions: Does co-creation lead to frame adaptation and policy change? And how can this be explained by the state and governance traditions in which co-creation is embedded? To answer the research questions we have conducted an international case comparison in Estonia, Germany and the Netherlands. The study showed that co-creation does lead to frame adaptation and policy change. The Estonian and Dutch cases indicated, that once prognostic frames (i.e. the identification of possible and relevant solutions and approaches for a problem) were changed, policy was also changed in favor of co-creation. In Germany, policy change occurred to a lesser extent, and the prognostic frames of German public officials were also changed to a lesser extent. However, to conclude that where we observe learning, there has been a policy change is too simple a conclusion. Our cases show that how policy changes is affected by the macro context of state and governance traditions in which actors and policy are embedded. The Estonian case showed that due to an authoritarian state tradition, policy change in favor of co-creation was relatively easy. This was strengthened by the fact that in Estonian welfare policy, the rule of law has a less prominent role than in the Rechtstaat cultures (Netherlands and Germany). Policy change is not 'obstructed' by regulative frameworks, which was the case in the other two countries. Here, we recognize how the consultative state tradition and the shared responsibility over many actors meant that the prognostic frames of many more actors needed to change in order to create policy change. In sum, to create a more comprehensive understanding of how and whether policy is changing accordingly, we need to take the context of state and governance traditions into consideration. Doing so offers a plausible explanation for contrasting relations between learning and policy change. These conclusions have theoretical implications for both the literature on co-creation and the literature on learning and policy change. To start with the latter, this research shows that due to the involvement of citizens as co-creators in public service design, learning is required to cause policy change. However, contrary to the assumptions of Hall (1993), we did not find that policy change is a reliable indicator to whether learning has occurred. Our analysis showed that in co-creation, the relationship between learning and policy change is more complicated. For instance, policy change does not by definition occur when actors show adapted frames. Furthermore, not every policy change is a result of frame adaptation of actors. Institutional arrangements -such as regulatory frameworks -should be considered as well. We add to the co-creation literature by taking a learning perspective. This allows us to open the black box of co-creation a little bit and offers an explanation why co-creation was successfully implemented in some cases. We've shown how actors from different backgrounds develop comparable ideas about problems and solutions and learn based on those contexts. In particular, in our Estonian case, an alignment of frames became visible. Related to this, the co-creation project in Estonia was the most smoothly implemented one of all are three cases. This way, a learning perspective provides us the possibility to identify a potentially key determinant of successful co-creation. Furthermore, we add to both bodies of literature by arguing, in line with Schön and Rein (1995), that in order to go one step further and to understand whether learning (i.e. frame adaption) and policy change have occurred or not, one needs to consider the institutional context surrounding the co-creation initiative. Our research shows that this macro-level context could potentially influence whether actors are willing and able to align their frames in co-creation processes. Analyzing learning as a process of frame adaptation (Schön & Rein, 1995) and making a distinction between diagnostic and prognostic frames (Benford & Snow, 2000) is a useful approach to empirically examine to what extent learning occurs. We must, of course, place our conclusions into perspective. In the first place, this paper was focused on whether change in frames occurred in processes of co-creation. In our analysis, we were therefore focused on only one aspect of co-creation. Given that co-creation is a processual concept (i.e. consisting of different stages), it may be important to examine how learning can be related to different aspects of this process, i.e. decision-making, implementation and evaluation. Future research is needed to conclude whether learning is such an inherent part of co-creation in the public domain, as suggested by Prahalad & Ramaswamy (2000). Secondly, we were only able to examine one case in each country. Variation in learning and policy change between the cases is possibly also explained by other characteristics of the case than just state and governance traditions. Including multiple cases from one country may nuance the findings. However, our aim was not to make statistically generalizable claims about the influence of state and governance traditions, but merely to explore whether they could offer a plausible explanation for learning and policy change. Future research must show to what extent there is a significant correlation between the kind of state and governance traditions and whether learning and policy change does occur. By focusing research on this topic, we can elaborate to what extent there is a significant relation between learning and policy change (Hall, 1993). Furthermore, in doing so, we can conclude what kind of institutional context can be considered as a fertile breeding ground for co-creation and which one is not. Disclosure statement No potential conflict of interest was reported by the authors. Funding This work was supported by FP 7 Learning from Innovation in Public Sector Environment (LIPSE) 320090. Notes on contributors William Voorberg is a doctoral candidate at the department of Public Administration and Sociology at Erasmus University Rotterdam.
#pragma once struct lua_State; namespace Afk { /** * Add bindings for imgui to the engine */ auto add_imgui_bindings(lua_State *l) -> void; }
Physiological studies on nitric oxide in the right sided colon of patients with diverticular disease. BACKGROUND/AIMS Previously, we reported that non-adrenergic non-cholinergic (NANC) inhibitory nerves are decreased in the left-sided colon of patients with diverticular disease, contributing to their intraluminal high pressure by segmentation (1). It is established that nitric oxide (NO) is released by stimulation of NANC inhibitory nerves. Among Oriental people, including the Japanese, right-sided diverticular disease has predominated more frequently than among Western people. In order to evaluate the function of NO in the right-sided colon of patients with diverticular disease, we examined the enteric nerve responses in colonic materials from patients with this disease, using the right-sided normal colon as a control. METHODOLOGY Colonic tissue specimens were obtained from 8 patients with diverticular disease of the right-sided colon, and normal segments of the right-sided colon were obtained from 11 patients with localized diseases. A mechanograph was used to evaluate in vitro colonic responses to electrical field stimulation (EFS) of adrenergic and cholinergic nerves before and after treatment with various autonomic nerve blockers, N(G)-nitro-L-arginine (L-NNA), and L-arginine. RESULTS 1) Cholinergic nerves were more dominant in the diverticular colon than in the normal colon (p<0.01). 2) NANC inhibitory nerves were found to act on the normal colon and to a lesser extent in the diverticular colon (p<0.05). 3) NO mediates the relaxation reaction of NANC inhibitory nerves in the normal colon and to a lesser extent in the diverticular colon. CONCLUSIONS The intrinsic intestinal innervation contains excitatory and inhibitory nerves and the former, especially cholinergic nerves, are dominant in the right-sided colon with diverticula. In addition, reduction of the action of NANC inhibitory nerves by substances such as NO may be largely related to the tight intraluminal pressure by colonic segmentation observed in the right-sided colon with diverticula.
#include<bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define mod 1000000007 #define mod2 1000000000 #define mod1 998244353 #define lol ios_base::sync_with_stdio(false);cin.tie(NULL); #define all(x) (x).begin(), (x).end() #define F(i, n) for (ll (i) = 0; (i) < (n); (i)++) #define pb push_back #define pf push_front #define mp make_pair #define f first #define ss second const int MAXN = 100000+5; set <ll> g[MAXN]; vector <ll> ch[MAXN]; void dfs(ll v,ll f=0) { for(auto u:g[v]) { if(u==f) continue; dfs(u,v); ch[v].pb(u); } } int main() { lol; ll n;cin >> n; ll c[n+1]; ll pp[n+1]; ll root = -1; for(ll i=1;i<=n;i++) { ll p; cin >> p >> c[i]; if(p==-1) { root = i; continue; } pp[i] = p; g[p].insert(i); g[i].insert(p); } dfs(root,0); vector <ll> ans; for(ll i=1;i<=n;i++) { if(c[i]==0) continue; ll fl = 0; for(auto ii:ch[i]) { if(c[ii]==0) fl=1; } if(fl==1) continue; for(auto ii:ch[i]) { g[ii].erase(i); g[i].erase(ii); g[ii].insert(pp[i]); g[pp[i]].insert(ii); } ans.pb(i); } if(ans.size()==0) { cout << -1 << endl;return 0; } for(auto i:ans) { cout << i << " "; } cout << endl; }
import enum from pydantic import BaseModel, Field from typing import List, Optional from datetime import datetime class CDOContext(BaseModel): """Common CDO Context arrtibutes""" tags: Optional[dict] tag_keys: Optional[list] = Field(alias="tagKeys") tag_values: Optional[list] = Field(alias="tagValues") uid: str name: Optional[str] namespace: str type: str # TODO: enum version: int created_date: Optional[datetime] = Field(alias="createdDate") last_updated_date: Optional[datetime] = Field(alias="lastUpdatedDate") action_context: Optional[dict] = Field(alias="actionContext") # TODO state: Optional[str] trigger_state: Optional[str] = Field(alias="triggerState") queue_trigger_state: Optional[str] = Field(alias="queueTriggerState") state_machine_context: Optional[str] = Field(alias="stateMachineContext") state_date: Optional[datetime] = Field(alias="stateDate") status: Optional[str] # TODO: enum state_machine_details: Optional[dict] = Field(alias="stateMachineDetails") scheduled_state_machine_enabled_map: Optional[dict] = Field(alias="scheduledStateMachineEnabledMap") pending_states_queue: Optional[list] = Field(alias="pendingStatesQueue") created_tenant_uid: Optional[str] = Field(alias="createdTenantUid") last_successful_login: Optional[datetime] = Field(alias="lastSuccessfulLogin") credentials: Optional[dict] model: Optional[bool]
#!/usr/bin/env python """ Make ROC plots for the ANN we trained """ import pathlib import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from final_project import model, io, alignment # Constants THISDIR = pathlib.Path(__file__).resolve().parent WEIGHTDIR = THISDIR / 'weights' MODELDIR = THISDIR / 'models' DATADIR = THISDIR / 'data' PLOTDIR = THISDIR / 'plots' # Functions def load_rand_data(positive_data, negative_file): """ Load a random sample of data :param positive_data: The numpy array of positive data, or a file containing positive examples :param negative_file: The negative examples as a FASTA file """ if isinstance(positive_data, pathlib.Path): pos_recs = io.read_example_file(positive_data) kmer = None x_data = [] y_data = [] for rec in pos_recs: if kmer is None: kmer = len(rec) else: assert kmer == len(rec) x_data.append(alignment.recode_as_one_hot(rec).ravel()) y_data.append(1.0) else: kmer = positive_data.shape[0] // 4 x_data = [rec for rec in positive_data.T] y_data = [1.0 for _ in x_data] # Random sample negatives (with replacement) print('Sampling {} negatives'.format(len(x_data))) neg_recs = io.read_fasta_file(negative_file) neg_indicies = np.random.randint(0, len(neg_recs), size=(len(x_data), )) neg_recs = [neg_recs[i] for i in neg_indicies] for rec in neg_recs: # Random sample a 17-mer i = np.random.randint(0, len(rec) - kmer, size=(1, )) samp = rec[int(i):int(i)+kmer] x_data.append(alignment.recode_as_one_hot(samp).ravel()) y_data.append(0.0) return np.array(x_data).T, np.array(y_data)[:, np.newaxis].T def calc_roc(positive_scores, negative_scores): """ Calculate the reciever operating characteristic :param positive_scores: The vector of positive scores :param negative_scores: The vector of negative scores :returns: the false positive rate, the true positive rate """ # Find the split points for each cutoff cutoff_min = np.min([positive_scores, negative_scores]) cutoff_max = np.max([positive_scores, negative_scores]) cutoffs = np.linspace(cutoff_min, cutoff_max, 200) # Using those cutoffs, calculate the empirical rates num_positive = positive_scores.shape[0] num_negative = negative_scores.shape[0] tp_rate = [1.0] fp_rate = [1.0] for cutoff in cutoffs: tp_rate.append(np.sum(positive_scores >= cutoff) / num_positive) fp_rate.append(np.sum(negative_scores >= cutoff) / num_negative) tp_rate.append(0.0) fp_rate.append(0.0) return np.array(fp_rate), np.array(tp_rate) def plot_roc_curve(x_data, labels, net, plotfile, title=''): """ Plot the ROC curve for the net's predictions :param x_data: The data to predict on :param labels: A mask of labels where 1 is a positive example and 0 a negative :param net: The net to predict the labels with :param plotfile: The filename to save the plot as """ # Have the net predict, then split the scores by ground truth scores = net.predict(x_data) distfile = PLOTDIR / plotfile.replace('roc', 'dist') fig, ax = plt.subplots(1, 1, figsize=(12, 12)) df = pd.DataFrame({'Condition': ['Positive' if int(i) == 1 else 'Negative' for i in labels[0, :]], 'Score': scores[0, :]}) sns.violinplot(x='Condition', y='Score', data=df, ax=ax) ax.set_title('{} Dist for Rap1 Identification'.format(title)) fig.savefig(str(distfile)) plt.close() fp_rate, tp_rate = calc_roc(scores[labels], scores[~labels]) # Make the plot plotfile = PLOTDIR / plotfile fig, ax = plt.subplots(1, 1, figsize=(12, 12)) ax.plot(fp_rate, tp_rate, '-o', linewidth=3) # Plot the line for perfect confusion ax.plot([0, 1], [0, 1], '--', linewidth=3) ax.set_title('{} ROC for Rap1 Identification'.format(title)) ax.set_xlabel('False Positive Rate') ax.set_ylabel('True Positive Rate') ax.set_xlim([-0.01, 1.01]) ax.set_ylim([-0.01, 1.01]) fig.savefig(str(plotfile)) plt.close() def main(): modelfile = MODELDIR / 'ann_rap1.json' weightfile = WEIGHTDIR / 'ann_rap1.npz' if not modelfile.is_file(): raise OSError('Train an ANN using `train_ann.py') if not weightfile.is_file(): raise OSError('Train an ANN using `train_ann.py`') # Load the model we trained net = model.load_model(modelfile) net.load_weights(weightfile) # ROC curve for the training data x_train, y_train = io.load_training_data(DATADIR / 'train_final.txt') plot_roc_curve(x_train, y_train > 0.5, net, 'roc_train_final.png', title='Training Data') # ROC curve for the test data x_test, y_test = io.load_training_data(DATADIR / 'test_final.txt') plot_roc_curve(x_test, y_test > 0.5, net, 'roc_test_final.png', title='Test Data') # ROC curve for the original positive examples vs a random negtive set x_rand, y_rand = load_rand_data(DATADIR / 'rap1-lieb-positives.txt', DATADIR / 'yeast-upstream-1k-negative.fa') plot_roc_curve(x_rand, y_rand > 0.5, net, 'roc_rand_true.png', title='Random True Sample') # ROC curve for our assumed positive examples vs a random negtive set x_train_pos = x_train[:, y_train[0, :] > 0.5] x_test_pos = x_test[:, y_test[0, :] > 0.5] print('Positive training: {}'.format(x_train_pos.shape)) print('Positive test: {}'.format(x_test_pos.shape)) x_pos = np.concatenate([x_train_pos, x_test_pos], axis=1) x_rand, y_rand = load_rand_data(x_pos, DATADIR / 'yeast-upstream-1k-negative.fa') plot_roc_curve(x_rand, y_rand > 0.5, net, 'roc_rand_final.png', title='Random Full Sample') # Test the two examples given in the HW pos_seq = 'ACATCCGTGCACCATTT' neg_seq = 'AAAAAAACGCAACTAAT' pos_enc = alignment.recode_as_one_hot(pos_seq).ravel()[:, np.newaxis] neg_enc = alignment.recode_as_one_hot(neg_seq).ravel()[:, np.newaxis] pos_score = net.predict(pos_enc) neg_score = net.predict(neg_enc) print('Positive example: {}'.format(pos_score)) print('Negative example: {}'.format(neg_score)) if __name__ == '__main__': main()
/** * Posts an {@link AdjustScrollerCommand} within the given <code> * delayMillis</code> * . */ private void postAdjustScrollerCommand(int delayMillis) { if (mAdjustScrollerCommand == null) { mAdjustScrollerCommand = new AdjustScrollerCommand(); } else { removeCallbacks(mAdjustScrollerCommand); } postDelayed(mAdjustScrollerCommand, delayMillis); }
def train(self, state, action, reward, next_state, done): if done: target = reward else: target = reward + self.gamma * np.amax(self.model.predict(next_state), axis=1) target_full = self.model.predict(state) target_full[0, action] = target self.model.sgd(state, target_full, self.alpha, self.momentum) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay
<filename>app/subdock/components/DraggableSubdockItem.tsx import * as React from 'react'; import { DragSource, DragSourceMonitor, DropTarget } from 'react-dnd'; import { getEmptyImage } from 'react-dnd-html5-backend'; import SubdockItem, { BareApplication, WrappedActions } from './SubdockItem'; import { findDOMNode } from 'react-dom'; import { compose } from 'redux'; import { withReorderFavoriteMutation, withReorderTabMutation } from '../../tabs/[email protected]'; // PROPS type GqlProps = { reorderTab: (tabId: string, newPosition: number) => any, reorderFavorite: (favoriteId: string, newPosition: number) => any, }; type OwnProps = { index: number, dragType: string, application: BareApplication, tabId: string, item: any, favorite: boolean, actions: WrappedActions, }; interface DndProps { connectDropTarget: (arg: any) => any, connectDragSource: (arg: any) => any, connectDragPreview: (arg: any) => any, isDragging: boolean, } type Props = OwnProps & GqlProps & DndProps; // DRAG SOURCE CONTRACTS // https://react-dnd.github.io/react-dnd/docs/api/drag-source#drag-source-specification const dockAppSource = { beginDrag(props: Props) { const { item, tabId } = props; return { index: props.index, application: { id: props.application.id }, item: { title: item.title }, tabId: tabId, }; }, endDrag(_props: Props, monitor: DragSourceMonitor) { const dropResult = monitor.getDropResult(); if (!dropResult) return; /* Add here any effects you would like. For example: if (dropResult.type === 'SOMETHING') { ...do something here } */ }, }; const SubdockItemTarget = { drop: () => ({ type: 'DND_SUBDOCK', }), hover(props: Props, monitor: any, component: any) { const { favorite, reorderTab, reorderFavorite } = props; const { tabId, index: dragIndex } = monitor.getItem(); const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { return; } // Determine rectangle on screen const domNode = findDOMNode(component); if (!domNode) return; const hoverBoundingRect = domNode.getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height // When dragging downwards, only move when the cursor is below 50% // When dragging upwards, only move when the cursor is above 50% // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { return; } // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { return; } // console.log(`dragIndex: ${dragIndex}, hoverIndex: ${hoverIndex}`); // Time to actually perform the action favorite ? reorderFavorite(tabId, hoverIndex) : reorderTab(tabId, hoverIndex); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; }, }; // DRAG COLLECT // https://react-dnd.github.io/react-dnd/docs/api/drag-source#the-collecting-function const collectTarget = (connect: any) => ({ connectDropTarget: connect.dropTarget(), }); const collectSource = (connect: any, monitor: any) => ({ connectDragSource: connect.dragSource(), connectDragPreview: connect.dragPreview(), isDragging: monitor.isDragging(), }); // COMPONENT @DropTarget(({ dragType }: Props) => dragType, SubdockItemTarget, collectTarget) @DragSource(({ dragType }: Props) => dragType, dockAppSource, collectSource) class DraggableSubdockItemImpl extends React.PureComponent<Props> { componentDidMount() { // Use empty image as a drag preview so browsers don't draw it // and we can draw whatever we want on the custom drag layer instead. this.props.connectDragPreview(getEmptyImage()); } componentDidUpdate() { // Used in componentDidUpdate too because of an issue (https://github.com/react-dnd/react-dnd/issues/1428). // There are high chances that this is fixed in more recent versions of DnD this.props.connectDragPreview(getEmptyImage()); } render() { const { isDragging, connectDragSource, connectDropTarget, application, actions, item, } = this.props; const opacity = isDragging ? 0 : undefined; return connectDragSource && connectDropTarget && connectDragSource(connectDropTarget( <div style={{ opacity }}> <SubdockItem application={application} actions={actions} item={item} /> </div> )); } } // COMPOSE const DraggableSubdockItem = compose( withReorderTabMutation({ props: ({ mutate }) => ({ reorderTab: (tabId: string, newPosition: number) => // @ts-ignore tabId exists on ownProps mutate && mutate({ variables: { tabId, newPosition } }), }), }), withReorderFavoriteMutation({ props: ({ mutate }) => ({ reorderFavorite: (favoriteId: string, newPosition: number) => // @ts-ignore tabId exists on ownProps mutate && mutate({ variables: { favoriteId, newPosition } }), }), }), )(DraggableSubdockItemImpl); // EXPORT export default DraggableSubdockItem as React.ComponentType<OwnProps>;
import program from "commander"; import { makeLogger } from "../../lib/logging" import { machineConfigPackage } from "@createdreamtech/carti-core" import * as clib from "@createdreamtech/carti-core" import { Bundle, bundle, PackageEntryOptions, generateLuaConfig } from "@createdreamtech/carti-core" import { Config, getMachineConfig, initMachineConfig, writeMachineConfig } from "../../lib/config" import inquirer from "inquirer" import { shortDesc, parseShortDesc } from "../../lib/bundle"; import * as utils from "../util" import os from "os" import https from "https" import fs from "fs-extra" import { spawnSync } from "child_process"; import path from "path" import rimraf from "rimraf"; import { promisify } from 'util'; import { bundleFetcher } from "../../lib/fetcher"; import { Readable } from "stream"; import { fromStreamToStr } from "../../lib/utils"; import url from "url" import { CID } from "multiformats"; const rmAll = promisify(rimraf) type addMachineCommandType = "ram" | "rom" | "flashdrive" | "raw"; export const addMachineCommand = (config: Config): program.Command => { const add = (addType: addMachineCommandType) => { return (name: string, options: PackageEntryOptions & {yes: boolean}) => { const { length, start, bootargs, shared, yes } = options return handleAdd(config, name, { length, start, bootargs, shared }, addType, yes) } } const machineCommand = program.command("machine") .description("Utilize cartesi machine commands to specify and generate stored machines") .storeOptionsAsProperties(false) .passCommandToAction(false) const machineAddCommand = new program.Command("add") .description("Add bundle to cartesi machine description using ram | rom | flashdrive | raw options") .storeOptionsAsProperties(false) .passCommandToAction(false) machineAddCommand.command("ram <bundle>") .description("add a bundle to the ram entry for carti-machine-package.json") .requiredOption("-l, --length <length>", "length of the drive in hex format ex. 0x4000") .option("-r, --resolvedpath <resolvedpath>", "specify a package outside of a cid the mechanism default uses") .option("-y, --yes", "choose match without prompt") .action(add("ram")) machineAddCommand.command("flash <bundle>") .requiredOption("-l, --length <length>", "length of the drive in hex format ex. 0x4000000") .requiredOption("-s, --start <start>", "start position of the drive in hex format ex. 0x800000") .option("-r, --resolvedpath <resolvedpath>", "specify a package outside of a cid the mechanism default uses") .option("-y, --yes", "choose match without prompt") .description("add a bundle to the flash entry for carti-machine-package.json") .action(add("flashdrive")) machineAddCommand.command("rom <bundle>") .description("add a bundle to the rom entry for carti-machine-package.json") .option("-b, --bootargs <bootargs>", "boot arguments for the rom") .option("-r, --resolvedpath <resolvedpath>", "specify a package outside of a cid the mechanism default uses") .option("-y, --yes", "choose match without prompt") .action(add("rom")) /* TODO: Feature needs more integration placeholder here. Pending implementation machineAddCommand.command("raw <bundle> - pending ") .description("add a raw asset bundle to the entry for carti-machine-package.json") .action(add("raw")) */ machineCommand.addCommand(machineAddCommand) machineCommand.command("build") .description("Build a stored machine from carti-machine-package.json") .action(async () => { return handleBuild(config) }) machineCommand.command("init") .description("Init a stored machine from carti-machine-package.json it is destructive") .action(handleInit) machineCommand.command("install <uri>") .description("Install a cartesi machine, installing bundles and optionally building a stored machine from a uri or file path specified carti-machine-package.json") .option("--nobuild", "install remote machine bundles but do not build stored machine") .action(async (uri,options) => handleInstall(config, uri,options.nobuild)) return machineCommand } const renderBundle = (b: Bundle): string => { const { bundleType, name, version, id } = b; return shortDesc({ bundleType, name, version, id, uri: "local" }) } async function handleInit() { return initMachineConfig() } async function getPackageFile(uri: string): Promise<Readable> { if (url.parse(uri).protocol === null) return fs.createReadStream(path.resolve(uri)) return new Promise((resolve) => { https.get(uri, (message) => { resolve(message) }) }) } async function handleInstall(config: Config, uri: string, nobuild:boolean): Promise<void> { //TODO add error handling here const packageConfig: machineConfigPackage.CartiPackage = JSON.parse(await fromStreamToStr(await getPackageFile(uri))) //check packages can all be resolved for (const asset of packageConfig.assets) { const bundles = await config.globalConfigStorage.getById(asset.cid) if (bundles === [] || bundles === undefined) throw new Error(`Could not resolve bundle for id:${asset.cid} name:${asset.name} try adding the repo`) const exists = await config.bundleStorage.diskProvider.exists(CID.parse(asset.cid)) if (exists) break await bundle.install(bundles[0], bundleFetcher(bundles[0].uri as string), config.bundleStorage) const path = await config.bundleStorage.path(CID.parse(bundles[0].id)) await config.localConfigStorage.add(path, [bundles[0]]) } if(nobuild) return return buildMachine(config, packageConfig) } async function handleAdd(config: Config, name: string, options: clib.PackageEntryOptions, addType: addMachineCommandType, yes: boolean): Promise<void> { const bundles: Bundle[] = await config.localConfigStorage.get(name) let bundle = bundles[0]; if (!yes) { const question = utils.pickBundle("Which bundle would you like to add to your cartesi machine build", bundles, renderBundle) const answer = await inquirer.prompt([question]) const { id } = parseShortDesc(answer.bundle) bundle = bundles.filter((b) => b.id === id)[0] } let cfg = await getMachineConfig() // NOTE we respect commandline ideal of what the bundleType should be so if you install something in // ram you can install the same data as a flash drive cfg = clib.updatePackageEntry(Object.assign({}, bundle, {bundleType: addType}), cfg, options) return writeMachineConfig(cfg) } async function handleBuild(config: Config): Promise<void> { return buildMachine(config, await getMachineConfig()) } async function buildMachine(config: Config, cfg: machineConfigPackage.CartiPackage): Promise<void> { //const tmpDir = await fs.mkdtemp(`${os.tmpdir()}/carti_build_package`) const tmpDir = path.resolve(await fs.mkdtemp(`carti_build_package`)) const machineConfig = await clib.install(cfg, config.bundleStorage, tmpDir) const luaConfig = generateLuaConfig(machineConfig, "return") await fs.writeFile(`${tmpDir}/machine-config.lua`, luaConfig) await fs.copyFile(`${__dirname}/../../scripts/run-config.lua`, `${tmpDir}/run-config.lua`) await runPackageBuild(tmpDir) //clean up return rmAll(tmpDir) } async function runPackageBuild(packageDir: string) { const { uid, gid, username } = os.userInfo() const command = ["run", "-e", `USER=${username}`, "-e", `UID=${uid}`, "-e", `GID=${gid}`, "-v", `${packageDir}:/opt/carti/packages`, "cartesi/playground:0.1.1", "/bin/bash", "-c", //"cd /opt/cartesi/packages && echo $(ls -l)" ] "cd /opt/carti/packages && luapp5.3 run-config.lua machine-config && echo 'package built'"] console.log("docker " + command.join(" ")) //TODO improve should stream output to stdout const result = spawnSync("docker", command) if (result.error || result.stderr.toString()) { console.error(result.stderr.toString()) return; } console.log(result.stdout.toString()) const storedMachinePath = `${packageDir}/cartesi-machine` if (fs.existsSync(`${process.cwd()}/stored_machine`)) await rmAll(`${process.cwd()}/stored_machine`) //NOTE just renaming to keep path's consistent await fs.move(storedMachinePath, `${process.cwd()}/stored_machine`) await rmAll(storedMachinePath) const loadMachineCommand = `docker run -e USER=$(id -u -n) -e UID=$(id -u) -e GID=$(id -g) \\ -v $(pwd)/cartesi-machine:/opt/cartesi-machine \\ cartesi/playground cartesi-machine --load='/opt/cartesi-machine'` console.log(`Copy command to run stored machine:`) console.log(`${loadMachineCommand}`) }
Comedy seems to work best when done in groups. This is not just true of older comedy routines – most modern television comedy hits are such due to the supporting actors. For example, Will and Grace would never have survived were it not for the character of Karen Walker. This list looks at ten of the most prolific and most well known comedy teams. It is perhaps a little light on the British comedy duos such as the Goons – but do feel free to name them all in the comments. 10 Amos and Andy Voiced by Freeman Gosden and Charles Correll, performing on the radio from 1928 all the way 1960. This sketch comedy act was based on turn of the century black minstrel acts, and the two voice artists depicted black people as poor, lower class menial workers, who eventually move from Georgia to Chicago and become taxi drivers. At least once, in 1931, when the Pittsburgh Courier took up the article of a black preacher who considered the show racially offensive (since the two voice artists were white). They tried to get a million names on a petition, in order to get the show canceled, but few people would sign it, not out of racial fear as much as out of enjoyment of the show. The black leads are always shown to be very simple-minded, but very polite and good-natured, and smarter than the average white man. They also thrived on malaprops, which are incorrect uses of a language. One of George “Kingfish” Stevens’s (played by Gosden) best such lines is, “Heck, naw, I ain’t gawn let my kids use no ‘cyclopedia! They kin walk to school like I did!” This was subsequently blamed on Yogi Berra, who, never to be outdone, said, “I didn’t say half the stuff I said.” 9 Frick and Frack Werner Groebli and Hans Mauch, respectively. They were comedic figure skaters, both from Basel, Switzerland, and performed all over the world in lederhosen and traditional German “Oktoberfest” garb. They performed in a few films, beginning with Lady, Let’s Dance, in 1944. They never performed in the Olympics, but a lot of Olympic figure skaters think they would have been shoe-ins for gold medals. “Frick and Frack” has become a household phrase in English, due to their popularity from the 1930s to the 1950s. Some of the stunts they performed defy belief, most notably Frack’s rubber legs, which were twisting, collapsing legs while skating in a spread-eagle. Frick’s signature move was a cantilever spread-eagle, which he invented. 8 The Smothers Brothers Tommy Smothers always plays the slower buffoon to Dick Smothers’s straight man. Tommy’s signature line was “Mom always liked you best!” after which they would argue over whether that were true or not. When their mother died, they never performed this routine again. They are accomplished guitar players, and Tommy is a master of the yo-yo. They have the distinction of being the longest-lived comedy team in American history, having performed for about 52 years. During the late 1960s, they had their own show, “The Smothers Brothers Comedy Hour,” which was extremely controversial (and funny) because of their peace advocacy. They regularly poked fun at the Vietnam War, President Nixon, and racism. The show lasted an amazing 2 years, 1967 to 1969, before being canceled for what CBS was forced to call “Anti-American Peace Propaganda.” Ah, the ’60s. 7 Cheech and Chong The hippies and counter-culturalists found their idols in the weed-smoking surrealists Cheech Marin and Tommy Chong. They broke up in 1985, but reunited in 2008 much to everyone’s delight. They made a number of films from 1978 through the 1980s, all having heavily to do with drug use, the free love of hippies, etc. Arguably their best work is the 1983 film Still Smokin’, in which they travel to Amsterdam, Netherlands, for a film festival about Burt Reynolds and Dolly Parton. When the latter two stars don’t show up, Cheech and Chong save the day with their own live stage performance. One of the best bits is Chong as “the old man in the park,” and the duo as “Ralph and Herbie the dogs.” 6 Abbott and Costello Bud Abbott played the straight man to Lou Costello, and even if they had only done one routine during their entire career, “Who’s on First?” would net them the #6 spot. They had already rehearsed it to perfection, but had not had a chance to perform it on stage. The first televised performance of it was at the Steel Pier, in Atlantic City, New Jersey. They had a few sheets of material written by someone else, and they didn’t think much of it, so Abbot asked Costello, “You wanna do Baseball?” “Yeah, let’s do it.” And they walked out and made history. It had been many times since before the radio days of burlesque vaudeville, with the simple gag of Who and What being proper nouns. Abbott and Costello were the first to hone it into its modern form of a baseball team’s names. They copyrighted it, and performed it several times in different films. None of this mentions the host of other outstanding performances to their credit. 5 Laurel and Hardy Well known to film buffs today as a duo of true friends. They were vaudevillians, in countless silent films together and separate, before teaming up in 1927, and remained together until Hardy’s death in 1957, appearing in a lot of films. By the 1950s, their healths were declining rapidly, and they no longer looked like their old selves. They were masters of slapstick, and an interesting idea that Laurel called “white magic.” A good example is in the film Way Out West, from 1937, one of their most famous, in which Laurel (the thin one) makes a fist, pours tobacco into it, flicks up his thumb and lights it, then blows real smoke out of his fist. Hardy proceeds to try duplicating it throughout the film, getting it right at the end, and freaking out about burning his thumb. They also have a famous soft-shoe dance number in this film. 4 Monty Python Britain’s, arguably the world’s, most irreverent comedy team so far, appearing on stage and in films from the late 1960s through the 1980s. Their films are still extremely popular, and very funny, the most famous of which is probably Monty Python and the Holy Grail. In it, King Arthur and his knights of Camelot, who eat ham and jam and spam a lot, traipse all over the English countryside looking for the Holy Grail, encountering a particularly tough Black Knight, a riddle-posing bridge guard, and God Himself. They have no horses, but at least they have coconuts to sound like horses, which a Cockney castle wall guard reminds them are not quite the same as horses. The conversation goes downhill thence. Their stage work is comparatively unheralded in America, but you can find a lot of it on YouTube. It is some of their very finest work. This lister’s favorite is a bit involving a man who’s just lost his mother, trying to get a mortician to bury her. The mortician replies that the mortuary can cook her or bury her, or dump in her the Thames. In finally ends with the mortician saying that he’ll cook her, the son can eat her, and then they’ll dig a grave and he can throw up in it. 3 The Three Stooges The most well known artists of slapstick in history were Moe and Curly Howard, and Larry Fine. Curly died of a stroke in 1952, and several people were chosen as replacements for a few more years, but it was never quite as good without him. Moe was the straight man, Curly the comedian, and Larry was something of both. Some of their gags are as physically demanding and dangerous as stunts you might see in a Looney Tunes cartoon. Curly or Larry would accidentally smack Moe in the head with something made of metal, and he would respond angrily, sometimes running a ripsaw over their heads, or smacking them with hammers. Their slap gags are always uproarious, and one of their most famous moments comes in the short Micro-phonies, from 1945, in which they lip-synch to the Sextet from Lucia di Lammermoor. 2 Martin and Lewis Martin was the straight man to Lewis’s utmost in zaniness. From 1946 to 1956, they were the pinnacle of the comedy world in Hollywood, performing around the country and in films. Martin was one of the finest crooners in history, but Lewis could belt out a song when he wanted. They could do it all, sing, dance, slapstick, vaudeville jokes, stand-up, and outstanding ad-lib segments. Their patented sketch was a Martin crooner, into which Lewis would walk with a silly face, and continue to interrupt him while he sang. 1 The Marx Brothers Modern comedians of all kinds, stand-up, sitcom, sketch, film and stage, look on the Marx Brothers with awe at how brilliant they were at every aspect of comedy. They grew as vaudeville performers, and although they couldn’t tapdance, they could certainly do everything else, and this lister means EVERYTHING. Harpo played the harp better than most professionals, and he taught himself by ear. His form was all wrong, but professionals came to him for instruction on how to play like him. Groucho was a fine singer, and usually sent himself up as a horrible singer. Chico could play the piano effortlessly, and was loved for his “shooting the keys” manner of playing, seen in A Night at the Opera, among others. Groucho’s one-liners and insults run throughout all their films and are still the stuff of legend. His greasepaint eyebrows and mustache are part of the classic Halloween, or gag glasses, with huge nose, that kids like to wear, or cartoons use to hide identities. Harpo’s voice was a rich baritone, and too low for his clownish persona, so he elected never to speak, except a few times at ceremonies, and on a talk show in the 1970s. This was one of his finest jokes, since he was begged to finally say something, and once he got going, the talk show host could not shut him up for a good 15 minutes. Chico’s name should be pronounced “Chick-O” not “Cheek-O,” because he was the brother all the chicks were after (according to him). He was also a gamblaholic, and they made some of their films just to pay off his debts. According to the late, great George Carlin, Groucho Marx told by far the funniest “Aristocrats” joke in history. It’s a notoriously dirty joke told from the turn of the century, by comedians who ad-lib the nastiest filth they can think of, and then end with the stupid punch-line “The Aristocrats!” Groucho didn’t care for dirty jokes, preferring clean jokes, in which more art is required to get a laugh. When asked about his version of it, he replied, “Well, bestiality’s not all that dirty.” Their performances in A Night at the Opera and Duck Soup are their finest efforts. The former includes the famous stateroom scene, the complete destruction of a production of Verdi’s Il Trovatore, and “The First Party of the First Part” sequence between Groucho and Chico. The latter includes their legendary mirror scene, the lemonade stand, their combat spoof (Groucho wears an American Civil War hat, then a coonskin cap, then a Napoleon hat, etc.) and their parody of Paul Revere’s Ride. They used a running joke throughout their films involving their meager accommodations growing up. Whenever they spot food in a film, they dash madly around the set, getting to the table, where they devour everything in sight, even their clothing.
<filename>iterator.go // Copyright 2014 <NAME>. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package containerkit // ============================================================================ // INTERFACE // ============================================================================ type Iterator interface { HasNext() bool Next() interface{} } // ============================================================================ // IMPLEMENTATION // ============================================================================ func CountElements(iter Iterator) int { res := 0 for iter.HasNext() { res++ iter.Next() } return res } // Empty iterator var EmptyIterator Iterator = new(emptyIterator) type emptyIterator struct {} func (this emptyIterator) HasNext() bool { return false } func (this emptyIterator) Next() interface{} { panic("EmptyIterator: no next element") } // Slice iterators func NewSlicedIterator(iter Iterator, drop int, dropWhile Predicate, takeWhile Predicate, take int) Iterator { // drop initial elements for i := 0; i < drop; i++ { if iter.HasNext() { iter.Next() } } // drop elements as long as they satisfy predicate takeWhile hasLookahead := false var lookahead interface{} = nil for iter.HasNext() && !hasLookahead { next := iter.Next() if !dropWhile(next) { lookahead = next hasLookahead = true } } return &slicedIterator{iter, hasLookahead, lookahead, takeWhile, true, take} } type slicedIterator struct { iter Iterator hasLookahead bool lookahead interface{} takeWhile Predicate evalTakeWhile bool take int } func (this *slicedIterator) HasNext() bool { return this.hasLookahead } func (this *slicedIterator) Next() interface{} { if this.hasLookahead { res := this.lookahead if this.iter.HasNext() { this.lookahead = this.iter.Next() if this.evalTakeWhile && !this.takeWhile(this.lookahead) { this.evalTakeWhile = false } if !this.evalTakeWhile { if this.take == 0 { this.lookahead = nil this.hasLookahead = false } else { this.take-- } } } else { this.lookahead = nil this.hasLookahead = false } return res } panic("slicedIterator: no next element") } // Filter iterators func NewFilterIterator(pred Predicate, iter Iterator) Iterator { res := &filteredIterator{pred, false, nil, iter} res.scan() return res } type filteredIterator struct { pred Predicate hasNext bool next interface{} iter Iterator } func (this *filteredIterator) scan() { for this.iter.HasNext() { this.next = this.iter.Next() if this.pred(this.next) { this.hasNext = true return } } this.next = nil this.hasNext = false } func (this *filteredIterator) HasNext() bool { return this.hasNext } func (this *filteredIterator) Next() interface{} { if this.hasNext { res := this.next this.scan() return res } panic("filteredIterator.Next: no next element") } // Map iterators func NewMappedIterator(f Mapping, iter Iterator) Iterator { return &mappedIterator{f, iter} } type mappedIterator struct { f Mapping iter Iterator } func (this *mappedIterator) HasNext() bool { return this.iter.HasNext() } func (this *mappedIterator) Next() interface{} { if this.iter.HasNext() { return this.f(this.iter.Next()) } panic("mappedIterator.Next: no next element") } // Flat-map iterators type flatMappedIterator struct { g Generator iter Iterator current Iterator } func (this *flatMappedIterator) scan() { for this.iter.HasNext() { if next, valid := this.g(this.iter.Next()).(Iterator); valid { this.current = next if this.current.HasNext() { return } } else { panic("flatMappedIterator.scan: generator did not return Iterator") } } this.current = EmptyIterator } func (this *flatMappedIterator) HasNext() bool { return this.current.HasNext() } func (this *flatMappedIterator) Next() interface{} { if this.current.HasNext() { res := this.current.Next() if !this.current.HasNext() { this.scan() } return res } panic("flatMappedIterator.Next: no next element") } // Composite iterators func NewCompositeIterator(first Iterator, second Iterator) Iterator { return &compositeIterator{first, second} } type compositeIterator struct { first Iterator second Iterator } func (this *compositeIterator) HasNext() bool { return this.first.HasNext() || this.second.HasNext() } func (this *compositeIterator) Next() interface{} { if this.first.HasNext() { return this.first.Next() } else if this.second.HasNext() { return this.second.Next() } panic("compositeIterator.Next: no next element") } // Combination iterator type combinedIterator struct { first Iterator second Iterator f Binop } func (this *combinedIterator) HasNext() bool { return this.first.HasNext() && this.second.HasNext() } func (this *combinedIterator) Next() interface{} { if this.HasNext() { return this.f(this.first.Next(), this.second.Next()) } panic("combinedIterator.Next: no next element") }
def _distance(self, other_loc): return np.sqrt(np.sum((self._loc - other_loc)**2))
<filename>src/main/java/com/imbus/bank/profilePictureModule/entity/ProfilePictureEntity.java package com.imbus.bank.profilePictureModule.entity; public class ProfilePictureEntity { private int userID; private String pictureUrl; }
<reponame>smooresni/batchwave<gh_stars>1-10 import functools def constrain_type(required_type: type, position=1): def wrapper(func): @functools.wraps(func) def set_value(*args, **kwargs): if not isinstance(args[position], required_type): raise TypeError('Value must be instance of type ' + str(required_type)) func(*args, **kwargs) return set_value return wrapper
/* * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_GC_G1_G1FULLGCMARKER_HPP #define SHARE_GC_G1_G1FULLGCMARKER_HPP #include "gc/g1/g1FullGCOopClosures.hpp" #include "gc/g1/g1RegionMarkStatsCache.hpp" #include "gc/shared/preservedMarks.hpp" #include "gc/shared/stringdedup/stringDedup.hpp" #include "gc/shared/taskqueue.hpp" #include "memory/iterator.hpp" #include "oops/markWord.hpp" #include "oops/oop.hpp" #include "runtime/timer.hpp" #include "utilities/chunkedList.hpp" #include "utilities/growableArray.hpp" #include "utilities/stack.hpp" typedef OverflowTaskQueue<oop, mtGC> OopQueue; typedef OverflowTaskQueue<ObjArrayTask, mtGC> ObjArrayTaskQueue; typedef GenericTaskQueueSet<OopQueue, mtGC> OopQueueSet; typedef GenericTaskQueueSet<ObjArrayTaskQueue, mtGC> ObjArrayTaskQueueSet; class G1CMBitMap; class G1FullCollector; class TaskTerminator; class G1FullGCMarker : public CHeapObj<mtGC> { G1FullCollector* _collector; uint _worker_id; // Backing mark bitmap G1CMBitMap* _bitmap; // Mark stack OopQueue _oop_stack; ObjArrayTaskQueue _objarray_stack; PreservedMarks* _preserved_stack; // Marking closures G1MarkAndPushClosure _mark_closure; G1VerifyOopClosure _verify_closure; G1FollowStackClosure _stack_closure; CLDToOopClosure _cld_closure; StringDedup::Requests _string_dedup_requests; G1RegionMarkStatsCache _mark_stats_cache; inline bool is_empty(); inline bool pop_object(oop& obj); inline bool pop_objarray(ObjArrayTask& array); inline void push_objarray(oop obj, size_t index); inline bool mark_object(oop obj); // Marking helpers inline void follow_object(oop obj); inline void follow_array(objArrayOop array); inline void follow_array_chunk(objArrayOop array, int index); public: G1FullGCMarker(G1FullCollector* collector, uint worker_id, PreservedMarks* preserved_stack, G1RegionMarkStats* mark_stats); ~G1FullGCMarker(); // Stack getters OopQueue* oop_stack() { return &_oop_stack; } ObjArrayTaskQueue* objarray_stack() { return &_objarray_stack; } PreservedMarks* preserved_stack() { return _preserved_stack; } // Marking entry points template <class T> inline void mark_and_push(T* p); inline void follow_klass(Klass* k); inline void follow_cld(ClassLoaderData* cld); inline void drain_stack(); void complete_marking(OopQueueSet* oop_stacks, ObjArrayTaskQueueSet* array_stacks, TaskTerminator* terminator); // Closure getters CLDToOopClosure* cld_closure() { return &_cld_closure; } G1MarkAndPushClosure* mark_closure() { return &_mark_closure; } G1FollowStackClosure* stack_closure() { return &_stack_closure; } // Flush live bytes to regions void flush_mark_stats_cache(); }; #endif // SHARE_GC_G1_G1FULLGCMARKER_HPP
<filename>src/components/pages/LoginPage/LoginForm.tsx import React from 'react'; import { SubmitHandler, useForm } from 'react-hook-form'; import { useHistory } from 'react-router-dom'; import { useSetRecoilState } from 'recoil'; import { Auth } from '../../../api'; import { Roles } from '../../../api/Auth'; import { auth } from '../../../state'; import { Input } from '../../common'; import { ILoginParams } from './loginTypes'; const LoginForm = ({ isMerge, codename, cleverId, }: ILoginParams): React.ReactElement => { const { errors, register, handleSubmit, clearErrors, setError } = useForm(); const setUser = useSetRecoilState(auth.user); const setToken = useSetRecoilState(auth.authToken); const { push } = useHistory(); const onSubmit: SubmitHandler<Auth.ILoginBody> = async ( data, ): Promise<void> => { try { let res: Auth.IAuthResponse; if (isMerge) { res = await Auth.mergeAccounts(data, cleverId as string); } else { res = await Auth.login(data); } setUser(res.user); setToken(res.token); clearErrors(); const userType = res.user.roleId === Roles.user ? 'student' : Roles[res.user.roleId]; push(`/dashboard/${userType}`); } catch (err) { console.log({ err }); let message: string; if (err.response?.data) { message = err.response.data.message; } else { message = 'An unknown error occurred. Please try again.'; } if (message === 'User not found') { setError('codename', { type: 'validate', message }); } else if (message === 'Invalid password') { setError('password', { type: 'validate', message }); } else { setError('form', { type: 'manual', message }); } } }; return ( <form className="auth-form" onSubmit={handleSubmit(onSubmit)}> <Input label="Codename" name="codename" register={register} id="login-codename" errors={errors} placeholder="Enter your codename" rules={{ required: 'Codename is required!', }} defaultValue={codename} /> <Input label="Password" name="password" register={register} id="login-password" errors={errors} type="password" placeholder="Enter your password" rules={{ required: 'Password is required!' }} /> <input className="submit" type="submit" value={isMerge ? 'Merge' : 'Log In'} onClick={() => clearErrors('form')} /> </form> ); }; export default LoginForm;
def parse_payload(self, payload:dict) -> dict: return { 'airline_code': payload['airline']['iata'], 'flight_number': payload['flight']['number'], 'flight_date': payload['flight_date'], 'flight_status': payload['flight_status'], 'departure_airport': payload['departure']['airport'].replace(',', '') if payload['departure']['airport'] is not None else '', 'arrival_airport': payload['arrival']['airport'].replace(',', '') if payload['arrival']['airport'] is not None else '', 'airline_name': payload['airline']['name'] }
package {{.PackageName}} import ( "strings" ) func (api {{.Name}}API) Delete(deleteObject {{.Name}}) error { objects, err := api.Get(deleteObject) if err != nil { return err } if api.Hooks.PreDelete != nil { if err = api.Hooks.PreDelete(objects); err != nil { if err == StopOperation { return nil } return err } } for _, obj := range objects { whereQueries, whereValues := api.getSetValues(&obj) if whereQueries == nil || whereValues == nil || len(whereQueries) <= 0 || len(whereValues) <= 0 { continue } for i := range whereQueries { whereQueries[i] = whereQueries[i] + " = ?" } _, err = api.DB.Exec("DELETE FROM {{.Name}} WHERE "+ strings.Join(whereQueries, " AND "), whereValues...) } if api.Hooks.PostDelete != nil { api.Hooks.PostDelete(objects) } return err } func (api {{.Name}}API) DeleteWhere(deleteQuery string, whereValues ...interface{}) error { objects, err := api.GetWhere(deleteQuery, whereValues...) if err != nil { return err } if api.Hooks.PreDelete != nil { if err = api.Hooks.PreDelete(objects); err != nil { return err } } for _, obj := range objects { whereQueries, whereValues := api.getSetValues(&obj) if whereQueries == nil || whereValues == nil || len(whereQueries) <= 0 || len(whereValues) <= 0 { continue } for i := range whereQueries { whereQueries[i] = whereQueries[i] + " = ?" } _, err = api.DB.Exec("DELETE FROM {{.Name}} WHERE "+ strings.Join(whereQueries, " AND "), whereValues...) } if api.Hooks.PostDelete != nil { api.Hooks.PostDelete(objects) } return err } func (api {{.Name}}API) DeleteAll() error { return api.DeleteWhere("") }
def build_all_images_for_lang(lang): if not args.git_checkout: if args.release != 'master': print( 'Cannot use --release without also enabling --git_checkout.\n') sys.exit(1) releases = [args.release] else: if args.release == 'all': releases = client_matrix.get_release_tags(lang) else: if args.release not in ['master' ] + client_matrix.get_release_tags(lang): jobset.message('SKIPPED', '%s for %s is not defined' % (args.release, lang), do_newline=True) return [] releases = [args.release] images = [] for release in releases: images += build_all_images_for_release(lang, release) jobset.message('SUCCESS', 'All docker images built for %s at %s.' % (lang, releases), do_newline=True) return images
// 16 bit colour - of last conversion. uint16_t Kelvin2RGB::RGB565() { uint16_t val = 0; val = uint8_t(_red * 32); val <<= 6; val |= uint8_t(_green * 64); val <<= 5; val |= uint8_t(_blue * 32); return val; }
// ChangeSvcCheckTimeperiod creates a new "CHANGE_SVC_CHECK_TIMEPERIOD" Nagios command. // // Changes the check timeperiod for a particular service to what is specified by the "check_timeperiod" option. // // The "check_timeperiod" option should be the short name of the timeperod that is to be used as the service check // timeperiod. // // The timeperiod must have been configured in Nagios before it was last (re)started. func ChangeSvcCheckTimeperiod( host_name string, service_description string, check_timeperiod string, ) *livestatus.Command { return livestatus.NewCommand( "CHANGE_SVC_CHECK_TIMEPERIOD", stringifyArg("host_name", "string", host_name), stringifyArg("service_description", "string", service_description), stringifyArg("check_timeperiod", "string", check_timeperiod), ) }
LAS VEGAS — The UFC is trying to get in on the sweet science in an official capacity. MMA’s leading organization has made a request with the Nevada Athletic Commission (NAC) to co-promote the huge Floyd Mayweather vs. Conor McGregor boxing match Aug. 26 in Las Vegas, per the commission’s upcoming meeting agenda. The NAC will vote on the addition of the UFC as co-promoter at its meeting Aug. 16. TGB Promotions, the lead promoter of boxing’s Premier Boxing Champions (PBC), is also requesting a program permit to co-promote Mayweather vs. McGregor. NAC executive director Bob Bennett told MMA Fighting that the UFC would not need a separate license to promote boxing in Nevada. The MMA organization would become an official co-promoter for the event in order to pay McGregor for the fight, Bennett said. UFC president Dana White said initially that the UFC won’t be in on the promotion officially for Mayweather vs. McGregor, only supporting it through social media and other mediums, like UFC Embedded. Mayweather Promotions was previously the only promoter listed for the fight. Showtime is the broadcast distributor in the United States. The UFC has had a major presence in the build up to the mega bout. White and the UFC public-relations staff were present at all the stops of the MayMac World Tour last month. McGregor, of course, is the UFC lightweight champion and the biggest star in mixed martial arts. The UFC is hosting McGregor’s media workout day Friday at the UFC Performance Institute, where McGregor has been training for Mayweather over the last three weeks. Also on the commission’s agenda for the Aug. 16 meeting is a vote on the application for McGregor’s boxing license. This will be McGregor’s first pro boxing match. Mayweather’s request for a license is listed, too. He is 40 years old and, per commission rule, any athlete over 38 years old must re-apply every time they book a fight. The NAC will select the referees and judges for Mayweather vs. McGregor on Aug. 16 and, in addition, vote on whether or not to allow the competitors to wear 8-ounce gloves, rather than the 10-ounce gloves the rules stipulate. In more of a formality, the agenda also lists the Mayweather Promotions request to move MayMac to T-Mobile Arena. The event was originally licensed for MGM Grand.
// Convert makes a best-effort at converting a value into a valid value func (object Object) Convert(value interface{}) interface{} { result := object.DefaultValue().(map[string]interface{}) valueAsMap := convert.MapOfInterface(value) for key, element := range object.Properties { if newValue, ok := valueAsMap[key]; ok { result[key] = element.Convert(newValue) } } return result }
package org.apache.commons.lang3; import java.io.PrintStream; public final class c { private static String a; private static final JavaVersion b; private static String c; private static String d; private static boolean e; private static boolean f; private static boolean g; private static boolean h; private static boolean i; private static boolean j; private static boolean k; private static boolean l; private static boolean m; private static boolean n; static { c("awt.toolkit"); c("file.encoding"); c("file.separator"); c("java.awt.fonts"); c("java.awt.graphicsenv"); c("java.awt.headless"); c("java.awt.printerjob"); c("java.class.path"); c("java.class.version"); c("java.compiler"); c("java.endorsed.dirs"); c("java.ext.dirs"); c("java.home"); c("java.io.tmpdir"); c("java.library.path"); c("java.runtime.name"); c("java.runtime.version"); c("java.specification.name"); c("java.specification.vendor"); String str = c("java.specification.version"); a = str; b = JavaVersion.get(str); c("java.util.prefs.PreferencesFactory"); c("java.vendor"); c("java.vendor.url"); c("java.version"); c("java.vm.info"); c("java.vm.name"); c("java.vm.specification.name"); c("java.vm.specification.vendor"); c("java.vm.specification.version"); c("java.vm.vendor"); c("java.vm.version"); c("line.separator"); c("os.arch"); c = c("os.name"); d = c("os.version"); c("path.separator"); if (c("user.country") == null) { c("user.region"); c("user.dir"); c("user.home"); c("user.language"); c("user.name"); c("user.timezone"); a("1.1"); a("1.2"); a("1.3"); a("1.4"); a("1.5"); a("1.6"); a("1.7"); e = b("AIX"); f = b("HP-UX"); g = b("Irix"); if ((!b("Linux")) && (!b("LINUX"))) break label522; } label522: for (boolean bool = true; ; bool = false) { h = bool; b("Mac"); i = b("Mac OS X"); j = b("FreeBSD"); k = b("OpenBSD"); l = b("NetBSD"); b("OS/2"); m = b("Solaris"); n = b("SunOS"); b("Windows"); a("Windows", "5.0"); a("Windows", "5.2"); a("Windows Server 2008", "6.1"); a("Windows 9", "4.0"); a("Windows 9", "4.1"); a("Windows", "4.9"); b("Windows NT"); a("Windows", "5.1"); a("Windows", "6.0"); a("Windows", "6.1"); return; c("user.country"); break; } } private static boolean a(String paramString) { String str = a; if (str == null) return false; return str.startsWith(paramString); } private static boolean a(String paramString1, String paramString2) { String str1 = c; String str2 = d; if ((str1 == null) || (str2 == null)); do return false; while ((!str1.startsWith(paramString1)) || (!str2.startsWith(paramString2))); return true; } public static boolean a(JavaVersion paramJavaVersion) { return b.atLeast(paramJavaVersion); } private static boolean b(String paramString) { String str = c; if (str == null) return false; return str.startsWith(paramString); } private static String c(String paramString) { try { String str = System.getProperty(paramString); return str; } catch (SecurityException localSecurityException) { System.err.println("Caught a SecurityException reading the system property '" + paramString + "'; the SystemUtils property value will default to null."); } return null; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: org.apache.commons.lang3.c * JD-Core Version: 0.6.0 */
Single Phase Convective Heat Transfer Passive Enhancement: Techniques, Mechanisms, Performance Comparisons and Applications In this keynote lecture an overview of single phase convective heat transfer passive enhancement techniques and their underlying mechanisms is provided. Then detailed analyses of the hydraulic and thermal performances of selected works conducted by the speaker’s group related to thermal boundary layer redevelopment, secondary flow generation and waviness are provided to demonstrate the effectiveness of these approaches. Finally, the application of these techniques for solving various practical cooling problems ranging for direct chip liquid cooling of servers to passive displacement cooling of buildings is discussed lic performance comparisons of the enhanced structures.
/** * This class illustrates the basic structure of a JUnit Test which needs to interact with a single Kafka * broker running in a docker container on the current machine. */ public class SimpleUnitTest { // --- Kafka Stuff -------------------------------------------------------------------------------------- private static Admin admin; private static KafkaProducer<String, String> producer; private static KafkaConsumer<String, String> consumer; private static final int defPartitions = 1; private static final short defReplication = 1; // --- Test Initialization ------------------------------------------------------------------------------ @BeforeAll static void initializeClients() { admin = TestUtils.getAdminClient(); String bootstrap = TestUtils.getBootstrapServers(); producer = new KafkaProducer<>( Map.of( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap, ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString() ), new StringSerializer(), new StringSerializer() ); consumer = new KafkaConsumer<>( Map.of( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap, ConsumerConfig.GROUP_ID_CONFIG, "tc-" + UUID.randomUUID(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest" ), new StringDeserializer(), new StringDeserializer() ); } // --- Test Cases --------------------------------------------------------------------------------------- /* * Simplistic happy-path test to confirm we can start up the kafka container, create a topic, publish a * record to it, and then consume it. This test does not use KStreams, just plain Producer/Consumers */ @Test void testHelloWorld() throws Exception { assertKafkaClusterReady(); assertAdminClientReady(); final String topicName = "SimpleTest_testHelloWorld"; Collection<NewTopic> topics = List.of( new NewTopic(topicName, defPartitions, defReplication) ); admin.createTopics(topics) .all() .get(TIMEOUT, TimeUnit.SECONDS); consumer.subscribe(List.of(topicName)); int recordKey = 0; int recordVal = 0; producer.send(new ProducerRecord<>(topicName, "key-"+recordKey++, "Hello Kafka ("+recordVal+++")")).get(); ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(TIMEOUT)); assertTrue( StreamSupport .stream(records.spliterator(), false) .anyMatch(e -> e.key().equals("key-0")) ); consumer.unsubscribe(); admin.deleteTopics(List.of(topicName)); } }
<filename>src/JavaToC/DirectFourierTransform.java package JavaToC; import java.io.File; import javax.swing.JFileChooser; public class DirectFourierTransform { public static boolean useGPU = true; public static native double[] direct(double[] input, int rowsFirst, int nRows, int nCols); /** * * @param input * @param rowsFirst * @param outputType 0: sqrt(re^2+im^2) <br>1: re<br>2: im * @return */ public static double[][][] direct(double[][] input, int rowsFirst, int outputType) { int nCols = input.length; int nRows = input[0].length; double[] oneD = new double[input.length * input[0].length]; int idx = 0; for(int x = 0; x < nCols; x++) { for(int y = 0; y < nRows; y++) { idx = y * nCols + x; oneD[idx] = input[x][y]; } } double[][][] returnVals = null; if(useGPU) { oneD = direct(oneD, rowsFirst, nRows, nCols); int len = oneD.length/2; double[] ft_re = new double[len]; double[] ft_im = new double[len]; for(int i = 0; i < ft_re.length; i++) { ft_re[i] = oneD[i]; ft_im[i] = oneD[i+len]; } returnVals = new double[2][nCols][nRows]; for(int x = 0; x < nCols; x++) { for(int y = 0; y < nRows; y++) { idx = y * nCols + x; returnVals[0][x][y] = ft_re[idx]; returnVals[1][x][y] = ft_im[idx]; } } } else { returnVals = ftRows2(input); returnVals = ftCols2(returnVals); } return returnVals; } static { if(useGPU) { String prop = "java.library.path"; String curPath = System.getProperty(prop); String newPath = "\"D:\\$research\\current\\eclipse projects\\My Packages\\JavaToC\""; if(!curPath.contains(newPath)) { System.out.println(prop + " before setting to: " + newPath + ": " + System.getProperty(prop)); System.setProperty(prop, curPath + ";" + newPath); System.out.println(System.getProperty(prop)); System.out.println(prop + " after setting to: " + newPath + ": " + System.getProperty(prop)); } String fileToLoad = "DirectFourierTransform"; System.loadLibrary(fileToLoad); if(!new File(fileToLoad + ".dll").exists()) { File loc = new File("."); System.out.println("Current file location: " + loc.getAbsolutePath()); JFileChooser chooser = new JFileChooser(loc); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = chooser.showOpenDialog(null); switch(returnVal) { case JFileChooser.APPROVE_OPTION: fileToLoad = chooser.getSelectedFile().getName(); fileToLoad = fileToLoad.substring(0, fileToLoad.lastIndexOf(".")); System.setProperty(prop, curPath + ";\"" + chooser.getSelectedFile().getParent() + "\""); System.out.println(prop + " after setting to: " + newPath + ": " + System.getProperty(prop)); break; } } System.loadLibrary(fileToLoad); } //cuInit(); } public static void main(String[] args) { // int outputType = 2; double[][] arr = new double[25][25]; for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[i].length; j++) { arr[i][j] = Math.random()-0.5; } } double[][][] newArr = DirectFourierTransform.direct(arr, 0, 0); // newArr = DirectFourierTransform.direct(arr, 0, 1); // newArr = DirectFourierTransform.direct(arr, 0, 0); // System.out.println(StringConverter.arrayToTabString(arr[0])); // arr = ftRows(arr, outputType); // System.out.println(StringConverter.arrayToTabString(arr[0])); // arr = ftCols(arr, outputType); // System.out.println(StringConverter.arrayToTabString(arr[0])); System.out.println("Original\tNew"); for(int i = 0; i < newArr.length; i++) { System.out.print(arr[i][0] + "\t"); } System.out.println(); for(int i = 0; i < newArr.length; i++) { System.out.print(newArr[0][i][0] + "\t"); } } private static double[][][] ftCols2(double[][] inputData) { double[][][] byCols = new double[2][inputData.length][inputData[0].length]; byCols[0] = inputData; return ftCols2(byCols); } private static double[][][] ftRows2(double[][] inputData) { double[][][] byRows = new double[2][inputData.length][inputData[0].length]; byRows[0] = inputData; return ftRows2(byRows); } private static double[][][] ftCols2(double[][][] inputData) { double[][][] byCols = new double[2][inputData[0].length][inputData[0][0].length]; int nRows = byCols[0][0].length; int nCols = byCols[0].length; for(int ky = 0; ky < nRows; ky++) { for(int kx = 0; kx < nCols; kx++) { double sumReal = 0; double sumImag = 0; for(int t = 0; t < nRows; t++) { double arg = 2*Math.PI * t * kx / nRows; sumReal += inputData[0][t][ky] * Math.cos(arg) + inputData[1][t][ky] * Math.sin(arg); sumImag += -inputData[0][t][ky] * Math.sin(arg) + inputData[1][t][ky] * Math.cos(arg); } byCols[0][kx][ky] = sumReal; byCols[1][kx][ky] = sumImag; } } return byCols; } private static double[][][] ftRows2(double[][][] inputData) { double[][][] byRows = new double[2][inputData[0].length][inputData[0][0].length]; int nCols = byRows[0].length; int nRows = byRows[0][0].length; for(int kx = 0; kx < nRows; kx++) { for(int ky = 0; ky < nCols; ky++) { double sumReal = 0; double sumImag = 0; for(int t = 0; t < nCols; t++) { double arg = 2*Math.PI * t * kx / nCols; sumReal += inputData[0][kx][t] * Math.cos(arg) + inputData[1][kx][t] * Math.sin(arg); sumImag += -inputData[0][kx][t] * Math.sin(arg) + inputData[1][kx][t] * Math.cos(arg); } byRows[0][kx][ky] = sumReal; byRows[1][kx][ky] = sumImag; } } return byRows; } private static double[][] ftCols(double[][] inputData, int outputType) { double[][] byCols = new double[inputData.length][inputData[0].length]; int nRows = byCols[0].length; int nCols = byCols.length; for(int ky = 0; ky < nRows; ky++) { for(int kx = 0; kx < nCols; kx++) { double sumReal = 0; double sumImag = 0; for(int t = 0; t < nCols; t++) { sumReal += inputData[t][ky] * Math.cos(2*Math.PI * t * kx / nCols); sumImag += -inputData[t][ky] * Math.sin(2*Math.PI * t * kx / nCols); } switch(outputType) { case 0: byCols[kx][ky] = Math.sqrt(Math.pow(sumReal, 2) + Math.pow(sumImag, 2)); break; case 1: byCols[kx][ky] = sumReal; break; case 2: byCols[kx][ky] = sumImag; break; } } } return byCols; } private static double[][] ftRows(double[][] exptData, int outputType) { double[][] byRows = new double[exptData.length][exptData[0].length]; int nCols = byRows.length; int nRows = byRows[0].length; for(int kx = 0; kx < nCols; kx++) { for(int ky = 0; ky < nRows; ky++) { double sumReal = 0; double sumImag = 0; for(int t = 0; t < nRows; t++) { sumReal += exptData[kx][t] * Math.cos(2*Math.PI * t * ky / nRows); sumImag += -exptData[kx][t] * Math.sin(2*Math.PI * t * ky / nRows); } switch(outputType) { case 0: byRows[kx][ky] = Math.sqrt(Math.pow(sumReal, 2) + Math.pow(sumImag, 2)); break; case 1: byRows[kx][ky] = sumReal; break; case 2: byRows[kx][ky] = sumImag; break; } } } return byRows; } }
def aligntime(dct, channels=None, mode="truncate", value=0): if channels is not None: err = 0 for item in channels: if item not in dct: err = 1 print(f"Channel {item} not found in `dct`.") if err: raise ValueError( "`dct` does not contain all requested channels. See above." ) parms = channels else: parms = list(dct.keys()) t, d, isarr = _get_timedata(dct[parms[0]]) dt = (t[-1] - t[0]) / (len(t) - 1) if mode == "truncate": tmin = t[0] tmax = t[-1] for key in parms: t, d, isarr = _get_timedata(dct[key]) if t[0] > tmax or t[-1] < tmin: raise ValueError("not all inputs overlap in time.") if not np.allclose(np.diff(t), dt): raise ValueError(f"not all time steps in {key} match {dt}") tmin = max(tmin, t[0]) tmax = min(tmax, t[-1]) n = int(np.ceil((tmax - tmin) / dt)) if (dt * n + tmin) < (tmax + dt / 2): n += 1 pv = np.arange(n) dctout = {} dctout["t"] = pv * dt + tmin start = tmin + dt / 2 for key in parms: t, d, isarr = _get_timedata(dct[key]) i = _get_prev_index(t, start) dctout[key] = d[i + pv] else: tmin = t[0] tmax = t[-1] for key in parms: t, d, isarr = _get_timedata(dct[key]) if not np.allclose(np.diff(t), dt): raise ValueError(f"not all time steps in {key} match {dt}") tmin = min(tmin, t[0]) tmax = max(tmax, t[-1]) n = int(np.ceil((tmax - tmin) / dt)) if (dt * n + tmin) < (tmax + dt / 2): n += 1 dctout = {} t = dctout["t"] = np.arange(n) * dt + tmin for key in parms: old_t, old_d, isarr = _get_timedata(dct[key]) i = _get_prev_index(t, old_t[0] + dt / 2) new_d = np.empty(n) new_d[:] = value old_n = len(old_t) if i + old_n > n: old_n = n - i new_d[i : i + old_n] = old_d[:old_n] dctout[key] = new_d return dctout
<reponame>adamb70/posthog<gh_stars>1-10 import { useValues } from 'kea' import { featureFlagLogic } from 'lib/logic/featureFlagLogic' import React from 'react' import imgEmptyLineGraph from 'public/empty-line-graph.svg' import imgEmptyLineGraphDark from 'public/empty-line-graph-dark.svg' import { QuestionCircleOutlined } from '@ant-design/icons' export function LineGraphEmptyState({ color }: { color: string }): JSX.Element { const { featureFlags } = useValues(featureFlagLogic) return ( <> {!featureFlags['1694-dashboards'] && ( <p style={{ textAlign: 'center', paddingTop: '4rem' }}> We couldn't find any matching events. Try changing dates or pick another action or event. </p> )} {featureFlags['1694-dashboards'] && ( <div className="text-center" style={{ height: '100%' }}> <img src={color === 'white' ? imgEmptyLineGraphDark : imgEmptyLineGraph} alt="" style={{ maxHeight: '100%', maxWidth: '80%', opacity: 0.5 }} /> <div style={{ textAlign: 'center', fontWeight: 'bold', marginTop: 16 }}> Seems like there's no data to show this graph yet{' '} <a target="_blank" href="https://posthog.com/docs/features/trends" style={{ color: color === 'white' ? 'rgba(0, 0, 0, 0.85)' : 'white' }} > <QuestionCircleOutlined /> </a> </div> </div> )} </> ) }
# -*- coding: utf-8 -*- # # Copyright 2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np from .atmophere import vpd_calc, psychrometric_gamma, specific_heat_cp, es_calc, ea_calc, delta_calc, rho_cp_dry, \ rho_cp_moist from .radiation import longwave_downwelling, available_energy __author__ = "<NAME> <<EMAIL>>" __version__ = "0.1.3" __date__ = "October 2018" """ """ def canopy_conductance(canopy_temperature, air_temperature, relative_humidity, atmospheric_pressure, available_energy, aerodynamic_resistance): """ Function to calculate the canopy conductance from micrometeorological parameters Berni et al. (2009) Input: - canopy_temperature: temperature of the canopy [Celsius] - air_temperature: temperature of the air [Celsius] - relative_humidity: relative humidity [%] - atmospheric_pressure: atmospheric pressure [Pa] - available_energy: net radiation or available energy at the canopy [W/m2] - aerodynamic_resistance: aerodynamic resistance of the canopy [s/m] Output: - canopy_conductance: canopy conductance [mm/s] Parameters ---------- canopy_temperature air_temperature relative_humidity atmospheric_pressure available_energy aerodynamic_resistance Returns ------- Union[array, float]: canopy conducntace [mm/s] """ gam = psychrometric_gamma(air_temperature, relative_humidity, atmospheric_pressure) pCpp = rho_cp_moist(air_temperature, relative_humidity, atmospheric_pressure) tc_ta = canopy_temperature - air_temperature conductance = 1000.0 / ( aerodynamic_resistance * (es_calc(canopy_temperature) - (es_calc(air_temperature) - ea_calc(air_temperature, relative_humidity))) / ( gam * (aerodynamic_resistance * available_energy / pCpp - tc_ta)) - aerodynamic_resistance) return conductance def canopy_conductance_2(canopy_temperature, air_temperature, relative_humidity, atmospheric_pressure, available_energy, aerodynamic_resistance): """ Function to calculate the canopy conductance from micrometeorological parameters Berni et al. (2009) Input: - canopy_temperature: temperature of the canopy [Celsius] - air_temperature: temperature of the air [Celsius] - relative_humidity: relative humidity [%] - atmospheric_pressure: atmospheric pressure [Pa] - available_energy: net radiation or available energy at the canopy [W/m2] - aerodynamic_resistance: aerodynamic resistance of the canopy [s/m] Output: - canopy_conductance: canopy conductance [mm/s] Parameters ---------- canopy_temperature air_temperature relative_humidity atmospheric_pressure available_energy aerodynamic_resistance Returns ------- Union[array, float]: canopy conducntace [mm/s] """ rho = atmospheric_pressure / (287.07 * (air_temperature + 273.15)) rho_cp = (rho * (1002.5 + 275e-6 * np.power(air_temperature + 273.15 - 200.0, 2))) le = (available_energy - sensible_heat_flux_2(air_temperature, relative_humidity, atmospheric_pressure, canopy_temperature, aerodynamic_resistance)) gam = psychrometric_gamma(air_temperature, relative_humidity, atmospheric_pressure) gam_le = (gam * le) #gam_le[gam_le < 0.01] = 0.01 rc = rho_cp * ( es_calc(canopy_temperature) - ea_calc(air_temperature, relative_humidity)) / gam_le - aerodynamic_resistance return 1000.0 / rc def sensible_heat_flux_2(air_temperature, relative_humidity, atmospheric_pressure, canopy_temperature, aerodynamic_resistance): rho = atmospheric_pressure / (287.07 * (air_temperature + 273.15)) rho_cp = (rho * (1002.5 + 275e-6 * np.power(air_temperature + 273.15 - 200.0, 2))) aerodynamic_resistance[aerodynamic_resistance < 0.01] = 0.01 tc_ta = canopy_temperature - air_temperature return rho_cp * tc_ta / aerodynamic_resistance def sensible_heat_flux(air_temperature, relative_humidity, atmospheric_pressure, canopy_temperature, aerodynamic_resistance): pCpp = rho_cp_moist(air_temperature, relative_humidity, atmospheric_pressure) tc_ta = canopy_temperature - air_temperature return pCpp * tc_ta / aerodynamic_resistance def latent_heat_flux(air_temperature, relative_humidity, atmospheric_pressure, canopy_temperature, aerodynamic_resistance, canopy_resistance): pCpp = rho_cp_moist(air_temperature, relative_humidity, atmospheric_pressure) es_canopy = es_calc(canopy_temperature) e_air = ea_calc(air_temperature, relative_humidity) gam = psychrometric_gamma(air_temperature, relative_humidity, atmospheric_pressure) return pCpp * (es_canopy - e_air) / (gam * (aerodynamic_resistance + canopy_resistance)) def canopy_temperature_sim(shortwave, air_temperature, relative_humidity, atmospheric_pressure, gc, aerodynamic_resistance, albedo=0.23, longwave=None, emissivity=0.98): """ Simulates the canopy temperature for a given canopy conductance and micro-meteorological parameters Berni et al. (2009) Parameters ---------- shortwave: Union[array, float] Downwelling shortwave radiation [W/m2] albedo: Union[array, float] Canopy albedo, default 0.23 [0.0-1.0] air_temperature: Union[array, float] Air temperature [Celsius] relative_humidity: Union[array, float] Relative humidity [%] atmospheric_pressure: Union[array, float] Atmospheric pressure [Pa] gc: Union[array, float] Canopy conductance [mm/s] aerodynamic_resistance: Union[array, float] Aerodynamic resistance [s/m] longwave: Union[array, float] Downwelling longwave radiation [W/m2]. If not provider will be calculated using air temperature and humidity assuming clear skies. emissivity: Union[array, float] Canopy emissivity. Default 0.98 Returns ------- Union[array, float]: simulated canopy temperature [Celsius] """ # Start with arbitrary value canopy_temperature = air_temperature + 3.0 gam = psychrometric_gamma(air_temperature, relative_humidity, atmospheric_pressure) delt = delta_calc(air_temperature) pCpp = rho_cp_moist(air_temperature, relative_humidity, atmospheric_pressure) vpd = vpd_calc(air_temperature, relative_humidity) canopy_resistance = 1000.0 / gc # If longwave radiation is not provided we calculate it from using the model and defaults for clear skies if longwave is None: longwave = longwave_downwelling(air_temperature, relative_humidity) # Iterate for implicit canopy temperature for i in range(5): rn = available_energy(shortwave, albedo, longwave, canopy_temperature, emissivity) tc_ta = (aerodynamic_resistance * rn * gam * (1 + canopy_resistance / aerodynamic_resistance) / pCpp - vpd) / ( delt + gam * (1 + canopy_resistance / aerodynamic_resistance)) canopy_temperature = tc_ta + air_temperature return canopy_temperature
/* Initialize the current state to the starting position of the * current puzzle, and reset the macro array and the stack. */ void initgamestate(int usemoves) { int i; memcpy(state.map, state.game->map, sizeof state.map); state.player = state.game->start; initmovelist(&state.undo); if (!state.game->moveanswer.count) copymovelist(&state.redo, &state.game->pushanswer); else if (!state.game->pushanswer.count || usemoves) copymovelist(&state.redo, &state.game->moveanswer); else copymovelist(&state.redo, &state.game->pushanswer); state.movecount = 0; state.pushcount = 0; state.storecount = state.game->storecount; recording = FALSE; for (i = 0 ; i < (int)(sizeof macros / sizeof *macros) ; ++i) if (macros[i].count) macros[i].count = 0; }
#include "stdafx.h" #include "accelerators.h" #include "language.h" ACCEL accel[] = { FNOINVERT|FVIRTKEY, VK_SPACE, KEY_PLAYPAUSE, FNOINVERT|FVIRTKEY, 'V', KEY_STOP, FNOINVERT|FVIRTKEY, VK_LEFT, KEY_REWINDBACK, FNOINVERT|FVIRTKEY, VK_RIGHT, KEY_REWINDFORWARD, FNOINVERT|FVIRTKEY, VK_UP, KEY_VOLUMEUP, FNOINVERT|FVIRTKEY, VK_DOWN, KEY_VOLUMEDOWN, FNOINVERT|FVIRTKEY|FALT, VK_RETURN, KEY_GOFULLSCREEN, FNOINVERT|FVIRTKEY, VK_ESCAPE, KEY_GOWINDOWED, FNOINVERT|FVIRTKEY|FALT, VK_F4, KEY_EXIT, FNOINVERT|FVIRTKEY, 'P', KEY_PANSCAN, FNOINVERT|FVIRTKEY, 'Z', KEY_PREVMOVIE, FNOINVERT|FVIRTKEY, 'X', KEY_NEXTMOVIE, FNOINVERT|FVIRTKEY, 'S', KEY_SUBTITLES, FNOINVERT|FVIRTKEY|FCONTROL, 'O', KEY_OPENMOVIE, FNOINVERT|FVIRTKEY|FSHIFT, 'O', KEY_OPENSUBTITLES, FNOINVERT|FVIRTKEY|FCONTROL, 'P', KEY_OPTIONS, FNOINVERT|FVIRTKEY|FSHIFT, 'P', KEY_MOVIEPROP, FNOINVERT|FVIRTKEY, 'L', KEY_PLAYLIST, FNOINVERT|FVIRTKEY|FCONTROL, 'O', KEY_PLSOPEN, FNOINVERT|FVIRTKEY|FCONTROL, 'S', KEY_PLSSAVE, FNOINVERT|FVIRTKEY|FCONTROL, 'C', KEY_PLSCLEAR, FNOINVERT|FVIRTKEY|FCONTROL, 'A', KEY_PLSADDFILES, FNOINVERT|FVIRTKEY, VK_DELETE, KEY_PLSDELETE, FNOINVERT|FVIRTKEY, VK_ESCAPE, KEY_PLSCLOSE, FNOINVERT|FVIRTKEY, VK_RETURN, KEY_PLSPLAY }; char *GetKeyName( int keyId ) { int numAccel = sizeof(accel) / sizeof(ACCEL); for ( int i=0; i<numAccel && keyId!=accel[i].cmd; i++ ) ; if ( i==numAccel ) return NULL; static char szkey[64]; *szkey = 0; int flags = accel[i].fVirt&(FSHIFT|FCONTROL|FALT); while ( flags ) { int f=0; if ( flags&FSHIFT ) f=FSHIFT; else if ( flags&FCONTROL ) f=FCONTROL; else if ( flags&FALT ) f=FALT; else break; sprintf( szkey+strlen(szkey), "%s + ", transl(f, TRANSL_KEYS) ); flags &= ~f; } char *psz = transl( accel[i].key, TRANSL_KEYS ); if ( !psz || !*psz ) { char szAccelerator[16]; int map = (accel[i].fVirt&FVIRTKEY)?MapVirtualKey(accel[i].key, 0):accel[i].key; GetKeyNameText( map<<16, szAccelerator, 16 ); strcpy( szkey+strlen(szkey), szAccelerator ); } else strcpy( szkey+strlen(szkey), psz ); return szkey; } int GetKeysCount() { return (sizeof(accel)/sizeof(ACCEL)); }
Businesses of various sizes are extremely worried about information security. On a daily basis, we hear news of banks and financial institutions losing customer records, confidential information and money due to cyberattacks. Cyberattacks have increased exponentially over the last 5 years, and attack methods are becoming more sophisticated each day. On average, enterprises take about 100 days to identify an attack. It takes even more time to investigate, plug the gaps and prevent similar incidents. The goal of my recent Journal article is to help enterprises and security leaders realign the strategy of their information security teams by empowering the chief information officer (CIO) and the chief information security officer (CISO). Effective strategies by information security drivers, such as the CIO and CISO, can fine-tune information security and the compliance needs of an organization. Many industries have invested heavily in order to meet regulatory requirements, but being compliant and being secure are 2 different things. Many compliant enterprises have been breached. Information security needs to be a priority at the board level. CEOs should take active roles in promoting information security, as most valuable information is stored electronically, all systems and databases are online, and mobile transactions occur every minute. CIOs’ and CISOs’ priority is to identify where sensitive information resides and how can it be protected effectively at the lowest possible cost. The security team, guided by the CISO, should approach problems in a consulting mode to solve security-related challenges in the best way for the business. Outsourcing security operations is still one of the easiest options to reduce cost and reduce risk. These decisions should always be undertaken consciously, evaluating the risk and fallback options. Information security teams are the walls of every enterprise. An empowered CIO and CISO can create a cost effective, consistent security culture across the enterprise with the right strategies. Read Devassy Jose Tharakan’s recent Journal article: “Protecting Information—Practical Strategies for CIOs and CISOs,” ISACA Journal, volume 3, 2016.
/** * Starts listening to location changes. Does nothing if is already * listening. */ public void start() { if (isWorking) return; Log.d("LocationFinder", "started"); List<String> providers = manager.getAllProviders(); for (String provider : providers) { if (manager.isProviderEnabled(provider)) { isWorking = true; manager.requestLocationUpdates(provider, 0, 0, listener); } } currentBestLocation = manager.getLastKnownLocation(manager.getBestProvider(new Criteria(), true)); }
// removePtrIfExists so the underlying type can be exposed. This is helpful // when they want to change the value in a loop for example. func removePtrIfExists(reflectOfV reflect.Value) reflect.Value { switch reflectOfV.Kind() { case reflect.Ptr: reflectOfV = reflectOfV.Elem() } return reflectOfV }
#ifndef ADV_DB_STORE_EDGES #define ADV_DB_STORE_EDGES #include "store.h" #include "types.h" /* EDGE PAGE header edge item(s) EDGE ITEM TOTAL SIZE: 24 bytes node_id (8): end node id of this edge type (4): type of the edge wgt (4): weight of the edge kv (8): pointer to key/values of edge */ edge_p edges_add(struct store *edges, edge_p e_old, node_p start, node_p end); edge_p edges_remove(struct store *edges, edge_p e_old, node_p start, node_p end); #endif
/** * Render list of libraries used */ public class OpenSourceReferenceList extends Control { private static final String PROPERTY_LINK = ".link.\\d$"; private static final Pattern linkPattern = Pattern.compile(PROPERTY_LINK); private final List<Item> items = new ArrayList<>(); public OpenSourceReferenceList(Properties openSourceProperties) { parseItems(openSourceProperties); getStyleClass().add("open-source-reference-list"); } private void parseItems(Properties licenseProperties) { Item item = null; Comparator<String> comparator = (s, t1) -> s.compareTo(t1); SortedSet<String> propertyNames = new TreeSet<>(comparator); propertyNames.addAll(licenseProperties.stringPropertyNames()); for (String propertyName : propertyNames) { String propertyValue = licenseProperties.getProperty(propertyName); Matcher m = linkPattern.matcher(propertyName); if (m.find()) { item.licenseLinks.add(propertyValue); } else { if (item != null) { items.add(item); } item = new Item(propertyName); if (propertyValue.contains("/")) {//dual licenses ex: GPL/CC BY 4.0 String[] licenses = propertyValue.split("/"); for (String license : licenses) { item.licenseNames.add(license); } } else { item.licenseNames.add(propertyValue); } } } //add last item constructed (since we're otherwise only adding the previous item when the following one is found) if (item != null) { items.add(item); } } @Override public Skin<?> createDefaultSkin() { return new OpenSourceReferenceListSkin(this); } @Override public String getUserAgentStylesheet() { return OpenSourceReferenceList.class.getResource("opensourcereferencelist.css").toExternalForm(); } public List<Item> getItems() { return items; } protected class Item { private List<String> licenseLinks = new ArrayList<>(); private List<String> licenseNames = new ArrayList<>(); private final String artifact; public Item(String artifact) { this.artifact = artifact; } public List<String> getLicenseLinks() { return licenseLinks; } public List<String> getLicenseNames() { return licenseNames; } public String getArtifact() { return artifact; } } }
We report an adolescent girl who had left-sided neurogenic thoracic outlet syndrome (TOS) due to impingement of the scalenus anterior muscle with bilateral changes on nerve conduction studies and responded well to surgical decompression. A 13-year-old Caucasian girl presented with intermittent pain, swelling, erythema, tingling and numbness of the palmar aspect of her left hand. Nerve conduction studies revealed bilateral ulnar sensory and motor conduction abnormalities, suggesting early compressive neuropathy in the asymptomatic arm as well. She underwent surgical exploration when it was noted that the scalenus anterior itself was impinging on the brachial plexus. She had a good clinical response to scalenectomy. The diagnosis of neurogenic TOS remains difficult as no single test has been accepted as a gold standard. But, once diagnosed using clinical symptoms, nerve conduction studies, electromyography and radiological investigations, it is a treatable condition with good prognosis.
from abc import ABC, abstractmethod class Environ(ABC): """ Environ """ def get(self, key, default=None): """ Get str value @return: str @rtype: str """ raise NotImplementedError("Not implemented error") def get_str(self, key, default=None): """ Get str value @return: str @rtype: str """ raise NotImplementedError("Not implemented error") def get_int(self, key, default=None): """ Get int value @return: int @rtype: int """ raise NotImplementedError("Not implemented error") def get_float(self, key, default=None): """ Get int value @return: int @rtype: int """ raise NotImplementedError("Not implemented error") def get_list(self, key, default=list()): """ Get list value @return: list @rtype: list """ raise NotImplementedError("Not implemented error") def get_list(self, key, default=tuple()): """ Get tuple value @return: tuple @rtype: tuple """ raise NotImplementedError("Not implemented error")
/** * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/). * * Copyright 2019-2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_INCLUDE_COMMON_UTILS_CSE_H_ #define MINDSPORE_CCSRC_INCLUDE_COMMON_UTILS_CSE_H_ #include <vector> #include <map> #include "utils/hash_map.h" #include "ir/anf.h" #include "ir/manager.h" #include "include/common/visible.h" namespace mindspore { /* namespace to support opt */ namespace opt { // Common subexpression elimination. class COMMON_EXPORT CSE { public: CSE() = default; virtual ~CSE() = default; virtual bool CheckReplace(const AnfNodePtr &main, const AnfNodePtr &node); virtual bool Cse(const FuncGraphPtr root, const FuncGraphManagerPtr manager); bool HasHiddenSideEffect(const AnfNodePtr &node); protected: void Init(); bool BuildOrderGroupForOneGraph(const FuncGraphPtr &fg); void DoReplace(const FuncGraphManagerPtr &manager); AnfNodePtr GetReplicatedNode(const AnfNodePtr &node) const; private: bool BuildOrderGroupAndDoReplace(const FuncGraphManagerPtr manager); bool CalReplaceNodes(const std::vector<std::size_t> &order_group, mindspore::HashMap<std::size_t, std::vector<AnfNodePtr>> *groups); void AddReplicatedNode(const AnfNodePtr &node, const AnfNodePtr &main); bool IsHiddenSideEffectCall(const AnfNodePtr &node); // Record func graphs having hidden_side_effect cnode. HashSet<FuncGraphPtr> hidden_side_effect_func_graphs_; // Record all node need to be replaced OrderedMap<AnfNodePtr, AnfNodePtr> replicated_nodes_; }; COMMON_EXPORT BasePtr AbsOf(const AnfNodePtr &node, bool ignore_fg_abs_tracking_id = false); } // namespace opt } // namespace mindspore #endif // MINDSPORE_CCSRC_INCLUDE_COMMON_UTILS_CSE_H_
def compute_cross_entropy_loss(labels, logits, label_mask_value: Optional[int] = -1): neg_log_probs = tf.nest.map_structure( lambda x, y: compute_neg_log_probs(x, y, label_mask_value), labels, logits) return tf.reduce_mean(sum(tf.nest.flatten(neg_log_probs)), axis=0)
<gh_stars>0 import { StepType } from '../../../core/entities/StepType' import { PollDetailComponentProvider } from './PollDetailComponentProvider' export class CompoundPollDetailComponentProvider<A, B> implements PollDetailComponentProvider<A & B> { private lhs: PollDetailComponentProvider<A> private rhs: PollDetailComponentProvider<B> constructor( lhs: PollDetailComponentProvider<A>, rhs: PollDetailComponentProvider<B>, ) { this.lhs = lhs this.rhs = rhs } getStepComponent(step: number): JSX.Element { const { provider, relativeStep } = this.getRelativeData(step) return provider.getStepComponent(relativeStep) } getNumberOfSteps(): number { return this.lhs.getNumberOfSteps() + this.rhs.getNumberOfSteps() } getStepType(step: number): StepType { const { provider, relativeStep } = this.getRelativeData(step) return provider.getStepType(relativeStep) } isDataComplete(step: number): boolean { const { provider, relativeStep } = this.getRelativeData(step) return provider.isDataComplete(relativeStep) } getResult(): A & B { const lhsResult = this.lhs.getResult() const rhsResult = this.rhs.getResult() return { ...lhsResult, ...rhsResult, } } private getRelativeData( step: number, ): { provider: PollDetailComponentProvider<Partial<A>> relativeStep: number } { if (step < this.lhs.getNumberOfSteps()) { return { provider: this.lhs, relativeStep: step } } else { return { provider: this.rhs, relativeStep: step - this.lhs.getNumberOfSteps(), } } } }
To understand Californians’ favorite methods for ingesting cannabis, Joshua Hoffman likens it to the different ways of experiencing music. Think of smoking cannabis flowers like attending a live concert, he said. The second most popular method — vape pens — is like listening to a CD on high-end speakers. “The flower is the musician with the instrument,” said Hoffman, who works for SPARC and Peace in Medicine dispensaries in Sonoma County and San Francisco. “The flower is getting the full interpretation of what that plant was doing. In some ways, a CD is crisper than a record or live music, and, in other ways, it leaves things out.” A new study based on data gathered from dispensaries across the state attempts to capture how California medical marijuana users spend money at legal pot shops — an estimated $2.68 billion by the end of the year, according to Boulder-based research firm BDS Analytics. The most popular strain across the state is called Blue Dream. To continue the musical analogy, Blue Dream could be described as a mainstream band with music that manages to both bring you to your feet and put your mind at ease. Several Sonoma County dispensary workers said Blue Dream’s popularity could be attributed to the fact it’s widely available. “It’s such a balanced blend,” said bud tender Joanna Rojas, from behind the counter at Santa Rosa’s OrganiCann dispensary on Todd Road. California is a pot behemoth where more than one-third of all legal purchases of marijuana in the United States take place, according to the report. There are an estimated 1,100 dispensaries and 2,000 delivery services in the state, according to Greg Shoenfeld, vice president of operations for BDS Analytics. Sales data shows California already looks like states where recreational use and production is underway because of the variety of products — particularly concentrates — available on the shelves, according to Shoenfeld. States with medical marijuana and no recreational sales typically have less variety, he said. Recreational use of marijuana for adults was legalized in California last year when voters passed Proposition 64. But there is no system yet for commercial production, and the state is expected to begin licensing commercial cannabis businesses in 2018. Special report: Cannabis and the environment. Compared to California, where about 34 percent of the nation’s legal marijuana is sold, Colorado, Washington and Oregon combined represent 41 percent of all legal sales, including recreational marijuana. “It’s probably indicative of how easy it’s been to get a (medical marijuana) recommendation in California,” Shoenfeld said. “It’s also due to the fact that with such greater scale of market there, you have a number of brands that have come to market even in the early days.” When Colorado began sales of recreational cannabis in 2014, dried flowers represented 65 percent of all sales, and concentrates took about 13 percent. The popularity of concentrates has risen since then, to about 27 percent, a rise that follows improvements in manufacturing methods, according to Shoenfeld. In California, more than half of sales, 55 percent, went toward dried flowers, generating transactions worth about $375 million during the second quarter of 2017, which ended June 30. BDS Analytics tracks 13,000 different types of named strains. The top five sold in California were Blue Dream, Golden Goat, Durban Poison, Gorilla Glue and Green Crack. The second-most popular form of cannabis was concentrates, comprising 25 percent of all sales worth $169 million during that same four-month time frame. Concentrates are a fast-evolving category that includes oils, waxes and other substances, that are typically heated up and smoked. The extraction methods draw compounds out of the marijuana plant, such as the psychoactive compound, THC, as well as other cannabinoids like CBD, which by itself doesn’t get a person high. Chocolate is the most popular infused edible product, followed by gummy candies, which together generated nearly $40 million in sales from April through June. “For us, first and foremost, the flowers are the dominant seller,” said Surina Sisavath, general manager of Natural Cannabis Company, which runs the OrganiCann dispensary. Don’t miss the rest of our celebrity strain reviews and check out our previous reviews of Cannabis Cup winners, sungrown organics, vape oils and summer strains. More than half of customers surveyed at OrganiCann dispensary on Todd Road in Santa Rosa said they like more than one type of cannabis product, according to an informal poll conducted on a mid-September day by dispensary staff. More than half of the 260 people polled said they like to consume cannabis in multiple forms. About 77 percent of the customers said they like smoking pot the old fashioned way and about 24 percent said they like using vape pen products. Sisavath said the dispensary aims to offer a wide variety of flowers, about 75 different strains on a day last week. They mostly come from Sonoma, Lake and Mendocino county cannabis farms. On Wednesday, Carena Piccinotto, 26, of Rohnert Park, discussed the merits of the Candy Jack strain with a bud tender. Piccinotto purchased four different strains of cannabis flowers, all geared toward different times of day when she wants to be alert or to help her sleep. She pointed to the scars on her knees, remnants of surgeries she endured last year after falling from an ATV. “I took no narcotics,” Piccinotto said. Across the way at the edibles counter, Catherine Jones, 23, of Novato, was buying cannabis-infused cheese crackers to eat before flying to Los Angeles for what could be a stressful family visit. And at a kiosk for topical creams and ointments, Chuck Cadman, 80, of Santa Rosa, was buying a sweet-smelling topical sports rub he uses on his arthritic knees. “It’s for anti-inflammation,” Cadman said. “I put it on my knees every morning, and it’s working within 10 to 15 minutes.” To subscribe to The Cannifornian’s email newsletter, click here.
def p_to_string(p): p_rounded = np.round(p, 3) if p_rounded >= 0.05: p_str = '$p = {}$'.format(p_rounded) elif p_rounded < 0.05 and p_rounded >= 0.01: p_str = '$p < 0.05$' elif p_rounded < 0.01 and p_rounded >= 0.001: p_str = '$p < 0.01$' else: p_str = '$p < 0.001$' return p_str
Twelve years ago, a stock boy at Target purchased a chunk of space debris at the Tucson Gem and Mineral Show that changed his life forever. Michael Farmer, aka the Meteorite Guy, holding a 20-pound meteorite on the boarder of Morocco. According to his website, he is wearing a "Jeleba," a traditional outfit for the area, to blend into this hostile-to-Westerners area. See the slide show below for more pictures of him and his collection. Today, that former star-struck stock boy thinks nothing of charging $20,000 to his well-traveled business credit card for outer space real estate the size of a Milky Way bar. He has flashed his plastic to sun-baked Bedouins, parched Peruvians and rustic Russians in exchange for fragments from the final frontier. He has taken more than 50 trips to Africa and earned 3 million frequent flier miles on one airline alone. He has not only held pieces of the moon and Mars in his hands -- he has tasted them. "I've eaten a piece of every moon rock and Mars rock that I have purchased or found, just to say I did it," he chuckles. "We are all made of space rock." Welcome to the out-of-this-world life of Michael Farmer, aka Meteorite Guy, one of only about 20 professional meteorite brokers -- on this planet anyway. Building a rock-solid empire Farmer was a 25-year-old college student attending the University of Arizona on the G.I. Bill, stocking shelves part time and vaguely drifting toward a career with the CIA when he happened to wander into the largest gem and mineral show on earth. "I bought a rock (meteorite) for $70 and got so fascinated with it that it changed the course of my life," Farmer recalls. "When I saw it, I thought, 'Wow, I'm holding a piece of outer space!'" Anxious to find more, he scoured the gem show site until he met an old-timer who had a box of 40 meteorites hidden under the table. His asking price: $4,000 for the box. "I had no money at the time, so I had to beg and borrow to buy the box," Farmer recalls. "When I started researching the meteorites, I found that that they were from a very rare collection, and I quadrupled my money on those stones in about 48 hours. That's when I realized you could actually make money doing this." Within a year, Farmer had earned enough to make the first of dozens of trips to Africa, initially focusing on the Sahara Desert. Why the desert? Prepare to be mentally humbled. I have meteorites I can sell you for less than $100 a pound, but the lunar meteorites, you're talking $1,000 a gram. -- Michael Farmer The Meteorite Guy "You have no ground cover, no vegetation and it's dry," Farmer explains. "Water affects meteorites because most of them are full of iron and metal, so they deteriorate in water. Anything that falls in the desert lasts 50,000 years, just like any other rock." What's more, the contrast with all that sand makes them pretty easy to spot. "I go hunting myself in Oman in the Middle East, and it looks like you're driving on snow over this white limestone and there are no black rocks there," he says. "If you see a black rock, 99 percent of the time it's a meteorite. You can pick up anywhere from five to 20 meteorites a day there." Farmer says the French initially showed Moroccan nomads a few meteorites and offered to buy any they might find in their journeys across Mali, Algeria and Mauritania. "The nomads started bringing them in by the ton," he says. "I used to go there and buy 800-900 pounds of rock in a day." So does a Berber nomad take Visa? "You'd be surprised!" Farmer laughs. "If they can't take a card, they can find somebody who can. I've actually done that in Africa; when I've depleted my cash, at the last second I've gone to businesses and charged a card, and they give the nomad their money." Nomads may live in the desert, but they are far from isolated these days, thanks to cellular phones and the Internet. Many nomadic meteorite hunters now sell directly to collectors and museums worldwide, and they drive a harder bargain with brokers like Farmer. "When I started, they were loading meteorites onto camel trains; now they all drive Land Cruisers and carry multiple cell phones," he chuckles. "They're all very rich now. They have bigger houses than I do." Story continues below. A far out investment Meteorites come in all dimensions, from the size of a grape to a 50-gallon drum. Their value to collectors and museums depends on their provenance, with fragments of the moon or Mars generally being the most prized. That's right, we've had moon rocks and Mars bars under foot long before the dawn of the space program, thanks to meteor strikes there that sent chunks from those low-atmosphere orbs hurtling here. But they're rare; out of about 70 known lunar meteorites, Farmer has found three. "I have meteorites I can sell you for less than $100 a pound, but the lunar meteorites, you're talking $1,000 a gram," he says. "By contrast, gold right now is $30 a gram." The rarest meteorites sell for more than $1 million. Farmer once paid $125,000 for a 1.25-pound moon rock from Morocco the size of a baseball. "I chopped it up, recovered most of the money and I have 50 percent left," he says. "We don't have one moon rock ever that was seen to fall. If that happens, the sky's the limit on price." Brokers tend to both hunt their own -- it is found money, after all -- and broker deals with collectors and museums, often literally taking a slice of the rock for their services if the stone is not sold whole. Some of Farmer's stones are on display at the Smithsonian Institute and the American Museum of Natural History. "It has taken me 12 years to build a client list. Right now, I have a client list where anything in the $10,000-$100,000 range, I can usually make a phone call and sell it. There are a few hundred on my list, but only about 20 big hitters," Farmer says. Theoretically, seven out of 10 meteorites fall into the ocean, since the oceans cover 70 percent of the earth's surface. But before you rush to the shore with your scuba gear, you should know that there's not much market for soggy chunks. "Finding them would be too expensive, and they wouldn't last very long because they would start oxidizing the minute they hit the water," Farmer explains. "Collectors and scientists don't like that. It's contaminated." When I put $50,000 into rock, it tends to be because I like it and can look at it every day and see where my money is. -- Michael Farmer The Meteorite Guy And contrary to Hollywood hype, although most meteorites hit the earth at a terminal velocity of around 120 miles per hour, they're not sizzling hot when they strike, having passed through the earth's frigid upper atmosphere. "You see this burning but it all stops 20 miles high," Farmer says. Although Farmer has endured scorching desert heat and subzero arctic temperatures in pursuit of meteorites, a fair number of them land on ordinary Main Streets around the globe. He frequently gets calls from startled folks such as those in the Chicago suburb of Park Forest, where hundreds of stones fell around midnight in 2003. "One woman was on her computer and saw a light out the window and suddenly there was a big explosion as a rock came through her roof and hit her printer two feet away," Farmer says. "Another stone went through the roof of a house, through the upstairs and downstairs floors and ended up in a pile of laundry in the basement." The February fall near Waco, Texas, was the first to be captured on Doppler weather radar, which set up a modern-day rock rush of hunters and collectors. "I saw it on CNN and was on a plane the next morning. We pinpointed it, we drove there and we were dead on," Farmer says. "Unfortunately, so were about 70 other hunters. Even collectors came out. I would negotiate with a landowner to hunt on their land and an hour later he would throw us out because someone else had made him a better offer." So how fares the meteorite market in these recessionary times? "The supply is very low and the demand has really been going up in the last few years," says Farmer. "Prices have quadrupled on certain items just in the last year." He is currently working on a $1.5 million sale of a 120-pound meteorite. He once negotiated in a similar price range with the Russians for a whopper weighing 3.5 tons. Having been burned investing in less rock-solid opportunities, Farmer says he's learned to keep his money in his inventory. One great thing about meteorites: you can't fake them. "I lost about a quarter-million dollars in the stock market and realized maybe I should stick to something I know. When I put $50,000 into rock, it tends to be because I like it and can look at it every day and see where my money is. And if the house burns down, I can pull them out of the ashes." See related: Credit card travel preperations, Card use overseas: Beware conversion and exchange fees, Taking too many financial risks? Blame your brain, 13 greatest credit card songs meld pop, plastic, Zodiac credit cards
<reponame>ifeilong/feilong-json /* * Copyright (C) 2008 feilong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.feilong.json.jsonlib; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feilong.store.member.Address; /** * test https://github.com/venusdrogon/feilong-json/issues/30 * * @author <a href="http://feitianbenyue.iteye.com/">feilong</a> * @since 1.14.0 * @deprecated json format bean 支持排序输出 放弃吧, */ @Deprecated public class FormatBeanSortBeanPropertyTest{ /** The Constant log. */ private static final Logger LOGGER = LoggerFactory.getLogger(FormatBeanSortBeanPropertyTest.class); //--------------------------------------------------------------- @Test public void test(){ //json format bean 支持排序输出 放弃吧, //参见 https://github.com/venusdrogon/feilong-json/issues/30 Address user = new Address("china", "shanghai", "216000", "wenshui wanrong.lu 888"); LOGGER.debug(JsonUtil.format(user)); } }
/** * Executes Telegram request synchronously. * * @param request Telegram Request. * @param <T> Telegram response type. * @return Telegram response. * @throws InterruptedException if errors occur. * @throws ExecutionException if errors occur. * @throws TimeoutException if errors occur. */ private <T extends TdApi.Object> TdApi.Object sendSynchronously(TdApi.Function<T> request) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture<TdApi.Object> response = new CompletableFuture<>(); telegramClient.send(request, response::complete, response::completeExceptionally); return response.get(5, TimeUnit.SECONDS); }
<filename>library/src/androidTest/java/com/google/android/exoplayer/text/ttml/TtmlStyleTest.java /* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.text.ttml; import android.graphics.Color; import android.test.InstrumentationTestCase; /** * Unit test for {@link TtmlStyle}. */ public final class TtmlStyleTest extends InstrumentationTestCase { private static final String FONT_FAMILY = "serif"; private static final String ID = "id"; public static final int FOREGROUND_COLOR = Color.WHITE; public static final int BACKGROUND_COLOR = Color.BLACK; private TtmlStyle style; @Override public void setUp() throws Exception { super.setUp(); style = new TtmlStyle(); } public void testInheritStyle() { style.inherit(createAncestorStyle()); assertNull("id must not be inherited", style.getId()); assertTrue(style.isUnderline()); assertTrue(style.isLinethrough()); assertEquals(TtmlStyle.STYLE_BOLD_ITALIC, style.getStyle()); assertEquals(FONT_FAMILY, style.getFontFamily()); assertEquals(Color.WHITE, style.getFontColor()); assertFalse("do not inherit backgroundColor", style.hasBackgroundColor()); } public void testChainStyle() { style.chain(createAncestorStyle()); assertNull("id must not be inherited", style.getId()); assertTrue(style.isUnderline()); assertTrue(style.isLinethrough()); assertEquals(TtmlStyle.STYLE_BOLD_ITALIC, style.getStyle()); assertEquals(FONT_FAMILY, style.getFontFamily()); assertEquals(FOREGROUND_COLOR, style.getFontColor()); // do inherit backgroundColor when chaining assertEquals("do not inherit backgroundColor when chaining", BACKGROUND_COLOR, style.getBackgroundColor()); } private TtmlStyle createAncestorStyle() { TtmlStyle ancestor = new TtmlStyle(); ancestor.setId(ID); ancestor.setItalic(true); ancestor.setBold(true); ancestor.setBackgroundColor(BACKGROUND_COLOR); ancestor.setFontColor(FOREGROUND_COLOR); ancestor.setLinethrough(true); ancestor.setUnderline(true); ancestor.setFontFamily(FONT_FAMILY); return ancestor; } public void testStyle() { assertEquals(TtmlStyle.UNSPECIFIED, style.getStyle()); style.setItalic(true); assertEquals(TtmlStyle.STYLE_ITALIC, style.getStyle()); style.setBold(true); assertEquals(TtmlStyle.STYLE_BOLD_ITALIC, style.getStyle()); style.setItalic(false); assertEquals(TtmlStyle.STYLE_BOLD, style.getStyle()); style.setBold(false); assertEquals(TtmlStyle.STYLE_NORMAL, style.getStyle()); } public void testLinethrough() { assertFalse(style.isLinethrough()); style.setLinethrough(true); assertTrue(style.isLinethrough()); style.setLinethrough(false); assertFalse(style.isLinethrough()); } public void testUnderline() { assertFalse(style.isUnderline()); style.setUnderline(true); assertTrue(style.isUnderline()); style.setUnderline(false); assertFalse(style.isUnderline()); } public void testFontFamily() { assertNull(style.getFontFamily()); style.setFontFamily(FONT_FAMILY); assertEquals(FONT_FAMILY, style.getFontFamily()); style.setFontFamily(null); assertNull(style.getFontFamily()); } public void testColor() { assertFalse(style.hasFontColor()); style.setFontColor(Color.BLACK); assertEquals(Color.BLACK, style.getFontColor()); assertTrue(style.hasFontColor()); } public void testBackgroundColor() { assertFalse(style.hasBackgroundColor()); style.setBackgroundColor(Color.BLACK); assertEquals(Color.BLACK, style.getBackgroundColor()); assertTrue(style.hasBackgroundColor()); } public void testId() { assertNull(style.getId()); style.setId(ID); assertEquals(ID, style.getId()); style.setId(null); assertNull(style.getId()); } }
IUD-related hospitalizations. United States and Puerto Rico, 1973. In a mail survey of physicians likely to be involved with intrauterine contraception in the United States and Puerto Rico, 49.2% of the physicians responded, describing 3,502 unduplicated reports of hospitalizations related to the use of intrauterine contraceptive devices (IUDs) during the first six months of 1973. We estimate from this response that approximately 7,900 IUD-related hospitalizations occurred during that period. Interviews with a probability sample of nonrespondents demonstrated that their IUD complication experience was not substantially different from that reported through the mail survey. Estimates of the number of IUDs worn in 1973 permit rate calculations of three to ten IUD-related hospitalizations per 1,000 woman-years of IUD use. The rate of hospitalizations attributable to the IUD is probably higher that that attributable to combination oral contraceptives.
def save(self, entity): collection = self.get_database_collection(entity.__class__) if '_id' in entity and entity['_id'] is not None: collection.replace_one({'_id': entity['_id']}, entity) else: entity['_id'] = collection.insert_one(entity).inserted_id
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.kernel.jaas.boot; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; /** * An OSGi proxy login module that should be used instead of a plain reference to * a given login module. Two properties must be set, the name of the login module * class and the bundle to be used to load it. * This class must be available from all modules, so it has to be either in a fragment * bundle attached to the system bundle or be made available through the boot delegation * class path. */ public class ProxyLoginModule implements LoginModule { public static final String PROPERTY_MODULE = "org.apache.servicemix.kernel.jaas.module"; public static final String PROPERTY_BUNDLE = "org.apache.servicemix.kernel.jaas.bundle"; private static BundleContext bundleContext = null; private LoginModule target = null; public static void init(BundleContext context) { bundleContext = context; } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map) */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { if (bundleContext == null) { throw new IllegalStateException("ProxyLoginModule not initialized. Init must be called prior any invocation."); } Map<String,?> newOptions = new HashMap<String,Object>(options); String module = (String) newOptions.remove(PROPERTY_MODULE); if (module == null) { throw new IllegalStateException("Option " + PROPERTY_MODULE + " must be set to the name of the factory service"); } String bundleId = (String) newOptions.remove(PROPERTY_BUNDLE); if (bundleId == null) { throw new IllegalStateException("Option " + PROPERTY_BUNDLE + " must be set to the name of the factory service"); } Bundle bundle = bundleContext.getBundle(Long.parseLong(bundleId)); if (bundle == null) { throw new IllegalStateException("No bundle found for id " + bundleId); } try { target = (LoginModule) bundle.loadClass(module).newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not load or create login module " + module + " for bundle " + bundleId, e); } target.initialize(subject, callbackHandler, sharedState, options); } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#login() */ public boolean login() throws LoginException { return target.login(); } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#commit() */ public boolean commit() throws LoginException { return target.commit(); } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#abort() */ public boolean abort() throws LoginException { return target.abort(); } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#logout() */ public boolean logout() throws LoginException { return target.logout(); } }
/* * Logically we would return an error here to prevent users from believing * they might have changed mount options using remount which can't be changed. * * But unfortunately mount(8) adds all options from mtab and fstab to the mount * arguments in some cases so we can't blindly reject options, but have to * check for each specified option if it actually differs from the currently * set option and only reject it if that's the case. * * Until that is implemented we return success for every remount request, and * silently ignore all options that we can't actually change. */ static int xfs_fs_reconfigure( struct fs_context *fc) { struct xfs_mount *mp = XFS_M(fc->root->d_sb); struct xfs_mount *new_mp = fc->s_fs_info; int flags = fc->sb_flags; int error; if (xfs_has_crc(mp)) fc->sb_flags |= SB_I_VERSION; error = xfs_fs_validate_params(new_mp); if (error) return error; sync_filesystem(mp->m_super); if (xfs_has_small_inums(mp) && !xfs_has_small_inums(new_mp)) { mp->m_features &= ~XFS_FEAT_SMALL_INUMS; mp->m_maxagi = xfs_set_inode_alloc(mp, mp->m_sb.sb_agcount); } if (!xfs_has_small_inums(mp) && xfs_has_small_inums(new_mp)) { mp->m_features |= XFS_FEAT_SMALL_INUMS; mp->m_maxagi = xfs_set_inode_alloc(mp, mp->m_sb.sb_agcount); } if (xfs_is_readonly(mp) && !(flags & SB_RDONLY)) { error = xfs_remount_rw(mp); if (error) return error; } if (!xfs_is_readonly(mp) && (flags & SB_RDONLY)) { error = xfs_remount_ro(mp); if (error) return error; } return 0; }
<filename>src/test/java/ch/rasc/extclassgenerator/bean/BeanWithValidation.java /** * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.extclassgenerator.bean; import ch.rasc.extclassgenerator.*; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; @ModelValidations({ @ModelValidation(propertyName = "email", value = ModelValidationType.PRESENCE) }) @Model public class BeanWithValidation { @Email public String email; @Pattern(regexp = "^/\\w.*\\.\\w.*") public String url; @DecimalMax("100") @DecimalMin("1") public BigDecimal minMax1; @Max(10000) @Min(20) public int minMax2; @Range(min = 20, max = 50) public long minMax3; @Digits(integer = 10, fraction = 2) public String digits; @Future public Date future; public Date past; @NotBlank public String notBlank; @CreditCardNumber public String creditCardNumber; @Past public Date getPast() { return this.past; } public void setPast(Date past) { this.past = past; } public static List<ModelFieldBean> expectedFields = new ArrayList<>(); static { ModelFieldBean field = new ModelFieldBean("email", ModelType.STRING); expectedFields.add(field); field = new ModelFieldBean("url", ModelType.STRING); expectedFields.add(field); field = new ModelFieldBean("minMax1", ModelType.FLOAT); expectedFields.add(field); field = new ModelFieldBean("minMax2", ModelType.INTEGER); expectedFields.add(field); field = new ModelFieldBean("minMax3", ModelType.INTEGER); expectedFields.add(field); field = new ModelFieldBean("digits", ModelType.STRING); expectedFields.add(field); field = new ModelFieldBean("future", ModelType.DATE); expectedFields.add(field); field = new ModelFieldBean("past", ModelType.DATE); expectedFields.add(field); field = new ModelFieldBean("notBlank", ModelType.STRING); expectedFields.add(field); field = new ModelFieldBean("creditCardNumber", ModelType.STRING); expectedFields.add(field); } }
/** * Return true if any evaluator returns true, indicating that * the stack trace should not be logged. */ private boolean isExcludedByEvaluator(ILoggingEvent event) { for (int i = 0; i < evaluators.size(); i++) { EventEvaluator<ILoggingEvent> evaluator = evaluators.get(i); try { if (evaluator.evaluate(event)) { return true; } } catch (EvaluationException eex) { int errors = errorCount.incrementAndGet(); if (errors < CoreConstants.MAX_ERROR_COUNT) { addError(String.format("Exception thrown for evaluator named [%s]", evaluator.getName()), eex); } else if (errors == CoreConstants.MAX_ERROR_COUNT) { ErrorStatus errorStatus = new ErrorStatus( String.format("Exception thrown for evaluator named [%s]", evaluator.getName()), this, eex); errorStatus.add(new ErrorStatus( "This was the last warning about this evaluator's errors." + "We don't want the StatusManager to get flooded.", this)); addStatus(errorStatus); } } } return false; }
/** * <p> * </p> * ClassName:ResourceLoaderTest <br> * Date: Sep 15, 2017 4:40:54 PM <br> * * @author kehw_zwei * @version 1.0.0 * @since JDK 1.8 */ public class ResourceLoaderTest { @Test public void blueprintTest() throws IOException { Map<Integer, Blueprint> blueprintMap = JacksonUtil.create(new YAMLFactory()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .toObject(FileUtil.getFirstExistFile("file:eve_data/fsd/blueprints.yaml"), new TypeReference<Map<Integer, Blueprint>>() { }); assertEquals(blueprintMap.get(681) .getActivities() .getCopying() .getTime(), 480); } @Test public void typeTest() throws IOException { Map<Integer, Type> blueprintMap = JacksonUtil.create(new YAMLFactory()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .toObject(FileUtil.getFirstExistFile("file:eve_data/fsd/typeIDs.yaml"), new TypeReference<Map<Integer, Type>>() { }); assertEquals(blueprintMap.get(9247) .getSofFactionName(), "minmatarbase"); } }
/** * * @param model * @param compartmentIdsToUri * @throws TransformerFactoryConfigurationError * @throws Exception */ public static void createCompartments( final Model model, final Map<String,String> compartmentIdsToUri ) throws TransformerFactoryConfigurationError, Exception { for( Map.Entry<String,String> entry : compartmentIdsToUri.entrySet() ) { final String compartmentId = entry.getKey(); final Compartment compartment = model.createCompartment( compartmentId ); compartment.setSBOTerm( SboUtils.COMPARTMENT ); compartment.setSize( 1.0 ); addOntologyTerm( compartment, "BQB_IS", OntologyUtils.getInstance().getOntologyTerm( entry.getValue() ) ); } }
import { gql } from "@apollo/client"; import { Alert, AlertDescription, AlertIcon, AlertTitle, Button, ButtonGroup, FormControl, FormLabel, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, NumberDecrementStepper, NumberIncrementStepper, NumberInput, NumberInputField, NumberInputStepper, Text, } from "@chakra-ui/react"; import React, { useCallback, useMemo, useState } from "react"; import { useUpdateUploadsRemainingMutation } from "../../../../../../generated/graphql"; gql` mutation UpdateUploadsRemaining($elementIds: [uuid!]!, $count: Int!) { update_content_Element(where: { id: { _in: $elementIds } }, _set: { uploadsRemaining: $count }) { affected_rows } } `; export function UpdateUploadsRemainingModal({ isOpen, onClose, elementsByItem, }: { isOpen: boolean; onClose: () => void; elementsByItem: { itemId: string; elementIds: string[]; }[]; }): JSX.Element { return ( <Modal isOpen={isOpen} onClose={onClose}> <ModalOverlay /> <ModalContent> <ModalHeader>Update uploads remaining</ModalHeader> <ModalCloseButton /> {isOpen ? <ModalInner elementsByItem={elementsByItem} onClose={onClose} /> : undefined} </ModalContent> </Modal> ); } function ModalInner({ onClose, elementsByItem, }: { onClose: () => void; elementsByItem: { itemId: string; elementIds: string[]; }[]; }): JSX.Element { const elementIds = useMemo(() => elementsByItem.flatMap((x) => x.elementIds), [elementsByItem]); const [newValue, setNewValue] = useState<number>(3); const [doUpdate, updateResponse] = useUpdateUploadsRemainingMutation(); const update = useCallback(async () => { try { await doUpdate({ variables: { elementIds, count: newValue, }, }); onClose(); } catch (e) { console.error("Failed to update uploads remaining", e); } }, [doUpdate, elementIds, newValue, onClose]); return ( <> <ModalBody> <Text>This will update the number of uploads remaining on selected elements.</Text> <FormControl mt={4}> <FormLabel>New uploads remaining</FormLabel> <NumberInput value={newValue} onChange={(_valueAsStr, value) => { if (!Number.isNaN(value)) { setNewValue(value); } }} min={0} max={3} > <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </FormControl> {updateResponse.error ? ( <Alert status="error" mt={4}> <AlertTitle> <AlertIcon /> Error updating uploads remaining </AlertTitle> <AlertDescription>{updateResponse.error.message}</AlertDescription> </Alert> ) : undefined} </ModalBody> <ModalFooter> <ButtonGroup spacing={2}> <Button onClick={onClose}>Cancel</Button> <Button colorScheme="purple" isLoading={updateResponse.loading} onClick={update}> Update </Button> </ButtonGroup> </ModalFooter> </> ); }
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module for ChangeState event.""" import collections from typing import Callable from launch.event import Event import lifecycle_msgs.msg if False: # imports here would cause loops, but are only used as forward-references for type-checking from ...actions import LifecycleNode # noqa: F401 class ChangeState(Event): """Event emitted when a state transition is requested for a lifecycle node.""" name = 'launch_ros.events.lifecycle.ChangeState' valid_transitions = collections.OrderedDict([ (lifecycle_msgs.msg.Transition.TRANSITION_CREATE, 'TRANSITION_CREATE'), (lifecycle_msgs.msg.Transition.TRANSITION_CONFIGURE, 'TRANSITION_CONFIGURE'), (lifecycle_msgs.msg.Transition.TRANSITION_CLEANUP, 'TRANSITION_CLEANUP'), (lifecycle_msgs.msg.Transition.TRANSITION_ACTIVATE, 'TRANSITION_ACTIVATE'), (lifecycle_msgs.msg.Transition.TRANSITION_DEACTIVATE, 'TRANSITION_DEACTIVATE'), ( lifecycle_msgs.msg.Transition.TRANSITION_UNCONFIGURED_SHUTDOWN, 'TRANSITION_UNCONFIGURED_SHUTDOWN', ), ( lifecycle_msgs.msg.Transition.TRANSITION_INACTIVE_SHUTDOWN, 'TRANSITION_INACTIVE_SHUTDOWN', ), (lifecycle_msgs.msg.Transition.TRANSITION_ACTIVE_SHUTDOWN, 'TRANSITION_ACTIVE_SHUTDOWN'), (lifecycle_msgs.msg.Transition.TRANSITION_DESTROY, 'TRANSITION_DESTROY'), ]) valid_states = collections.OrderedDict([ (lifecycle_msgs.msg.State.PRIMARY_STATE_UNKNOWN, 'PRIMARY_STATE_UNKNOWN'), (lifecycle_msgs.msg.State.PRIMARY_STATE_UNCONFIGURED, 'PRIMARY_STATE_UNCONFIGURED'), (lifecycle_msgs.msg.State.PRIMARY_STATE_INACTIVE, 'PRIMARY_STATE_INACTIVE'), (lifecycle_msgs.msg.State.PRIMARY_STATE_ACTIVE, 'PRIMARY_STATE_ACTIVE'), (lifecycle_msgs.msg.State.PRIMARY_STATE_FINALIZED, 'PRIMARY_STATE_FINALIZED'), (lifecycle_msgs.msg.State.TRANSITION_STATE_CONFIGURING, 'TRANSITION_STATE_CONFIGURING'), (lifecycle_msgs.msg.State.TRANSITION_STATE_CLEANINGUP, 'TRANSITION_STATE_CLEANINGUP'), (lifecycle_msgs.msg.State.TRANSITION_STATE_SHUTTINGDOWN, 'TRANSITION_STATE_SHUTTINGDOWN'), (lifecycle_msgs.msg.State.TRANSITION_STATE_ACTIVATING, 'TRANSITION_STATE_ACTIVATING'), (lifecycle_msgs.msg.State.TRANSITION_STATE_DEACTIVATING, 'TRANSITION_STATE_DEACTIVATING'), ( lifecycle_msgs.msg.State.TRANSITION_STATE_ERRORPROCESSING, 'TRANSITION_STATE_ERRORPROCESSING', ), ]) def __init__( self, *, lifecycle_node_matcher: Callable[['LifecycleNode'], bool], transition_id: int ) -> None: """ Constructor. :param: lifecycle_node_matcher is a callable which returns True if the given lifecycle node should be affected by this event. :param: transition_id is the id of the requested transition which are defined in the :class:`lifecycle_msgs.msg.Transition` message class, e.g. `lifecycle_msgs.msg.Transition.TRANSITION_CONFIGURE`. """ super().__init__() self.__lifecycle_node_matcher = lifecycle_node_matcher self.__transition_id = transition_id if transition_id not in self.valid_transitions.keys(): raise ValueError("given transition_id of '{}', expected one of {{{}}}".format( transition_id, ', '.join(['{}: {}'.format(v, k) for k, v in self.valid_transitions.items()]), )) @property def lifecycle_node_matcher(self) -> Callable[['LifecycleNode'], bool]: """Getter for lifecycle_node_matcher.""" return self.__lifecycle_node_matcher @property def transition_id(self) -> int: """Getter for transition_id.""" return self.__transition_id
def _GenerateSantaEventsFromJsonEvent(cls, event, host): dbevent = event_models.SantaEvent() dbevent.host_id = host.key.id() dbevent.file_name = event.get(_EVENT_UPLOAD.FILE_NAME) dbevent.file_path = event.get(_EVENT_UPLOAD.FILE_PATH) dbevent.version = event.get(_EVENT_UPLOAD.FILE_BUNDLE_VERSION) dbevent.executing_user = event.get(_EVENT_UPLOAD.EXECUTING_USER) dbevent.event_type = event.get(_EVENT_UPLOAD.DECISION) dbevent.bundle_path = event.get(_EVENT_UPLOAD.FILE_BUNDLE_PATH) dbevent.bundle_key = cls._GetBundleKeyFromJsonEvent(event) blockable_id = event.get(_EVENT_UPLOAD.FILE_SHA256) if blockable_id: dbevent.blockable_key = ndb.Key( binary_models.SantaBlockable, blockable_id) publisher, cert_sha256 = ( cls._GetPublisherAndCertFingerprintFromJsonEvent(event)) dbevent.publisher = publisher if cert_sha256: dbevent.cert_key = ndb.Key(cert_models.SantaCertificate, cert_sha256) occurred_dt = datetime.datetime.utcfromtimestamp( event.get(_EVENT_UPLOAD.EXECUTION_TIME, 0)) dbevent.first_blocked_dt = occurred_dt dbevent.last_blocked_dt = occurred_dt quarantine_timestamp = event.get(_EVENT_UPLOAD.QUARANTINE_TIMESTAMP, 0) if quarantine_timestamp: quarantine_time = datetime.datetime.utcfromtimestamp(quarantine_timestamp) dbevent.quarantine = event_models.QuarantineMetadata( data_url=event.get(_EVENT_UPLOAD.QUARANTINE_DATA_URL), referer_url=event.get(_EVENT_UPLOAD.QUARANTINE_REFERER_URL), agent_bundle_id=event.get(_EVENT_UPLOAD.QUARANTINE_AGENT_BUNDLE_ID), downloaded_dt=quarantine_time) usernames = event.get(_EVENT_UPLOAD.LOGGED_IN_USERS, []) tables.EXECUTION.InsertRow( sha256=blockable_id, device_id=dbevent.host_id, timestamp=occurred_dt, platform=dbevent.GetPlatformName(), client=dbevent.GetClientName(), bundle_path=dbevent.bundle_path, file_path=dbevent.file_path, file_name=dbevent.file_name, executing_user=dbevent.executing_user or 'UNKNOWN', associated_users=usernames, decision=dbevent.event_type) event_keys = model_utils.GetEventKeysToInsert( dbevent, usernames, [host.primary_user]) return [ datastore_utils.CopyEntity(dbevent, new_key=event_key) for event_key in event_keys]
<filename>frontend/src/routes/ClusterManagement/ClusterManagement.test.tsx<gh_stars>0 /* Copyright Contributors to the Open Cluster Management project */ import { render } from '@testing-library/react' import { MemoryRouter } from 'react-router-dom' import { RecoilRoot } from 'recoil' import { waitForNotText, waitForText } from '../../lib/test-util' import ClusterManagementPage from './ClusterManagement' import { mockDiscoveryFeatureGate } from '../../lib/test-metadata' import { featureGatesState } from '../../atoms' describe('Cluster Management', () => { test('Discovery Feature Flag Enabled', async () => { render( <RecoilRoot initializeState={(snapshot) => { snapshot.set(featureGatesState, [mockDiscoveryFeatureGate]) }} > <MemoryRouter> <ClusterManagementPage /> </MemoryRouter> </RecoilRoot> ) await waitForText('cluster:clusters') await waitForText('cluster:clusters.discovered') }) test('No Discovery Feature Flag', async () => { render( <RecoilRoot initializeState={(snapshot) => { snapshot.set(featureGatesState, []) }} > <MemoryRouter> <ClusterManagementPage /> </MemoryRouter> </RecoilRoot> ) await waitForText('cluster:clusters') await waitForNotText('cluster:clusters.discovered') }) })
<gh_stars>0 package letter const testVersion = 1 func ConcurrentFrequency(texts []string) FreqMap { ch := make(chan FreqMap) defer close(ch) for _, s := range texts { go func(s string, ch chan FreqMap) { ch <- Frequency(s) }(s, ch) } var res = make(FreqMap) for i := 0; i < len(texts); i++ { f := <-ch for r, c := range f { res[r] += c } } return res }
Well that didn't take long. Less than one week after the bloody terror attacks at the offices of Charlie Hebdo, former President Jimmy Carter has all but blamed Israel for instigating the massacre. Appearing on Comedy Central's The Daily Show, Carter was asked by host Jon Stewart about the influence of radical Islam on the attackers. His answer was inexplicable: "Well, one of the origins for it is the Palestinian problem. And this aggravates people who are affiliated in any way with the Arab people who live in the West Bank and Gaza, what they are doing now — what’s being done to them. So I think that’s part of it." As Jamie Weinstein at The Daily Caller reports: Carter didn’t explain how solving the Israeli-Palestinian issue would in any way resolve the violent conflicts currently engulfing the Arab world, including the Syrian civil war, the Islamic State’s takeover of part of Iraq and its brutal implementation of Islamic law, and the conflict between the Egyptian government and the Muslim Brotherhood, just to name a few. Nor did he detail how the “Palestinian problem” helps explain why three French Muslims murdered innocent French Jews buying groceries for the coming Sabbath and cartoonists preparing the next issue of their paper. Carter's book on Israel and the Palestinian territory likened Israel to the racist Apartheid government of South Africa.
<reponame>roxdumitriu/spark<filename>async-shuffle-upload/async-shuffle-upload-core/src/main/java/org/apache/spark/palantir/shuffle/async/client/basic/DefaultPartitionOffsetsFetcher.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.palantir.shuffle.async.client.basic; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.exceptions.SafeIoException; import com.palantir.logsafe.exceptions.SafeRuntimeException; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.palantir.shuffle.async.AsyncShuffleDataIoSparkConfigs; import org.apache.spark.palantir.shuffle.async.ShuffleDriverEndpointRef; import org.apache.spark.palantir.shuffle.async.io.PartitionDecoder; import org.apache.spark.palantir.shuffle.async.metadata.MapOutputId; import org.apache.spark.palantir.shuffle.async.util.AbortableOutputStream; import org.apache.spark.palantir.shuffle.async.util.PartitionOffsets; import org.apache.spark.palantir.shuffle.async.util.streams.BufferedSeekableInput; import org.apache.spark.palantir.shuffle.async.util.streams.SeekableInput; /** * Default implementation of {@link PartitionOffsetsFetcher} that is backed by index files stored * by the {@link HadoopShuffleClient} module. * <p> * This module may cache index files on local disk, if it is so configured via * {@link AsyncShuffleDataIoSparkConfigs#CACHE_INDEX_FILES_LOCALLY()}. An asynchronous task also * periodically removes downloaded index files that are no longer needed. */ public final class DefaultPartitionOffsetsFetcher implements PartitionOffsetsFetcher { private static final Logger LOG = LoggerFactory.getLogger(DefaultPartitionOffsetsFetcher.class); private final LocalDownloadShuffleFileSystem localShuffleFs; private final RemoteShuffleFileSystem remoteShuffleFs; private final int localFileBufferSize; private final int shuffleDownloadBufferSize; private final boolean cacheIndexFilesLocally; private final Map<MapOutputId, Boolean> fetchingIndexFiles; private final Set<Integer> fetchedShuffleIds; private final ListeningScheduledExecutorService cleanupExecutor; private final ShuffleDriverEndpointRef driverEndpointRef; public DefaultPartitionOffsetsFetcher( LocalDownloadShuffleFileSystem localShuffleFs, RemoteShuffleFileSystem remoteShuffleFs, ScheduledExecutorService cleanupExecutor, ShuffleDriverEndpointRef driverEndpointRef, int localFileBufferSize, int shuffleDownloadBufferSize, boolean cacheIndexFilesLocally) { this.localShuffleFs = localShuffleFs; this.remoteShuffleFs = remoteShuffleFs; this.cleanupExecutor = MoreExecutors.listeningDecorator(cleanupExecutor); this.driverEndpointRef = driverEndpointRef; this.localFileBufferSize = localFileBufferSize; this.shuffleDownloadBufferSize = shuffleDownloadBufferSize; this.cacheIndexFilesLocally = cacheIndexFilesLocally; this.fetchingIndexFiles = new ConcurrentHashMap<>(); this.fetchedShuffleIds = ConcurrentHashMap.newKeySet(); } public void startCleaningIndexFiles() { cleanupExecutor.scheduleWithFixedDelay( this::cleanupUnregisteredIndexFiles, 30, 30, TimeUnit.SECONDS); } @Override public PartitionOffsets fetchPartitionOffsets( int shuffleId, int mapId, long mapAttemptId, int reduceId) { if (cacheIndexFilesLocally) { MapOutputId id = new MapOutputId(shuffleId, mapId, mapAttemptId); fetchIndexFileToDisk(id); SeekableInput indexFileInput = localShuffleFs.getLocalSeekableIndexFile( shuffleId, mapId, mapAttemptId); BufferedSeekableInput bufferedIndexFileInput = new BufferedSeekableInput( indexFileInput, localFileBufferSize); return PartitionDecoder.decodePartitionOffsets(bufferedIndexFileInput, reduceId); } else { try { SeekableInput indexInput = remoteShuffleFs.getRemoteSeekableIndexFile( shuffleId, mapId, mapAttemptId); BufferedSeekableInput bufferedIndexInput = new BufferedSeekableInput( indexInput, shuffleDownloadBufferSize); return PartitionDecoder.decodePartitionOffsets(bufferedIndexInput, reduceId); } catch (IOException e) { throw new SafeRuntimeException( new SafeIoException( "Failed to decode partition offsets from remote storage.", e, SafeArg.of("shuffleId", shuffleId), SafeArg.of("mapId", mapId), SafeArg.of("mapAttemptId", mapAttemptId), SafeArg.of("reduceId", reduceId))); } } } private void fetchIndexFileToDisk(MapOutputId key) { if (localShuffleFs.doesLocalIndexFileExist(key.shuffleId(), key.mapId(), key.mapAttemptId())) { return; } fetchingIndexFiles.computeIfAbsent(key, id -> { int shuffleId = key.shuffleId(); int mapId = key.mapId(); long mapAttemptId = key.mapAttemptId(); if (!localShuffleFs.doesLocalIndexFileExist(shuffleId, mapId, mapAttemptId)) { AbortableOutputStream resolvedIndexOutput = null; try (InputStream remoteIndexInput = remoteShuffleFs.openRemoteIndexFile( shuffleId, mapId, mapAttemptId); AbortableOutputStream localIndexOutput = localShuffleFs.createLocalIndexFile( shuffleId, mapId, mapAttemptId)) { resolvedIndexOutput = localIndexOutput; IOUtils.copy(remoteIndexInput, localIndexOutput, shuffleDownloadBufferSize); } catch (IOException e) { if (resolvedIndexOutput != null) { resolvedIndexOutput.abort(e); } throw new SafeRuntimeException( new SafeIoException( "Failed to fetch index file from remote storage to local disk.", e, SafeArg.of("shuffleId", id.shuffleId()), SafeArg.of("mapId", id.mapId()), SafeArg.of("mapAttemptId", id.mapAttemptId()))); } } fetchedShuffleIds.add(key.shuffleId()); return true; }); fetchingIndexFiles.remove(key); } private void cleanupUnregisteredIndexFiles() { try { Iterator<Integer> fetchedShufflesIterator = fetchedShuffleIds.iterator(); while (fetchedShufflesIterator.hasNext()) { int shuffleId = fetchedShufflesIterator.next(); if (!driverEndpointRef.isShuffleRegistered(shuffleId)) { fetchedShufflesIterator.remove(); localShuffleFs.deleteDownloadedIndexFilesForShuffleId(shuffleId); } } } catch (Exception e) { LOG.warn("Failed to clean up unregistered index files.", e); } } }
. With aging there occurred a clear increase of the content of total water in several structures of the brain, most pronounced in the hypothalamus. The content of total water in the grey and white matter showed a reduction in the fronto-caudal direction both in the younger and older age groups though in the old this regularity was less pronounced. In the young the content of total water was higher in the structures of the anterior hypothalamus as compared with the posterior.
<filename>cas/apiv1/extension.go package apiv1 import ( "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "github.com/pkg/errors" ) var ( oidStepRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64} oidStepCertificateAuthority = append(asn1.ObjectIdentifier(nil), append(oidStepRoot, 2)...) ) // CertificateAuthorityExtension type is used to encode the certificate // authority extension. type CertificateAuthorityExtension struct { Type string CertificateID string `asn1:"optional,omitempty"` KeyValuePairs []string `asn1:"optional,omitempty"` } // CreateCertificateAuthorityExtension returns a X.509 extension that shows the // CAS type, id and a list of optional key value pairs. func CreateCertificateAuthorityExtension(typ Type, certificateID string, keyValuePairs ...string) (pkix.Extension, error) { b, err := asn1.Marshal(CertificateAuthorityExtension{ Type: typ.String(), CertificateID: certificateID, KeyValuePairs: keyValuePairs, }) if err != nil { return pkix.Extension{}, errors.Wrapf(err, "error marshaling certificate id extension") } return pkix.Extension{ Id: oidStepCertificateAuthority, Critical: false, Value: b, }, nil } // FindCertificateAuthorityExtension returns the certificate authority extension // from a signed certificate. func FindCertificateAuthorityExtension(cert *x509.Certificate) (pkix.Extension, bool) { for _, ext := range cert.Extensions { if ext.Id.Equal(oidStepCertificateAuthority) { return ext, true } } return pkix.Extension{}, false } // RemoveCertificateAuthorityExtension removes the certificate authority // extension from a certificate template. func RemoveCertificateAuthorityExtension(cert *x509.Certificate) { for i, ext := range cert.ExtraExtensions { if ext.Id.Equal(oidStepCertificateAuthority) { cert.ExtraExtensions = append(cert.ExtraExtensions[:i], cert.ExtraExtensions[i+1:]...) return } } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { RoleTemplate, StoredRoleTemplate, InlineRoleTemplate, InvalidRoleTemplate, } from '../../../../../../common/model'; export function isStoredRoleTemplate( roleMappingTemplate: RoleTemplate ): roleMappingTemplate is StoredRoleTemplate { return ( roleMappingTemplate.template != null && roleMappingTemplate.template.hasOwnProperty('id') && typeof ((roleMappingTemplate as unknown) as StoredRoleTemplate).template.id === 'string' ); } export function isInlineRoleTemplate( roleMappingTemplate: RoleTemplate ): roleMappingTemplate is InlineRoleTemplate { return ( roleMappingTemplate.template != null && roleMappingTemplate.template.hasOwnProperty('source') && typeof ((roleMappingTemplate as unknown) as InlineRoleTemplate).template.source === 'string' ); } export function isInvalidRoleTemplate( roleMappingTemplate: RoleTemplate ): roleMappingTemplate is InvalidRoleTemplate { return !isStoredRoleTemplate(roleMappingTemplate) && !isInlineRoleTemplate(roleMappingTemplate); }
Predictable stereoselective and chemoselective hydroxylations and epoxidations with P450 3A4. Enantioselective hydroxylation of one specific methylene in the presence of many similar groups is debatably the most challenging chemical transformation. Although chemists have recently made progress toward the hydroxylation of inactivated C-H bonds, enzymes such as P450s (CYPs) remain unsurpassed in specificity and scope. The substrate promiscuity of many P450s is desirable for synthetic applications; however, the inability to predict the products of these enzymatic reactions is impeding advancement. We demonstrate here the utility of a chemical auxiliary to control the selectivity of CYP3A4 reactions. When linked to substrates, inexpensive, achiral theobromine directs the reaction to produce hydroxylation or epoxidation at the fourth carbon from the auxiliary with pro-R facial selectivity. This strategy provides a versatile yet controllable system for regio-, chemo-, and stereoselective oxidations at inactivated C-H bonds and demonstrates the utility of chemical auxiliaries to mediate the activity of highly promiscuous enzymes.
<reponame>saiba/OpenBMLFlowVisualizer<gh_stars>0 package saiba.bmlflowvisualizer.demo; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.xml.transform.TransformerConfigurationException; import saiba.bmlflowvisualizer.BMLFlowVisualizerPort; import saiba.bmlflowvisualizer.transformed.GretaBMLFlowVisualizerPort; import asap.realizerport.BMLFeedbackListener; import asap.realizerport.RealizerPort; /** * Try out submitting BML + feedback through a UI * @author hvanwelbergen * */ public class BMLFlowVisualizerDemo { public static void main(String args[]) throws TransformerConfigurationException { JFrame jf = new JFrame("BMLFlowVisualizerDemo"); BMLFlowVisualizerPort realizerPort = new GretaBMLFlowVisualizerPort(new RealizerPort() { @Override public void addListeners(BMLFeedbackListener... listeners) { } @Override public void removeListener(BMLFeedbackListener l) { } @Override public void removeAllListeners() { } @Override public void performBML(String bmlString) { } }); jf.setLayout(new FlowLayout()); jf.add(realizerPort.getVisualization()); jf.add(new BMLAndFeedbackSubmissionUI(realizerPort,realizerPort).getPanel()); jf.setSize(1600,768); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } }
#pragma once #define WIN32_LEAN_AND_MEAN #include <Windows.h> class BlindGui { #ifdef _WIN32 //Windows def #define MAX_LOADSTRING 100 HINSTANCE hInst; // current instance WCHAR szTitle[MAX_LOADSTRING]; // The title bar text WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name HWND winID; // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); #else #endif #ifdef LINUX //SOONTM #endif #ifdef _WIN32 //Win32 def of windows form creation private: //Init the window, and get the HWND void Init(); public: BlindGui(); BlindGui(int wHeight, int wWidth); ~BlindGui(); //Direct cast to HWND operator HWND() { return winID; } //Get HWND : Returns the HWND for the window HWND GetHWND() { return winID; } #else #endif };
// Move src object to dst or fdst if nil. If dst is nil then it uses // remote as the name of the new object. // // Note that you must check the destination does not exist before // calling this and pass it as dst. If you pass dst=nil and the // destination does exist then this may create duplicates or return // errors. // // It returns the destination object if possible. Note that this may // be nil. func Move(ctx context.Context, fdst fs.Fs, dst fs.Object, remote string, src fs.Object) (newDst fs.Object, err error) { tr := accounting.Stats(ctx).NewCheckingTransfer(src) defer func() { if err == nil { accounting.Stats(ctx).Renames(1) } tr.Done(ctx, err) }() newDst = dst if SkipDestructive(ctx, src, "move") { in := tr.Account(ctx, nil) in.DryRun(src.Size()) return newDst, nil } if doMove := fdst.Features().Move; doMove != nil && (SameConfig(src.Fs(), fdst) || (SameRemoteType(src.Fs(), fdst) && fdst.Features().ServerSideAcrossConfigs)) { if dst != nil && !SameObject(src, dst) { err = DeleteFile(ctx, dst) if err != nil { return newDst, err } } newDst, err = doMove(ctx, src, remote) switch err { case nil: if newDst != nil && src.String() != newDst.String() { fs.Infof(src, "Moved (server-side) to: %s", newDst.String()) } else { fs.Infof(src, "Moved (server-side)") } return newDst, nil case fs.ErrorCantMove: fs.Debugf(src, "Can't move, switching to copy") default: err = fs.CountError(err) fs.Errorf(src, "Couldn't move: %v", err) return newDst, err } } newDst, err = Copy(ctx, fdst, dst, remote, src) if err != nil { fs.Errorf(src, "Not deleting source as copy failed: %v", err) return newDst, err } return newDst, DeleteFile(ctx, src) }
<reponame>jeffhammond/Elemental<filename>src/blas_like/level3/Trdtrmm/Unblocked.hpp /* Copyright (c) 2009-2016, <NAME> All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include <El/blas_like/level2.hpp> namespace El { namespace trdtrmm { template<typename F> void LUnblocked( Matrix<F>& L, bool conjugate=false ) { DEBUG_CSE DEBUG_ONLY( if( L.Height() != L.Width() ) LogicError("L must be square"); ) const Int n = L.Height(); const Int ldim = L.LDim(); Matrix<F> s10; for( Int k=0; k<n; ++k ) { auto L00 = L( IR(0,k), IR(0,k) ); auto l10 = L( IR(k), IR(0,k) ); // S10 := L10 s10 = l10; // L10 := L10 / delta11 const F deltaInv = F(1)/L.Get(k,k); l10 *= deltaInv; // L00 := L00 + l10' s10 const F* l10Buf = l10.LockedBuffer(); if( conjugate ) { for( Int j=0; j<k; ++j ) { F* L00Col = L00.Buffer(0,j); const F gamma = s10.Get(0,j); for( Int i=j; i<k; ++i ) L00Col[i] += Conj(l10Buf[i*ldim])*gamma; } } else { for( Int j=0; j<k; ++j ) { F* L00Col = L00.Buffer(0,j); const F gamma = s10.Get(0,j); for( Int i=j; i<k; ++i ) L00Col[i] += l10Buf[i*ldim]*gamma; } } // L11 := 1 / delta11 L.Set( k, k, deltaInv ); } } template<typename F> void LUnblocked( Matrix<F>& L, const Matrix<F>& dSub, bool conjugate=false ) { DEBUG_CSE DEBUG_ONLY( if( L.Height() != L.Width() ) LogicError("L must be square"); ) const Int n = L.Height(); const Int ldim = L.LDim(); const Orientation orientation = ( conjugate ? ADJOINT : TRANSPOSE ); Matrix<F> s10, S10, D11(2,2), D11Inv(2,2); Int k=0; while( k < n ) { const Int nb = ( k<n-1 && dSub.Get(k,0) != F(0) ? 2 : 1 ); if( nb == 1 ) { auto L00 = L( IR(0,k), IR(0,k) ); auto l10 = L( IR(k,k+nb), IR(0,k) ); // S10 := L10 s10 = l10; // L10 := L10 / delta11 const F deltaInv = F(1)/L.Get(k,k); l10 *= deltaInv; // L00 := L00 + l10' s10 // TODO: Extend Trr for this case and then switch const F* l10Buf = l10.LockedBuffer(); if( conjugate ) { for( Int j=0; j<k; ++j ) { F* L00Col = L00.Buffer(0,j); const F gamma = s10.Get(0,j); for( Int i=j; i<k; ++i ) L00Col[i] += Conj(l10Buf[i*ldim])*gamma; } } else { for( Int j=0; j<k; ++j ) { F* L00Col = L00.Buffer(0,j); const F gamma = s10.Get(0,j); for( Int i=j; i<k; ++i ) L00Col[i] += l10Buf[i*ldim]*gamma; } } // lambda11 := 1 / delta11 L.Set( k, k, deltaInv ); } else { auto L00 = L( IR(0,k), IR(0,k) ); auto L10 = L( IR(k,k+nb), IR(0,k) ); auto L11 = L( IR(k,k+nb), IR(k,k+nb) ); // S10 := L10 S10 = L10; // L10 := inv(D11) L10 D11.Set( 0, 0, L11.Get(0,0) ); D11.Set( 1, 1, L11.Get(1,1) ); D11.Set( 1, 0, dSub.Get(k,0) ); D11Inv = D11; Symmetric2x2Inv( LOWER, D11Inv, conjugate ); MakeSymmetric( LOWER, D11Inv, conjugate ); Transform2x2Rows( D11Inv, L10, 0, 1 ); // L00 := L00 + L10' S10 // TODO: Custom rank-2 update Trrk( LOWER, orientation, NORMAL, F(1), L10, S10, F(1), L00 ); // L11 := inv(D11) L11.Set( 0, 0, D11Inv.Get(0,0) ); L11.Set( 1, 0, D11Inv.Get(1,0) ); L11.Set( 1, 1, D11Inv.Get(1,1) ); } k += nb; } } template<typename F> void UUnblocked( Matrix<F>& U, bool conjugate=false ) { DEBUG_CSE DEBUG_ONLY( if( U.Height() != U.Width() ) LogicError("U must be square"); ) const Int n = U.Height(); Matrix<F> s01; for( Int k=0; k<n; ++k ) { auto U00 = U( IR(0,k), IR(0,k) ); auto u01 = U( IR(0,k), IR(k) ); s01 = u01; // u01 := u01 / delta11 const F deltaInv = F(1)/U.Get(k,k); u01 *= deltaInv; // U00 := U00 + s01 u01' Trr( UPPER, F(1), s01, u01, U00, conjugate ); // lambda11 := 1 / delta11 U.Set( k, k, deltaInv ); } } } // namespace trdtrmm } // namespace El
def recompute_from_res(labels, result, vol= None, volfns=None, dprc='full', fp='', mode='3d', neuroglancer=False, em_path=None): print('\nStarting to relabel the mask with the results from the clustering results.') if dprc == 'full': if mode == '2d': cld_labels = np.zeros(shape=labels.shape) for r in range(labels.shape[0]): tmp = labels[r] for idx in range(np.amin(tmp[np.nonzero(tmp)]), np.amax(tmp) + 1): tmp[tmp == idx] = result[idx - 1] + 1 cld_labels[r] = tmp else: ldict = {} for k, v in zip(labels, result): ldict[k] = v + 1 k = np.array(list(ldict.keys())) v = np.array(list(ldict.values())) mapv = np.zeros(k.max() + 1) mapv[k] = v cld_labels = mapv[vol] elif dprc == 'iter': ldict = {} for k, v in zip(labels, result): ldict[k] = v + 1 k = np.array(list(ldict.keys())) v = np.array(list(ldict.values())) if neuroglancer: emfns = glob.glob(em_path+"*.png") recompute_from_res_per_slice_h5(volfns, emfns, k=k, v=v, fp=fp) else: with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as pool: pool.starmap(functools.partial(recompute_from_res_per_slice, k=k, v=v, fp=fp), enumerate(volfns)) cld_labels = 0 else: raise ValueError('No valid data processing option choosen. Please choose \'full\' or \'iter\'.') print('Relabeling of the mask is done.\n') return cld_labels
/** * DTO para listar os certificados na API */ @Data @NoArgsConstructor @AllArgsConstructor public class CertificateDto { private String hash; private long chainIndex; private ZonedDateTime expiration; private long startPulseIndex; private long endPulseIndex; }
def read_input_files( fasta_file_list: str, hmms_file_list: str ): fasta_file_list = [i.strip('\n').split('\t') for i in open(fasta_file_list)] hmms_file_list = [i.strip('\n').split('\t') for i in open(hmms_file_list)] return fasta_file_list, hmms_file_list
<reponame>nehasingh97/pythonscript-togetotp<gh_stars>0 from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(executable_path="./chromedriver") driver.get("https://www.easemytrip.com/hotels/") driver.implicitly_wait(5) driver.maximize_window() # driver.find_element_by_xpath("//*[@id="myTopnav"]/div[1]/ul/li[2]/a").click() # driver.find_element_by_id("mainlogin").click() time.sleep(3) driver.find_element_by_id("txtCity").send_keys=("Delhi") driver.find_element_by_id("txtCheckInDate").send_keys("21 July,2021") driver.find_element_by_id("txtCheckOutDate").send_keys("22 July,2021") print(driver.title)