Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Reorder BrowserProcess constructor to avoid invalid memory
// Copyright (c) 2012 The Chromium 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 "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" #include "ui/base/l10n/l10n_util.h" BrowserProcess* g_browser_process = NULL; BrowserProcess::BrowserProcess() { g_browser_process = this; print_job_manager_.reset(new printing::PrintJobManager); } BrowserProcess::~BrowserProcess() { g_browser_process = NULL; } std::string BrowserProcess::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } printing::PrintJobManager* BrowserProcess::print_job_manager() { return print_job_manager_.get(); }
// Copyright (c) 2012 The Chromium 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 "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" #include "ui/base/l10n/l10n_util.h" BrowserProcess* g_browser_process = NULL; BrowserProcess::BrowserProcess() : print_job_manager_(new printing::PrintJobManager) { g_browser_process = this; } BrowserProcess::~BrowserProcess() { g_browser_process = NULL; } std::string BrowserProcess::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } printing::PrintJobManager* BrowserProcess::print_job_manager() { return print_job_manager_.get(); }
Set sanity threshold for TVL1 optical flow to 0.5
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; typedef TestBaseWithParam< pair<string, string> > ImagePair; pair<string, string> impair(const char* im1, const char* im2) { return make_pair(string(im1), string(im2)); } PERF_TEST_P(ImagePair, OpticalFlowDual_TVL1, testing::Values(impair("cv/optflow/RubberWhale1.png", "cv/optflow/RubberWhale2.png"))) { declare.time(40); Mat frame1 = imread(getDataPath(GetParam().first), IMREAD_GRAYSCALE); Mat frame2 = imread(getDataPath(GetParam().second), IMREAD_GRAYSCALE); ASSERT_FALSE(frame1.empty()); ASSERT_FALSE(frame2.empty()); Mat flow; OpticalFlowDual_TVL1 tvl1; TEST_CYCLE() { tvl1(frame1, frame2, flow); } SANITY_CHECK(flow, 0.02); }
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; typedef TestBaseWithParam< pair<string, string> > ImagePair; pair<string, string> impair(const char* im1, const char* im2) { return make_pair(string(im1), string(im2)); } PERF_TEST_P(ImagePair, OpticalFlowDual_TVL1, testing::Values(impair("cv/optflow/RubberWhale1.png", "cv/optflow/RubberWhale2.png"))) { declare.time(40); Mat frame1 = imread(getDataPath(GetParam().first), IMREAD_GRAYSCALE); Mat frame2 = imread(getDataPath(GetParam().second), IMREAD_GRAYSCALE); ASSERT_FALSE(frame1.empty()); ASSERT_FALSE(frame2.empty()); Mat flow; OpticalFlowDual_TVL1 tvl1; TEST_CYCLE() { tvl1(frame1, frame2, flow); } SANITY_CHECK(flow, 0.5); }
Fix byte order when writing CAN messages on LPC17xx.
#include "bitfield.h" #include "canutil_lpc17xx.h" #include "canutil.h" #include "canwrite.h" #include "log.h" #include <stdbool.h> void copyToMessageBuffer(uint64_t source, uint8_t* a, uint8_t* b) { for(int i = 0, j = 4; i < 3 && j < 8; i++, j++) { a[i] = nthByte(source, i); b[i] = nthByte(source, j); } } bool sendCanMessage(CanBus* bus, CanMessage request) { CAN_MSG_Type message; message.id = request.id; message.len = 8; message.type = DATA_FRAME; message.format = STD_ID_FORMAT; copyToMessageBuffer(request.data, message.dataA, message.dataB); return CAN_SendMsg(CAN_CONTROLLER(bus), &message) == SUCCESS; }
#include "bitfield.h" #include "canutil_lpc17xx.h" #include "canutil.h" #include "canwrite.h" #include "log.h" #include <stdbool.h> void copyToMessageBuffer(uint64_t source, uint8_t* a, uint8_t* b) { for(int i = 0, j = 4; i < 4 && j < 8; i++, j++) { a[3 - i] = nthByte(source, j); b[3 - i] = nthByte(source, i); } } bool sendCanMessage(CanBus* bus, CanMessage request) { CAN_MSG_Type message; message.id = request.id; message.len = 8; message.type = DATA_FRAME; message.format = STD_ID_FORMAT; copyToMessageBuffer(request.data, message.dataA, message.dataB); return CAN_SendMsg(CAN_CONTROLLER(bus), &message) == SUCCESS; }
Fix test to test the right thing.
// RUN: %clang_cc1 -fsyntax-only -Wconditional-uninitialized -fsyntax-only %s -verify class Foo { public: Foo(); ~Foo(); operator bool(); }; int bar(); int baz(); int init(double *); // This case flags a false positive under -Wconditional-uninitialized because // the destructor in Foo fouls about the minor bit of path-sensitivity in // -Wuninitialized. double test() { double x; // expected-note {{variable 'x' is declared here}} expected-note{{add initialization to silence this warning}} if (bar() || baz() || Foo() || init(&x)) { return x; // expected-warning {{variable 'x' is possibly uninitialized when used here}} } return 1.0; }
// RUN: %clang_cc1 -fsyntax-only -Wconditional-uninitialized -fsyntax-only %s -verify class Foo { public: Foo(); ~Foo(); operator bool(); }; int bar(); int baz(); int init(double *); // This case flags a false positive under -Wconditional-uninitialized because // the destructor in Foo fouls about the minor bit of path-sensitivity in // -Wuninitialized. double test() { double x; // expected-note {{variable 'x' is declared here}} expected-note{{add initialization to silence this warning}} if (bar() || baz() || Foo() || init(&x)) return 1.0; return x; // expected-warning {{variable 'x' is possibly uninitialized when used here}} }
Enable HiDPI for the demo app.
#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include <QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
Fix a tiny bug in my test case in r335309 by marking that we don't expect any diagnostics.
// RUN: %clang_cc1 -triple=x86_64-apple-darwin -fsyntax-only -verify %s // // Ensure that when we use builtins in C++ code with templates that compute the // valid immediate, the dead code with the invalid immediate doesn't error. typedef short __v8hi __attribute__((__vector_size__(16))); template <int Imm> __v8hi test(__v8hi a) { if (Imm < 4) return __builtin_ia32_pshuflw(a, 0x55 * Imm); else return __builtin_ia32_pshuflw(a, 0x55 * (Imm - 4)); } template __v8hi test<0>(__v8hi); template __v8hi test<1>(__v8hi); template __v8hi test<2>(__v8hi); template __v8hi test<3>(__v8hi); template __v8hi test<4>(__v8hi); template __v8hi test<5>(__v8hi); template __v8hi test<6>(__v8hi); template __v8hi test<7>(__v8hi);
// RUN: %clang_cc1 -triple=x86_64-apple-darwin -fsyntax-only -verify %s // // Ensure that when we use builtins in C++ code with templates that compute the // valid immediate, the dead code with the invalid immediate doesn't error. // expected-no-diagnostics typedef short __v8hi __attribute__((__vector_size__(16))); template <int Imm> __v8hi test(__v8hi a) { if (Imm < 4) return __builtin_ia32_pshuflw(a, 0x55 * Imm); else return __builtin_ia32_pshuflw(a, 0x55 * (Imm - 4)); } template __v8hi test<0>(__v8hi); template __v8hi test<1>(__v8hi); template __v8hi test<2>(__v8hi); template __v8hi test<3>(__v8hi); template __v8hi test<4>(__v8hi); template __v8hi test<5>(__v8hi); template __v8hi test<6>(__v8hi); template __v8hi test<7>(__v8hi);
Add test case from PR5763
// RUN: %clang_cc1 -fsyntax-only -verify %s class Base { }; class Derived1 : public Base { }; class Derived2 : public Base { }; void f0(volatile Base *b, Derived1 *d1, const Derived2 *d2) { if (b > d1) return; if (d1 <= b) return; if (b > d2) return; if (d1 >= d2) // expected-error{{comparison of distinct}} return; } void f1(volatile Base *b, Derived1 *d1, const Derived2 *d2) { if (b == d1) return; if (d1 == b) return; if (b != d2) return; if (d1 == d2) // expected-error{{comparison of distinct}} return; } // PR4691 int ptrcmp1(void *a, int *b) { return a < b; } int ptrcmp2(long *a, int *b) { return a < b; // expected-error{{distinct}} } // PR5509 - Multi-level pointers int f2() { typedef int *IntPtr; typedef IntPtr *IntPtrPtr; typedef IntPtr const *IntPtrConstPtr; IntPtrConstPtr i = 0; IntPtrPtr j = 0; return i != j; }
// RUN: %clang_cc1 -fsyntax-only -verify %s class Base { }; class Derived1 : public Base { }; class Derived2 : public Base { }; void f0(volatile Base *b, Derived1 *d1, const Derived2 *d2) { if (b > d1) return; if (d1 <= b) return; if (b > d2) return; if (d1 >= d2) // expected-error{{comparison of distinct}} return; } void f1(volatile Base *b, Derived1 *d1, const Derived2 *d2) { if (b == d1) return; if (d1 == b) return; if (b != d2) return; if (d1 == d2) // expected-error{{comparison of distinct}} return; } // PR4691 int ptrcmp1(void *a, int *b) { return a < b; } int ptrcmp2(long *a, int *b) { return a < b; // expected-error{{distinct}} } // PR5509 - Multi-level pointers int f2() { typedef int *IntPtr; typedef IntPtr *IntPtrPtr; typedef IntPtr const *IntPtrConstPtr; IntPtrConstPtr i = 0; IntPtrPtr j = 0; return i != j; } // PR5763 typedef double Matrix4[4][4]; bool f(Matrix4 m1, const Matrix4 m2) { return m1 != m2; }
Remove roundf from test because windows
#include <Halide.h> #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Func f; Var x; ImageParam input(Float(32), 1); f(x) = input(cast<int>(round(0.3f * ceil(0.4f * floor(x * 22.5f))))); f.infer_input_bounds(10); Image<float> in = input.get(); int correct = roundf(0.3f * ceilf(0.4f * floorf(9 * 22.5f))) + 1; if (in.width() != correct) { printf("Width is %d instead of %d\n", in.width(), correct); return -1; } printf("Success!\n"); return 0; }
#include <Halide.h> #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Func f; Var x; ImageParam input(Float(32), 1); f(x) = input(cast<int>(ceil(0.3f * ceil(0.4f * floor(x * 22.5f))))); f.infer_input_bounds(10); Image<float> in = input.get(); int correct = 26; if (in.width() != correct) { printf("Width is %d instead of %d\n", in.width(), correct); return -1; } printf("Success!\n"); return 0; }
Put back the extensions display.
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <iostream> #include <mipp.h> int main(int argc, char* argv[]) { std::cout << "MIPP tests" << std::endl; std::cout << "----------" << std::endl << std::endl; std::cout << "Instr. type: " << mipp::InstructionType << std::endl; std::cout << "Instr. full type: " << mipp::InstructionFullType << std::endl; std::cout << "Instr. version: " << mipp::InstructionVersion << std::endl; std::cout << "Instr. size: " << mipp::RegisterSizeBit << " bits" << std::endl; std::cout << "Instr. lanes: " << mipp::Lanes << std::endl; std::cout << "64-bit support: " << (mipp::Support64Bit ? "yes" : "no") << std::endl; std::cout << "Byte/word support: " << (mipp::SupportByteWord ? "yes" : "no") << std::endl; std::cout << std::endl; int result = Catch::Session().run(argc, argv); return result; }
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <iostream> #include <mipp.h> int main(int argc, char* argv[]) { std::cout << "MIPP tests" << std::endl; std::cout << "----------" << std::endl << std::endl; std::cout << "Instr. type: " << mipp::InstructionType << std::endl; std::cout << "Instr. full type: " << mipp::InstructionFullType << std::endl; std::cout << "Instr. version: " << mipp::InstructionVersion << std::endl; std::cout << "Instr. size: " << mipp::RegisterSizeBit << " bits" << std::endl; std::cout << "Instr. lanes: " << mipp::Lanes << std::endl; std::cout << "64-bit support: " << (mipp::Support64Bit ? "yes" : "no") << std::endl; std::cout << "Byte/word support: " << (mipp::SupportByteWord ? "yes" : "no") << std::endl; auto ext = mipp::InstructionExtensions(); if (ext.size() > 0) { std::cout << "Instr. extensions: {"; for (auto i = 0; i < (int)ext.size(); i++) std::cout << ext[i] << (i < ((int)ext.size() -1) ? ", " : ""); std::cout << "}" << std::endl; } std::cout << std::endl; int result = Catch::Session().run(argc, argv); return result; }
Fix members of StatisticsWriter not being initialized
// Copyright (c) 2013, Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <ctime> #include <iostream> #include <vector> #include "statistics_writer.h" namespace amx_profiler { StatisticsWriter::StatisticsWriter() : print_date_(false) { } } // namespace amx_profiler
// Copyright (c) 2013, Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <ctime> #include <iostream> #include <vector> #include "statistics_writer.h" namespace amx_profiler { StatisticsWriter::StatisticsWriter() : stream_(0) , print_date_(false) , print_run_time_(false) { } } // namespace amx_profiler
Stop trying to compare arrays (deprecated in C++20)
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> using namespace vespalib; void testDebug() { TEST_DEBUG("lhs.out", "rhs.out"); EXPECT_EQUAL("a\n" "b\n" "c\n", "a\n" "b\n" "c\n" "d\n"); EXPECT_EQUAL("a\n" "d\n" "b\n" "c\n", "a\n" "b\n" "c\n" "d\n"); EXPECT_EQUAL(1, 2); EXPECT_EQUAL("foo", "bar"); } TEST_MAIN() { testDebug(); }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> using namespace vespalib; void testDebug() { TEST_DEBUG("lhs.out", "rhs.out"); EXPECT_EQUAL(string("a\n" "b\n" "c\n"), string("a\n" "b\n" "c\n" "d\n")); EXPECT_EQUAL(string("a\n" "d\n" "b\n" "c\n"), string("a\n" "b\n" "c\n" "d\n")); EXPECT_EQUAL(1, 2); EXPECT_EQUAL(string("foo"), string("bar")); } TEST_MAIN() { testDebug(); }
Use the correct VariationsRequestScheduler on iOS.
// Copyright (c) 2013 The Chromium 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 "chrome/browser/metrics/variations/variations_request_scheduler.h" namespace chrome_variations { namespace { // Time between seed fetches, in hours. const int kSeedFetchPeriodHours = 5; } // namespace VariationsRequestScheduler::VariationsRequestScheduler( const base::Closure& task) : task_(task) { } VariationsRequestScheduler::~VariationsRequestScheduler() { } void VariationsRequestScheduler::Start() { // Call the task and repeat it periodically. task_.Run(); timer_.Start(FROM_HERE, base::TimeDelta::FromHours(kSeedFetchPeriodHours), task_); } void VariationsRequestScheduler::Reset() { if (timer_.IsRunning()) timer_.Reset(); } base::Closure VariationsRequestScheduler::task() const { return task_; } #if !defined(OS_ANDROID) // static VariationsRequestScheduler* VariationsRequestScheduler::Create( const base::Closure& task, PrefService* local_state) { return new VariationsRequestScheduler(task); } #endif // !defined(OS_ANDROID) } // namespace chrome_variations
// Copyright (c) 2013 The Chromium 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 "chrome/browser/metrics/variations/variations_request_scheduler.h" namespace chrome_variations { namespace { // Time between seed fetches, in hours. const int kSeedFetchPeriodHours = 5; } // namespace VariationsRequestScheduler::VariationsRequestScheduler( const base::Closure& task) : task_(task) { } VariationsRequestScheduler::~VariationsRequestScheduler() { } void VariationsRequestScheduler::Start() { // Call the task and repeat it periodically. task_.Run(); timer_.Start(FROM_HERE, base::TimeDelta::FromHours(kSeedFetchPeriodHours), task_); } void VariationsRequestScheduler::Reset() { if (timer_.IsRunning()) timer_.Reset(); } base::Closure VariationsRequestScheduler::task() const { return task_; } #if !defined(OS_ANDROID) && !defined(OS_IOS) // static VariationsRequestScheduler* VariationsRequestScheduler::Create( const base::Closure& task, PrefService* local_state) { return new VariationsRequestScheduler(task); } #endif // !defined(OS_ANDROID) && !defined(OS_IOS) } // namespace chrome_variations
Rename unit test: WebViewTest.GetContentAsPlainText -> WebViewTest.ActiveState.
// Copyright (c) 2006-2008 The Chromium 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 "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebView; class WebViewTest : public TestShellTest { }; TEST_F(WebViewTest, GetContentAsPlainText) { WebView* view = test_shell_->webView(); ASSERT_TRUE(view != 0); view->setIsActive(true); EXPECT_TRUE(view->isActive()); view->setIsActive(false); EXPECT_FALSE(view->isActive()); view->setIsActive(true); EXPECT_TRUE(view->isActive()); } // TODO(viettrungluu): add more tests
// Copyright (c) 2006-2008 The Chromium 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 "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebView; class WebViewTest : public TestShellTest { }; TEST_F(WebViewTest, ActiveState) { WebView* view = test_shell_->webView(); ASSERT_TRUE(view != 0); view->setIsActive(true); EXPECT_TRUE(view->isActive()); view->setIsActive(false); EXPECT_FALSE(view->isActive()); view->setIsActive(true); EXPECT_TRUE(view->isActive()); } // TODO(viettrungluu): add more tests
Fix incorrect column numbers in test from r350282.
// RUN: c-index-test -test-load-source all -c %s -fsyntax-only -target x86_64-apple-darwin9 -fcoroutines-ts -std=c++1z -I%S/../SemaCXX/Inputs | FileCheck %s #include "std-coroutine.h" using std::experimental::suspend_always; using std::experimental::suspend_never; struct promise_void { void get_return_object(); suspend_always initial_suspend(); suspend_always final_suspend(); void return_void(); void unhandled_exception(); }; template <> struct std::experimental::coroutine_traits<void> { using promise_type = promise_void; }; void CoroutineTestRet() { co_return; } // CHECK: [[@LINE-3]]:25: UnexposedStmt= // CHECK-SAME: [[@LINE-4]]:25 - [[@LINE-2]]:2] // CHECK: [[@LINE-4]]:5: UnexposedStmt= // CHECK-SAME: [[@LINE-5]]:5 - [[@LINE-5]]:14]
// RUN: c-index-test -test-load-source all -c %s -fsyntax-only -target x86_64-apple-darwin9 -fcoroutines-ts -std=c++1z -I%S/../SemaCXX/Inputs | FileCheck %s #include "std-coroutine.h" using std::experimental::suspend_always; using std::experimental::suspend_never; struct promise_void { void get_return_object(); suspend_always initial_suspend(); suspend_always final_suspend(); void return_void(); void unhandled_exception(); }; template <> struct std::experimental::coroutine_traits<void> { using promise_type = promise_void; }; void CoroutineTestRet() { co_return; } // CHECK: [[@LINE-3]]:25: UnexposedStmt= // CHECK-SAME: [[@LINE-4]]:25 - [[@LINE-2]]:2] // CHECK: [[@LINE-4]]:3: UnexposedStmt= // CHECK-SAME: [[@LINE-5]]:3 - [[@LINE-5]]:12]
Configure entityx systems after init
#include "main_state.hpp" #include "system_movement.hpp" #include "system_draw.hpp" #include "entityx/entityx.h" #include <SDL2/SDL.h> MainState::MainState(Game *game) : m_game(game) {} MainState::~MainState(){} int MainState::init() { m_systems.add<MovementSystem>(); m_systems.add<DrawSystem>(m_game); return 0; } void MainState::update(double dt) { SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { m_game->shutdown(); } if (e.type == SDL_KEYDOWN) { if(e.key.keysym.sym == SDLK_ESCAPE) { m_game->shutdown(); } } } SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); SDL_RenderClear(m_game->get_renderer()); SDL_RenderPresent(m_game->get_renderer()); m_systems.update<MovementSystem>(dt); m_systems.update<DrawSystem>(dt); }
#include "main_state.hpp" #include "system_movement.hpp" #include "system_draw.hpp" #include "entityx/entityx.h" #include <SDL2/SDL.h> MainState::MainState(Game *game) : m_game(game) {} MainState::~MainState(){} int MainState::init() { m_systems.add<MovementSystem>(); m_systems.add<DrawSystem>(m_game); m_systems.configure(); return 0; } void MainState::update(double dt) { SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { m_game->shutdown(); } if (e.type == SDL_KEYDOWN) { if(e.key.keysym.sym == SDLK_ESCAPE) { m_game->shutdown(); } } } SDL_SetRenderDrawColor(m_game->get_renderer(), 0, 100, 200, 255); SDL_RenderClear(m_game->get_renderer()); SDL_RenderPresent(m_game->get_renderer()); m_systems.update<MovementSystem>(dt); m_systems.update<DrawSystem>(dt); }
Enable pragma for SIMD also when _OPENMP is defined
/////////////////////////////////////////////////////////////////////// // File: dotproduct.h // Description: Native dot product function. // // (C) Copyright 2018, Google 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. /////////////////////////////////////////////////////////////////////// #include "dotproduct.h" namespace tesseract { // Computes and returns the dot product of the two n-vectors u and v. double DotProductNative(const double *u, const double *v, int n) { double total = 0.0; #if defined(OPENMP_SIMD) #pragma omp simd reduction(+:total) #endif for (int k = 0; k < n; ++k) { total += u[k] * v[k]; } return total; } } // namespace tesseract
/////////////////////////////////////////////////////////////////////// // File: dotproduct.h // Description: Native dot product function. // // (C) Copyright 2018, Google 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. /////////////////////////////////////////////////////////////////////// #include "dotproduct.h" namespace tesseract { // Computes and returns the dot product of the two n-vectors u and v. double DotProductNative(const double *u, const double *v, int n) { double total = 0.0; #if defined(OPENMP_SIMD) || defined(_OPENMP) #pragma omp simd reduction(+:total) #endif for (int k = 0; k < n; ++k) { total += u[k] * v[k]; } return total; } } // namespace tesseract
Add funtionality to match in files
// This is the starting point // #include <iostream> int main() { std::string greeting("Welcome to RGrep-CPP"); std::cout << greeting << std::endl; std::string firstInputString; std::string secondInputString; std::cout << "Enter the first string" << std::endl; std::cin >> firstInputString; std::cout << "Enter the second string" << std::endl; std::cin >> secondInputString; if (firstInputString == secondInputString) { std::cout << "Match!" << std::endl; } return 0; }
// This is the starting point // #include <iostream> #include <fstream> #include <sstream> int main() { std::string greeting("Welcome to RGrep-CPP"); std::cout << greeting << std::endl; std::string firstInputString; std::string secondInputString; std::cout << "Enter the first string" << std::endl; std::cin >> firstInputString; std::cout << "Enter the second string" << std::endl; std::cin >> secondInputString; if (firstInputString == secondInputString) { std::cout << "Match!" << std::endl; } std::string fileName; std::cout << "Enter a filename in which to look for the string" << std::endl; std::cin >> fileName; std::ifstream fileInputStream(fileName); std::string line; if (fileInputStream.is_open()) { std::cout << "Successfully opened " << fileName << std::endl; while(true) { if (fileInputStream.fail()) { std::cout << "The file input stream went into an error state" << std::endl; break; } getline(fileInputStream, line); std::cout << line << std::endl; if (firstInputString == line) { std::cout << "Match!" << std::endl; } } } else { std::cout << "Could not open file for reading" << std::endl; } return 0; }
Correct the dynamic lib suffix on Darwin.
//===- llvm/System/Darwin/Path.cpp - Linux Path Implementation --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the Darwin specific implementation of the Path class. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only Darwin specific code //=== and must not be generic UNIX code (see ../Unix/Path.cpp) //===----------------------------------------------------------------------===// // Include the generic unix implementation #include "../Unix/Path.cpp" namespace llvm { using namespace sys; bool Path::is_valid() const { if (path.empty()) return false; if (path.length() >= MAXPATHLEN) return false; return true; } Path Path::GetTemporaryDirectory() { char pathname[MAXPATHLEN]; strcpy(pathname,"/tmp/llvm_XXXXXX"); if (0 == mkdtemp(pathname)) ThrowErrno(std::string(pathname) + ": Can't create temporary directory"); Path result; result.set_directory(pathname); assert(result.is_valid() && "mkdtemp didn't create a valid pathname!"); return result; } std::string Path::GetDLLSuffix() { return "dyld"; } } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
//===- llvm/System/Darwin/Path.cpp - Linux Path Implementation --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the Darwin specific implementation of the Path class. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only Darwin specific code //=== and must not be generic UNIX code (see ../Unix/Path.cpp) //===----------------------------------------------------------------------===// // Include the generic unix implementation #include "../Unix/Path.cpp" namespace llvm { using namespace sys; bool Path::is_valid() const { if (path.empty()) return false; if (path.length() >= MAXPATHLEN) return false; return true; } Path Path::GetTemporaryDirectory() { char pathname[MAXPATHLEN]; strcpy(pathname,"/tmp/llvm_XXXXXX"); if (0 == mkdtemp(pathname)) ThrowErrno(std::string(pathname) + ": Can't create temporary directory"); Path result; result.set_directory(pathname); assert(result.is_valid() && "mkdtemp didn't create a valid pathname!"); return result; } std::string Path::GetDLLSuffix() { return "dylib"; } } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
Enforce focus for the line edit.
/* * DialogPassword.cpp * * Created on: 01.01.2017 * Author: felix */ #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QVBoxLayout> #include <frontend/DialogPassword.h> namespace Flix { DialogPassword::DialogPassword(QWidget *parent, Qt::WindowFlags flags): QDialog(parent, flags) { setWindowTitle(tr("Password dialog")); initLayout(); } DialogPassword::~DialogPassword() { } QString DialogPassword::getPassword(void) const { return editPassword->text(); } void DialogPassword::initLayout(void) { QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(new QLabel(tr("Please enter the password") + ":")); editPassword = new QLineEdit(); editPassword->setEchoMode(QLineEdit::EchoMode::Password); layout->addWidget(editPassword); QHBoxLayout* layoutDialogButtons = new QHBoxLayout(); buttonOk = new QPushButton(tr("OK")); connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept())); layoutDialogButtons->addWidget(buttonOk); buttonCancel = new QPushButton(tr("Cancel")); connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject())); layoutDialogButtons->addWidget(buttonCancel); layout->addLayout(layoutDialogButtons); } } /* namespace Flix */
/* * DialogPassword.cpp * * Created on: 01.01.2017 * Author: felix */ #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QVBoxLayout> #include <frontend/DialogPassword.h> namespace Flix { DialogPassword::DialogPassword(QWidget *parent, Qt::WindowFlags flags): QDialog(parent, flags) { setWindowTitle(tr("Password dialog")); initLayout(); } DialogPassword::~DialogPassword() { } QString DialogPassword::getPassword(void) const { return editPassword->text(); } void DialogPassword::initLayout(void) { QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(new QLabel(tr("Please enter the password") + ":")); editPassword = new QLineEdit(); editPassword->setEchoMode(QLineEdit::EchoMode::Password); layout->addWidget(editPassword); QHBoxLayout* layoutDialogButtons = new QHBoxLayout(); buttonOk = new QPushButton(tr("OK")); connect(buttonOk, SIGNAL(clicked()), this, SLOT(accept())); layoutDialogButtons->addWidget(buttonOk); buttonCancel = new QPushButton(tr("Cancel")); connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject())); layoutDialogButtons->addWidget(buttonCancel); layout->addLayout(layoutDialogButtons); editPassword->setFocus(); } } /* namespace Flix */
Remove a test FIXME for a case which is already fixed.
// RUN: %clang_cc1 -std=c++11 -verify %s using size_t = decltype(sizeof(int)); void operator "" wibble(const char *); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} void operator "" wibble(const char *, size_t); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} template<typename T> void f() { // A program containing a reserved ud-suffix is ill-formed. // FIXME: Reject these for the right reason. 123wibble; // expected-error {{suffix 'wibble'}} 123.0wibble; // expected-error {{suffix 'wibble'}} const char *p = ""wibble; // expected-error {{invalid suffix on literal; C++11 requires a space between literal and identifier}} expected-error {{expected ';'}} const char *q = R"x("hello")x"wibble; // expected-error {{invalid suffix on literal; C++11 requires a space between literal and identifier}} expected-error {{expected ';'}} }
// RUN: %clang_cc1 -std=c++11 -verify %s using size_t = decltype(sizeof(int)); void operator "" wibble(const char *); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} void operator "" wibble(const char *, size_t); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} template<typename T> void f() { // A program containing a reserved ud-suffix is ill-formed. 123wibble; // expected-error {{invalid suffix 'wibble'}} 123.0wibble; // expected-error {{invalid suffix 'wibble'}} const char *p = ""wibble; // expected-error {{invalid suffix on literal; C++11 requires a space between literal and identifier}} expected-error {{expected ';'}} const char *q = R"x("hello")x"wibble; // expected-error {{invalid suffix on literal; C++11 requires a space between literal and identifier}} expected-error {{expected ';'}} }
Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ struct GrGLInterface; const GrGLInterface* GrGLDefaultInterface() { return NULL; }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLInterface.h" const GrGLInterface* GrGLDefaultInterface() { return NULL; }
Return the open callback function pointer so it can be freed on the Haskell side.
{-# LANGUAGE CPP, FlexibleContexts #-} module Graphics.UI.FLTK.LowLevel.X (flcOpenDisplay, flcXid, openCallback) where import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Hierarchy import Graphics.UI.FLTK.LowLevel.Dispatch import Graphics.UI.FLTK.LowLevel.Utils import Foreign.Ptr import qualified Data.Text as T #include "Fl_C.h" #include "xC.h" {# fun flc_open_display as flcOpenDisplay {} -> `()' #} {# fun flc_xid as flcXid' {`Ptr ()'} -> `Ptr ()' #} flcXid :: (Parent a WindowBase) => Ref a -> IO (Maybe WindowHandle) flcXid win = withRef win ( \winPtr -> do res <- flcXid' winPtr if (res == nullPtr) then return Nothing else return (Just (WindowHandle res)) ) {# fun flc_open_callback as openCallback' { id `FunPtr OpenCallbackPrim' } -> `()' #} openCallback :: Maybe OpenCallback -> IO () openCallback Nothing = openCallback' nullFunPtr openCallback (Just cb) = do ptr <- mkOpenCallbackPtr $ \cstr -> do txt <- cStringToText cstr cb txt openCallback' ptr
{-# LANGUAGE CPP, FlexibleContexts #-} module Graphics.UI.FLTK.LowLevel.X (flcOpenDisplay, flcXid, openCallback) where import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Hierarchy import Graphics.UI.FLTK.LowLevel.Dispatch import Graphics.UI.FLTK.LowLevel.Utils import Foreign.Ptr #include "Fl_C.h" #include "xC.h" {# fun flc_open_display as flcOpenDisplay {} -> `()' #} {# fun flc_xid as flcXid' {`Ptr ()'} -> `Ptr ()' #} flcXid :: (Parent a WindowBase) => Ref a -> IO (Maybe WindowHandle) flcXid win = withRef win ( \winPtr -> do res <- flcXid' winPtr if (res == nullPtr) then return Nothing else return (Just (WindowHandle res)) ) {# fun flc_open_callback as openCallback' { id `FunPtr OpenCallbackPrim' } -> `()' #} openCallback :: Maybe OpenCallback -> IO (Maybe (FunPtr OpenCallbackPrim)) openCallback Nothing = openCallback' nullFunPtr >> return Nothing openCallback (Just cb) = do ptr <- mkOpenCallbackPtr $ \cstr -> do txt <- cStringToText cstr cb txt openCallback' ptr return (Just ptr)
Fix for older versions of webkit
module Graphics.UI.Gtk.WebKit.DOM.StorageInfo (cTEMPORARY, cPERSISTENT, StorageInfo, StorageInfoClass, castToStorageInfo, gTypeStorageInfo, toStorageInfo) where import System.Glib.FFI import System.Glib.UTFString import Control.Applicative {#import Graphics.UI.Gtk.WebKit.Types#} import System.Glib.GError import Graphics.UI.Gtk.WebKit.DOM.EventM cTEMPORARY = 0 cPERSISTENT = 1
module Graphics.UI.Gtk.WebKit.DOM.StorageInfo ( #if WEBKIT_CHECK_VERSION(1,10,0) cTEMPORARY, cPERSISTENT, StorageInfo, StorageInfoClass, castToStorageInfo, gTypeStorageInfo, toStorageInfo #endif ) where import System.Glib.FFI import System.Glib.UTFString import Control.Applicative {#import Graphics.UI.Gtk.WebKit.Types#} import System.Glib.GError import Graphics.UI.Gtk.WebKit.DOM.EventM cTEMPORARY = 0 cPERSISTENT = 1
Add openFile and delete procedures
@0xc020c6481d06e29b; interface Editor { # An editor. insert @0 (line: UInt64, column: UInt64, string: Text); # Inserts `string` at [`line`][`column`] of the file. writeFile @1 (path: Text); # Writes the contents of this editor to the file specified by path. quit @2 (); # Quits this editor. }
@0xc020c6481d06e29b; interface Editor { # An editor. openFile @0 (path: Text); # Opens `path` for editing. If `path` does not exist, it is created. writeFile @1 (path: Text); # Writes the contents of this editor to the file specified by path. insert @2 (line: UInt64, column: UInt64, string: Text); # Inserts `string` at [`line`][`column`] of the file. delete @3 (line: UInt64, column: UInt64, length: UInt64); # Delete the string at [`line`][`column`] with `length`. quit @4 (); # Quits this editor. }
Update Temoral Memory Proto to include Orphan Decay
@0xc5bf8243b0c10764; # TODO: Use absolute path using import "ConnectionsProto.capnp".ConnectionsProto; using import "RandomProto.capnp".RandomProto; # Next ID: 16 struct TemporalMemoryProto { columnDimensions @0 :List(UInt32); cellsPerColumn @1 :UInt32; activationThreshold @2 :UInt32; learningRadius @3 :UInt32; initialPermanence @4 :Float32; connectedPermanence @5 :Float32; minThreshold @6 :UInt32; maxNewSynapseCount @7 :UInt32; permanenceIncrement @8 :Float32; permanenceDecrement @9 :Float32; connections @10 :ConnectionsProto; random @11 :RandomProto; # Lists of indices activeCells @12 :List(UInt32); predictiveCells @13 :List(UInt32); activeSegments @14 :List(UInt32); winnerCells @15 :List(UInt32); }
@0xc5bf8243b0c10764; # TODO: Use absolute path using import "ConnectionsProto.capnp".ConnectionsProto; using import "RandomProto.capnp".RandomProto; # Next ID: 18 struct TemporalMemoryProto { columnDimensions @0 :List(UInt32); cellsPerColumn @1 :UInt32; activationThreshold @2 :UInt32; learningRadius @3 :UInt32; initialPermanence @4 :Float32; connectedPermanence @5 :Float32; minThreshold @6 :UInt32; maxNewSynapseCount @7 :UInt32; permanenceIncrement @8 :Float32; permanenceDecrement @9 :Float32; connections @10 :ConnectionsProto; random @11 :RandomProto; # Lists of indices activeCells @12 :List(UInt32); predictiveCells @13 :List(UInt32); activeSegments @14 :List(UInt32); winnerCells @15 :List(UInt32); matchingSegments @16 :List(UInt32); matchingCells @17 :List(UInt32); }
Revise comments following feedback in anticipation of merge
@0xfa7d16f86048a6e4; struct ScalarEncoderProto { # ScalarEncoder() constructor signature w @0 :UInt32; minval @1 :Float32; maxval @2 :Float32; periodic @3 :Bool; n @4 :UInt32; radius @5 :Float32; resolution @6 :Float32; name @7 :Text; verbosity @8 :UInt8; clipInput @9 :Bool; }
@0xfa7d16f86048a6e4; # Next ID: 10 struct ScalarEncoderProto { w @0 :UInt32; minval @1 :Float32; maxval @2 :Float32; periodic @3 :Bool; n @4 :UInt32; radius @5 :Float32; resolution @6 :Float32; name @7 :Text; verbosity @8 :UInt8; clipInput @9 :Bool; }
Revise comments following feedback in anticipation of merge
@0xfa7d16f86048a6e4; struct ScalarEncoderProto { # ScalarEncoder() constructor signature w @0 :UInt32; minval @1 :Float32; maxval @2 :Float32; periodic @3 :Bool; n @4 :UInt32; radius @5 :Float32; resolution @6 :Float32; name @7 :Text; verbosity @8 :UInt8; clipInput @9 :Bool; }
@0xfa7d16f86048a6e4; # Next ID: 10 struct ScalarEncoderProto { w @0 :UInt32; minval @1 :Float32; maxval @2 :Float32; periodic @3 :Bool; n @4 :UInt32; radius @5 :Float32; resolution @6 :Float32; name @7 :Text; verbosity @8 :UInt8; clipInput @9 :Bool; }
Prepend copyright statement to Cap'n Proto schema.
@0x81f586f4d873f6ac; struct Snapshot { id @0 :Int64; familyName @1: Text; msg @2 :Text; hash @3 :Data; treeReference @4 :Data; } struct SnapshotList { snapshots @0 :List(Snapshot); } struct ChunkRef { blobId @0 :Data; offset @1: Int64; length @2: Int64; } struct HashRef { hash @0 :Data; chunkRef @1 :ChunkRef; } struct HashRefList { hashRefs @0 :List(HashRef); }
# Copyright 2014 Google Inc. 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. @0x81f586f4d873f6ac; struct Snapshot { id @0 :Int64; familyName @1: Text; msg @2 :Text; hash @3 :Data; treeReference @4 :Data; } struct SnapshotList { snapshots @0 :List(Snapshot); } struct ChunkRef { blobId @0 :Data; offset @1: Int64; length @2: Int64; } struct HashRef { hash @0 :Data; chunkRef @1 :ChunkRef; } struct HashRefList { hashRefs @0 :List(HashRef); }
Update Temoral Memory Proto to include Orphan Decay
@0xc5bf8243b0c10764; # TODO: Use absolute path using import "ConnectionsProto.capnp".ConnectionsProto; using import "RandomProto.capnp".RandomProto; # Next ID: 18 struct TemporalMemoryProto { columnDimensions @0 :List(UInt32); cellsPerColumn @1 :UInt32; activationThreshold @2 :UInt32; learningRadius @3 :UInt32; initialPermanence @4 :Float32; connectedPermanence @5 :Float32; minThreshold @6 :UInt32; maxNewSynapseCount @7 :UInt32; permanenceIncrement @8 :Float32; permanenceDecrement @9 :Float32; connections @10 :ConnectionsProto; random @11 :RandomProto; # Lists of indices activeCells @12 :List(UInt32); predictiveCells @13 :List(UInt32); activeSegments @14 :List(UInt32); winnerCells @15 :List(UInt32); matchingSegments @16 :List(UInt32); matchingCells @17 :List(UInt32); }
@0xc5bf8243b0c10764; # TODO: Use absolute path using import "ConnectionsProto.capnp".ConnectionsProto; using import "RandomProto.capnp".RandomProto; # Next ID: 19 struct TemporalMemoryProto { columnDimensions @0 :List(UInt32); cellsPerColumn @1 :UInt32; activationThreshold @2 :UInt32; learningRadius @3 :UInt32; initialPermanence @4 :Float32; connectedPermanence @5 :Float32; minThreshold @6 :UInt32; maxNewSynapseCount @7 :UInt32; permanenceIncrement @8 :Float32; permanenceDecrement @9 :Float32; permanenceOrphanDecrement @10 :Float32; connections @11 :ConnectionsProto; random @12 :RandomProto; # Lists of indices activeCells @13 :List(UInt32); predictiveCells @14 :List(UInt32); activeSegments @15 :List(UInt32); winnerCells @16 :List(UInt32); matchingSegments @17 :List(UInt32); matchingCells @18 :List(UInt32); }
Add Temporal Memory serialization schema
@0xc5bf8243b0c10764; # TODO: Use absolute path using import "ConnectionsProto.capnp".ConnectionsProto; using import "RandomProto.capnp".RandomProto; # Next ID: 16 struct TemporalMemoryProto { columnDimensions @0 :List(UInt32); cellsPerColumn @1 :UInt32; activationThreshold @2 :UInt32; learningRadius @3 :UInt32; initialPermanence @4 :Float32; connectedPermanence @5 :Float32; minThreshold @6 :UInt32; maxNewSynapseCount @7 :UInt32; permanenceIncrement @8 :Float32; permanenceDecrement @9 :Float32; connections @10 :ConnectionsProto; random @11 :RandomProto; activeCells @12 :List(UInt32); predictiveCells @13 :List(UInt32); activeSegments @14 :List(UInt32); winnerCells @15 :List(UInt32); }
Switch to no-space string to make the version value pass validation
Version "2.0.0 beta3" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign the trill object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Version "2.0.0b3" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign the trill object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Update language in a message
Version "2.0.0b3" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign the trill object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Version "2.0.0b3" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign this object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Update release to beta 3
Version "2.0.0 beta2" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign the trill object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Version "2.0.0 beta3" PluginName "Sibelius to MEI Exporter" Author "Andrew Hankinson" _InitialProgressTitle "Exporting %s to MEI" _ExportFileIsNull "You must specify a file to save." _ScoreError "Please open a score and try again." _ExportSuccess "The file was exported successfully." _ExportFailure "The file was not exported because of an error." _VersionNotSupported "Versions earlier than Sibelius 7 are not supported." _ExportingBars "Exporting to MEI: Bar %s of %s" _ObjectAssignedToAllVoicesWarning "Bar %s, voice %s. %s assigned to all voices will be encoded on voice 1. If this is incorrect, you should explicitly assign the trill object to a voice." _ObjectHasNoMEISupport "%s is not supported by MEI at this time." _ObjectIsOnAnIllogicalObject "Bar %s, voice %s. %s is added to a %s object. This will create invalid MEI. You should fix this in your Sibelius file if possible, or edit your MEI file after export." LOGFILE "/tmp/sibelius.log"
Change makeArray -> arrayOfSize to fix compilation error
Array<Cell<Key->Item>?> makeCellEntryArray<Key,Item>(Integer size) given Key satisfies Object given Item satisfies Object { return makeArray<Cell<Key->Item>?>(size, (Integer index) null); } Array<Cell<Element>?> makeCellElementArray<Element>(Integer size) { return makeArray<Cell<Element>?>(size, (Integer index) null); }
Array<Cell<Key->Item>?> makeCellEntryArray<Key,Item>(Integer size) given Key satisfies Object given Item satisfies Object { return arrayOfSize<Cell<Key->Item>?>(size, null); } Array<Cell<Element>?> makeCellElementArray<Element>(Integer size) { return arrayOfSize<Cell<Element>?>(size, null); }
Fix unstable test by not checking collections order
import ceylon.language.meta.declaration { Module } import ceylon.test { test, assertEquals } import ceylon.build.runner { findTopLevelAnnotatedGoals, findAnnotatedIncludes } import mock.ceylon.build.runner.mock4 { include1, include2 } import mock.ceylon.build.runner.mock4.subpackage { include3 } test void shouldNotFindIncludeAnnotatedValuesIfNoPackage() { Module mod = `module mock.ceylon.build.runner.mock1`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldNotFindIncludeAnnotatedValuesInEmptyPackages() { Module mod = `module mock.ceylon.build.runner.mock2`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldNotFindIncludeAnnotatedValuesIfNoValuesAnnotatedWithIt() { Module mod = `module mock.ceylon.build.runner.mock3`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldFindIncludeAnnotatedValues() { Module mod = `module mock.ceylon.build.runner.mock4`; value results = [].chain(findAnnotatedIncludes(mod)); value expected = [`value include1`, `value include2`, `value include3`]; assertEquals(results, expected); }
import ceylon.build.runner { findTopLevelAnnotatedGoals, findAnnotatedIncludes } import ceylon.collection { HashSet } import ceylon.language.meta.declaration { Module, ValueDeclaration } import ceylon.test { test, assertEquals } import mock.ceylon.build.runner.mock4 { include1, include2 } import mock.ceylon.build.runner.mock4.subpackage { include3 } test void shouldNotFindIncludeAnnotatedValuesIfNoPackage() { Module mod = `module mock.ceylon.build.runner.mock1`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldNotFindIncludeAnnotatedValuesInEmptyPackages() { Module mod = `module mock.ceylon.build.runner.mock2`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldNotFindIncludeAnnotatedValuesIfNoValuesAnnotatedWithIt() { Module mod = `module mock.ceylon.build.runner.mock3`; value results = findTopLevelAnnotatedGoals(mod); assertEquals(results, []); } test void shouldFindIncludeAnnotatedValues() { Module mod = `module mock.ceylon.build.runner.mock4`; value results = [].chain(findAnnotatedIncludes(mod)); value expected = [`value include1`, `value include2`, `value include3`]; containSameElements(results, expected); } void containSameElements({ValueDeclaration*} actual, {ValueDeclaration*} expected) { assertEquals(HashSet { elements = actual; } , HashSet { elements = expected; }); }
Add a "maxLineLength" formatting option.
{FormattingOption+} formattingOptions = { FormattingOption { "The indentation mode of the formatter."; "IndentMode"; "indentMode"; /* = */ "Spaces(4)"; } };
{FormattingOption+} formattingOptions = { FormattingOption { "The indentation mode."; "IndentMode"; "indentMode"; /* = */ "Spaces(4)"; }, FormattingOption { "The maximum line length, or `null` for unlimited line length."; "Integer?"; "maxLineLength"; /* = */ "null"; } };
Add test for named arg funs with type params
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {}
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } };
Print obtained classname in error message
import check {...} void test_outer_inner_safety() { class Outer() { shared class Inner() { } } Outer? o = null; Outer.Inner? i1 = o?.Inner(); Outer.Inner? cons() = o?.Inner(); if (exists i1) { fail("i1 should be null"); } check(className(cons)=="ceylon.language::JsCallable", "cons is Callable"); Outer.Inner|Nothing i2 = cons(); if (exists i2) { fail("i2 should not exist"); } }
import check {...} void test_outer_inner_safety() { class Outer() { shared class Inner() { } } Outer? o = null; Outer.Inner? i1 = o?.Inner(); Outer.Inner? cons() = o?.Inner(); if (exists i1) { fail("i1 should be null"); } check(className(cons)=="ceylon.language::JsCallable", "cons is Callable, " className(cons) ""); Outer.Inner|Nothing i2 = cons(); if (exists i2) { fail("i2 should not exist"); } }
Add Gavin's tests for the 3 styles of higher-order function calling
import assert { ... } Element? find<Element>(Array<Element> a, Boolean f(Element x)) { for (Element e in a) { if (f(e)) { return e; } } return null; } void testAnonymous() { print("Testing anonymous functions..."); value nums = array(1,2,3,4,5); //Test positional argument call variable value found := find(nums, (Integer i) i%2==0); if (exists i=found) { assert(i == 2, "anonfunc positional"); } else { fail("anonfunc positional"); } //Named argument call found := find{ function f(Integer i) { return i%2==0; } a=nums; }; if (exists i=found) { assert(i == 2, "anonfunc named"); } else { fail("anonfunc named"); } }
import assert { ... } Element? find<Element>(Array<Element> a, Boolean f(Element x)) { for (Element e in a) { if (f(e)) { return e; } } return null; } void testAnonymous() { print("Testing anonymous functions..."); value nums = array(1,2,3,4,5); //Test positional argument call variable value found := find(nums, (Integer i) i%2==0); if (exists i=found) { assert(i == 2, "anonfunc positional"); } else { fail("anonfunc positional"); } //Named argument call found := find{ function f(Integer i) { return i%2==0; } a=nums; }; if (exists i=found) { assert(i == 2, "anonfunc named"); } else { fail("anonfunc named"); } //Gavin's test void callFunction(String f(Integer i)) { print(f(0)); } function f(Integer i) { return (i+12).string; } callFunction(f); callFunction((Integer i) (i*3).string); callFunction { function f(Integer i) { return (i**2).string; } }; }
Add support for persisting arrays.
import ceylon.language.meta.model { Attribute, Type } import ceylon.language.meta.declaration { ValueDeclaration, TypeParameter } "Contract for flattening the state of an instance of a class. This interface is implemented by a serialization library." shared interface Deconstructor { "Adds the given type argument of the given type parameter to the flattened state." throws (`class AssertionError`, "if there is already a value for the given type argument") shared formal void putTypeArgument(TypeParameter typeParameter, Type typeArgument); "Adds the value of the given attribute to the flattened state." throws (`class AssertionError`, "if there is already a value for the given attribute") shared formal void putValue<Type>(ValueDeclaration attribute, Type referenced); } "The flattened state of an instance of a class. This interface is implemented by a serialization library." shared interface Deconstructed satisfies {[ValueDeclaration, Anything]*} { "Get the type argument of the given type parameter" throws (`class AssertionError`, "if the type argument is missing") shared formal Type getTypeArgument(TypeParameter typeParameter); "Get the value of the given attribute." throws (`class AssertionError`, "if the value is missing") shared formal Type|Reference<Type> getValue<Type>(ValueDeclaration attribute); }
import ceylon.language.meta.model { Attribute, Type } import ceylon.language.meta.declaration { ValueDeclaration, TypeParameter } "Contract for flattening the state of an instance of a class. This interface is implemented by a serialization library." shared interface Deconstructor { "Adds the given type argument of the given type parameter to the flattened state." throws (`class AssertionError`, "if there is already a value for the given type argument") shared formal void putTypeArgument(TypeParameter typeParameter, Type typeArgument); "Adds the value of the given attribute to the flattened state." throws (`class AssertionError`, "if there is already a value for the given attribute") shared formal void putValue<Type>(ValueDeclaration attribute, Type referenced); shared formal void putArray<Element>(ValueDeclaration attribute, Array<Element> array); } "The flattened state of an instance of a class. This interface is implemented by a serialization library." shared interface Deconstructed satisfies {[ValueDeclaration, Anything]*} { "Get the type argument of the given type parameter" throws (`class AssertionError`, "if the type argument is missing") shared formal Type getTypeArgument(TypeParameter typeParameter); "Get the value of the given attribute." throws (`class AssertionError`, "if the value is missing") shared formal Type|Reference<Type> getValue<Type>(ValueDeclaration attribute); shared formal Array<Element> array getArray<Element>(ValueDeclaration attribute); }
Update import of ANTLR runtime
"A formatter for the Ceylon programming language." module ceylon.formatter "1.0.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.0.0"; shared import org.antlr.runtime "3.4"; import ceylon.time "1.0.0"; import ceylon.interop.java "1.0.0"; import ceylon.collection "1.0.0"; import ceylon.file "1.0.0"; }
"A formatter for the Ceylon programming language." module ceylon.formatter "1.0.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.0.0"; shared import 'org.antlr-runtime' "3.4"; import ceylon.time "1.0.0"; import ceylon.interop.java "1.0.0"; import ceylon.collection "1.0.0"; import ceylon.file "1.0.0"; }
Add the required native annotation
"Module that allows developping the Ceylon IDE in Ceylon" by("David Festal") module com.redhat.ceylon.eclipse.ui "1.1.1" { shared import com.redhat.ceylon.typechecker "1.1.1"; shared import com.redhat.ceylon.model "1.1.1"; shared import ceylon.collection "1.1.1"; import ceylon.interop.java "1.1.1"; shared import java.base "7"; }
"Module that allows developping the Ceylon IDE in Ceylon" by("David Festal") native("java") module com.redhat.ceylon.eclipse.ui "1.1.1" { shared import com.redhat.ceylon.typechecker "1.1.1"; shared import com.redhat.ceylon.model "1.1.1"; shared import ceylon.collection "1.1.1"; import ceylon.interop.java "1.1.1"; shared import java.base "7"; }
Fix wrong order of arguments in doc
"Given two streams, form a new stream by applying a function to the arguments in the given streams. The length of the resulting stream is the length of the shorter of the two given streams. Thus: mapPairs(xs,ys,fun)[i]==fun(xs[i],ys[i]) for every `0<=i<min({xs.size,ys.size})`." shared {Result*} mapPairs<Result,FirstArgument,SecondArgument>( Result collecting(FirstArgument firstArg, SecondArgument secondArg), {FirstArgument*} firstArguments, {SecondArgument*} secondArguments ) { object iterable satisfies {Result*} { shared actual Iterator<Result> iterator() { value first = firstArguments.iterator(); value second = secondArguments.iterator(); object iterator satisfies Iterator<Result> { shared actual Result|Finished next() { if (!is Finished firstArg=first.next(), !is Finished secondArg=second.next()) { return collecting(firstArg,secondArg); } else { return finished; } } } return iterator; } } return iterable; }
"Given two streams, form a new stream by applying a function to the arguments in the given streams. The length of the resulting stream is the length of the shorter of the two given streams. Thus: mapPairs(fun,xs,ys)[i]==fun(xs[i],ys[i]) for every `0<=i<min({xs.size,ys.size})`." shared {Result*} mapPairs<Result,FirstArgument,SecondArgument>( Result collecting(FirstArgument firstArg, SecondArgument secondArg), {FirstArgument*} firstArguments, {SecondArgument*} secondArguments ) { object iterable satisfies {Result*} { shared actual Iterator<Result> iterator() { value first = firstArguments.iterator(); value second = secondArguments.iterator(); object iterator satisfies Iterator<Result> { shared actual Result|Finished next() { if (!is Finished firstArg=first.next(), !is Finished secondArg=second.next()) { return collecting(firstArg,secondArg); } else { return finished; } } } return iterator; } } return iterable; }
Add missing charsets to charsetsByAlias
import ceylon.buffer.codec { buildCodecLookup } "A mapping of all supported character sets. Currently this lists contains: - ASCII - ISO 8859 1 - UTF-8 - UTF-16 " shared Map<String,Charset> charsetsByAlias = buildCodecLookup { utf8 };
import ceylon.buffer.codec { buildCodecLookup } "A mapping of all supported character sets. Currently this lists contains: - ASCII - ISO 8859 1 - UTF-8 - UTF-16 " shared Map<String,Charset> charsetsByAlias = buildCodecLookup { utf8, utf16, iso_8859_1, ascii };
Add simple test for type alias
import check { ... } shared class AliasingClass() { shared interface AliasingIface { shared Boolean aliasingIface() { return true; } } shared class AliasingInner() { shared Boolean aliasingInner() { return true; } } } class AliasingSubclass() extends AliasingClass() { shared class InnerAlias() = AliasingInner; shared class SubAlias() extends InnerAlias() {} shared Boolean aliasingSubclass() { return SubAlias().aliasingInner(); } shared interface AliasedIface = AliasingIface; } class AliasingSub2() extends AliasingSubclass() { shared AliasedIface iface { object aliased satisfies AliasedIface { } return aliased; } } void testAliasing() { print("testing type aliases"); check(AliasingSubclass().aliasingSubclass(), "Aliased member class"); class InnerSubalias() = AliasingSubclass; check(InnerSubalias().aliasingSubclass(), "Aliased top-level class"); interface AliasedIface2 = AliasingClass.AliasingIface; Boolean use(AliasedIface2 aif) { return aif.aliasingIface(); } check(use(AliasingSub2().iface), "Aliased member interface"); }
import check { ... } alias Strinteger = String|Integer; shared class AliasingClass() { shared interface AliasingIface { shared Boolean aliasingIface() { return true; } } shared class AliasingInner() { shared Boolean aliasingInner() { return true; } } } class AliasingSubclass() extends AliasingClass() { shared class InnerAlias() = AliasingInner; shared class SubAlias() extends InnerAlias() {} shared Boolean aliasingSubclass() { return SubAlias().aliasingInner(); } shared interface AliasedIface = AliasingIface; } class AliasingSub2() extends AliasingSubclass() { shared AliasedIface iface { object aliased satisfies AliasedIface { } return aliased; } } void testAliasing() { print("testing type aliases"); check(AliasingSubclass().aliasingSubclass(), "Aliased member class"); class InnerSubalias() = AliasingSubclass; check(InnerSubalias().aliasingSubclass(), "Aliased top-level class"); interface AliasedIface2 = AliasingClass.AliasingIface; Boolean use(AliasedIface2 aif) { return aif.aliasingIface(); } check(use(AliasingSub2().iface), "Aliased member interface"); Strinteger xxxxx = 5; check(is Integer xxxxx, "Type alias"); }
Add test for generic anonymous functions
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } };
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } }; value anonymousGenericFunction = <T>(T t) => t;
Use the `utf-8` charset for html
import ceylon.html { Head, Body, Html } import ceylon.markdown.core { Document } "Render Markdown as a complete HTML document. This method returns an [[Html]] object. value html = renderCompleteHtml(tree);" shared Html renderCompleteHtml(Document document) => Html { Head { }, Body { children = HtmlVisitor().visitDocument(document); } }; "Render Markdown as a list of HTML elements. This method returns a sequence. value nodes = renderPartialHtml(tree);" shared HtmlChildren[] renderPartialHtml(Document document) => HtmlVisitor().visitDocument(document);
import ceylon.html { Head, Body, Html, Meta } import ceylon.markdown.core { Document } "Render Markdown as a complete HTML document. This method returns an [[Html]] object using the `utf-8` charset. value html = renderCompleteHtml(tree);" shared Html renderCompleteHtml(Document document) => Html { Head { Meta { charset="utf-8"; } }, Body { children = HtmlVisitor().visitDocument(document); } }; "Render Markdown as a list of HTML elements. This method returns a sequence. value nodes = renderPartialHtml(tree);" shared HtmlChildren[] renderPartialHtml(Document document) => HtmlVisitor().visitDocument(document);
Add test for backtick-less meta literals
void decLiterals() { value clM = `module ceylon.language`; value clP = `package ceylon.language`; value stringC = `class String`; value iterableI = `interface Iterable`; value aliasA = `alias Alias`; value givenG = `given Given`; value nullV = `value null`; value identityF = `function identity`; value newN = `new Constructor`; value currentM = `module`; value currentP = `package`; value currentC = `class`; value currentI = `interface`; }
void decLiterals() { value clM = `module ceylon.language`; value clP = `package ceylon.language`; value stringC = `class String`; value iterableI = `interface Iterable`; value aliasA = `alias Alias`; value givenG = `given Given`; value nullV = `value null`; value identityF = `function identity`; value newN = `new Constructor`; value currentM = `module`; value currentP = `package`; value currentC = `class`; value currentI = `interface`; } void decLiteralsWithoutBackticks() { value clM = module ceylon.language; value clP = package ceylon.language; value stringC = class String; value iterableI = interface Iterable; value aliasA = alias Alias; value givenG = given Given; value nullV = value null; value identityF = function identity; value newN = new Constructor; value currentM = module; value currentP = package; value currentC = class; value currentI = interface; }
Add test for parameterized exprs with type params
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } }; value anonymousGenericFunction = <T>(T t) => t;
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } }; value anonymousGenericFunction = <T>(T t) => t; class C() { parameterizedExpressionWithTypeParams<T>(T t) => t; }
Use HashMap instead of LazyMap
import ceylon.build.task { Goal, GoalSet } import ceylon.collection { LinkedList } "An interactive console." void console({<Goal|GoalSet>+} goals) { value exitMessages = LazyMap<Integer, String>({ exitCodes.success->"Success", exitCodes.dependencyCycleFound->"Dependency Cycle Found", exitCodes.invalidGoalFound->"Invalid goal found", exitCodes.duplicateGoalsFound->"Duplicate goals found", exitCodes.noGoalToRun->"No goal to run", exitCodes.errorOnTaskExecution->"Error on task execution" }); print("Available goals: ``mergeGoalSetsWithGoals(goals)``"); print("Enter Ctrl + D to quit"); while (true) { process.write("> "); String? rawLine = process.readLine(); // workaround for https://github.com/ceylon/ceylon.language/issues/372 if (is Null rawLine) { process.writeLine(); return; } assert(exists rawLine); String line = rawLine.trimmed; value result = runEngine(goals,"",line.split().sequence); assert(exists msg = exitMessages[result.exitCode]); print(msg); } }
import ceylon.build.task { Goal, GoalSet } import ceylon.collection { HashMap } "An interactive console." void console({<Goal|GoalSet>+} goals) { value exitMessages = HashMap<Integer, String>({ exitCodes.success->"Success", exitCodes.dependencyCycleFound->"Dependency Cycle Found", exitCodes.invalidGoalFound->"Invalid goal found", exitCodes.duplicateGoalsFound->"Duplicate goals found", exitCodes.noGoalToRun->"No goal to run", exitCodes.errorOnTaskExecution->"Error on task execution" }); print("Available goals: ``mergeGoalSetsWithGoals(goals)``"); print("Enter Ctrl + D to quit"); while (true) { process.write("> "); String? rawLine = process.readLine(); // workaround for https://github.com/ceylon/ceylon.language/issues/372 if (is Null rawLine) { process.writeLine(); return; } assert(exists rawLine); String line = rawLine.trimmed; value result = runEngine(goals,"",line.split().sequence); assert(exists msg = exitMessages[result.exitCode]); print(msg); } }
Test condition list with comprehensions
import check {...} shared void test() { Boolean a = true; Boolean b = false; variable value count := 0; if (a && b) { fail("WTF?"); } else if (a || b) { check(a||b, "boolean 1"); count++; } String? c = "X"; String? d = null; if (exists c && exists d) { fail("WTF exists"); } else if (exists c1=c, exists c1[0]) { check(c1 == "X", "exists"); count++; } String|Integer e = 1; if (is Integer e && exists d) { fail("WTF is"); } else if (is Integer e, exists c) { check(e>0, "is"); count++; } String[] f = {"a","b","c"}; Integer[] g = {}; if (nonempty f && nonempty g) { fail("WTF nonempty"); } else if (nonempty f, nonempty f.first) { check(f.first.uppercased=="A", "nonempty"); count++; } check(count==4, "some conditions were not met: " count " instead of 4"); results(); }
import check {...} shared void test() { Boolean a = true; Boolean b = false; variable value count := 0; if (a && b) { fail("WTF?"); } else if (a || b) { check(a||b, "boolean 1"); count++; } String? c = "X"; String? d = null; if (exists c && exists d) { fail("WTF exists"); } else if (exists c1=c, exists c1[0]) { check(c1 == "X", "exists"); count++; } String|Integer e = 1; if (is Integer e && exists d) { fail("WTF is"); } else if (is Integer e, exists c) { check(e>0, "is"); count++; } String[] f = {"a","b","c"}; Integer[] g = {}; if (nonempty f && nonempty g) { fail("WTF nonempty"); } else if (nonempty f, nonempty f.first) { check(f.first.uppercased=="A", "nonempty"); count++; } check(count==4, "some conditions were not met: " count " instead of 4"); Void zz = 1; assert(is Integer zz2=zz, zz2 > 0); check(zz2==1, "special -> boolean"); //and now some comprehensions Sequence<Integer?> seq1 = { 1, 2, 3, null, 4, 5, null, 6, 7, null, 10}; check({ for (i in seq1) if (exists i, i%2==0) i*10 }=={20,40,60,100},"comprehension [1]"); results(); }
Add test for anon functions with type constraints
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } }; value anonymousGenericFunction = <T>(T t) => t; class C() { parameterizedExpressionWithTypeParams<T>(T t) => t; }
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {} value namedArgsInvocWithFunctionArgWithTypeParam = f { function f<T>(T t) { return t; } }; value anonymousGenericFunction = <T>(T t) given T satisfies Anything => t; class C() { parameterizedExpressionWithTypeParams<T>(T t) => t; }
Add tests for escaped character literals
void characters() { value c = `a`; assert(c.lowercase, "lowercase char"); assert(!c.uppercase, "lowercase char"); assert(`A`.uppercase, "uppercase char"); assert(!`A`.lowercase, "uppercase char"); assert(c.uppercased==`A`, "uppercased char"); assert(`A`.lowercased==`a`, "lowercased char"); assert(c.string=="a", "character string"); assert(!c.whitespace, "character not whitespace"); assert(!c.digit, "character not whitespace"); assert(` `.whitespace, "character whitespace"); assert(`1`.digit, "character digt"); assert(`a`<`z`, "char order"); assert(`a`.successor==`b`, "char successor"); assert(`Z`.predecessor==`Y`, "char predecessor"); variable value i:=0; for (x in `a`..`z`) { i:=i+1; assert(x>=`a`&&x<=`z`, "character range"); } assert(i==26, "character range"); assert(c.integer.character==c, "integer/character conversion"); assert(69.character.integer==69, "integer/character conversion"); }
void characters() { value c = `a`; assert(c.lowercase, "lowercase char"); assert(!c.uppercase, "lowercase char"); assert(`A`.uppercase, "uppercase char"); assert(!`A`.lowercase, "uppercase char"); assert(c.uppercased==`A`, "uppercased char"); assert(`A`.lowercased==`a`, "lowercased char"); assert(c.string=="a", "character string"); assert(!c.whitespace, "character not whitespace"); assert(!c.digit, "character not whitespace"); assert(` `.whitespace, "character whitespace"); assert(`1`.digit, "character digt"); assert(`a`<`z`, "char order"); assert(`a`.successor==`b`, "char successor"); assert(`Z`.predecessor==`Y`, "char predecessor"); assert(`\t`.integer==9, "escaped characters 1"); assert(`\\`.integer==92, "escaped characters 2"); assert(`\``.integer==96, "escaped characters 3"); variable value i:=0; for (x in `a`..`z`) { i:=i+1; assert(x>=`a`&&x<=`z`, "character range"); } assert(i==26, "character range"); assert(c.integer.character==c, "integer/character conversion"); assert(69.character.integer==69, "integer/character conversion"); }
Remove creation of new array.
import java.nio { JByteBuffer=ByteBuffer } import java.lang { ByteArray } shared {Byte*} toBytes(JByteBuffer[] jByteBufferArray) => jByteBufferArray.flatMap((JByteBuffer element) => collectBytes(element)); {Byte*} collectBytes(JByteBuffer jByteBuffer) { ByteArray array = ByteArray(jByteBuffer.remaining()); //TODO can we do without new array? jByteBuffer.get(array); return array.iterable; }
import java.nio { JByteBuffer=ByteBuffer } import java.lang { ByteArray } shared {Byte*} toBytes(JByteBuffer[] jByteBufferArray) => jByteBufferArray.flatMap((JByteBuffer element) => collectBytes(element)); {Byte*} collectBytes(JByteBuffer jByteBuffer) { return jByteBuffer.array().iterable; }
Fix for the JS backend: made run method shared
/* * Copyright 2011 Red Hat 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. */ void run(){ print("Look, Ma! No module!"); }
/* * Copyright 2011 Red Hat 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. */ shared void run(){ print("Look, Ma! No module!"); }
Make run with latest ceylon
"Something that can go through a transition and is meant to be be fulfilled or rejected." by("Julien Viet") shared interface Resolver<in Value> { "Fulfills the promise with a value or a promise to the value." shared formal void fulfill(Value|Promise<Value> val); "Rejects the promise with a reason." shared formal void reject(Throwable reason); "Either fulfill or reject the promise" shared void resolve(Value|Promise<Value>|Throwable val) { if (is Value|Promise<Value> val) { fulfill(val); } else { assert(is Throwable val); reject(val); } } }
"Something that can go through a transition and is meant to be be fulfilled or rejected." by("Julien Viet") shared interface Resolver<in Value> { "Fulfills the promise with a value or a promise to the value." shared formal void fulfill(Value|Promise<Value> val); "Rejects the promise with a reason." shared formal void reject(Throwable reason); "Either fulfill or reject the promise" shared void resolve(Value|Promise<Value>|Throwable val) { if (is Value|Promise<Value> val) { fulfill(val); } else { reject(val); } } }
Complete the array tests (which now pass with flying colors)
//Array tests void testArrays() { assert(!nonempty arrayOfNone(), "arrayOfNone"); value a1 = arrayOfSome({1}); //assert(nonempty a1, "nonempty array"); assert(a1.size==1, "array.size"); assert(a1[0] exists, "array[0]"); assert(!a1.empty, "array.empty"); assert(a1.hash==1, "array.hash"); a1.setItem(0,10); if (exists i=a1[0]) { assert(i==10, "array.setItem"); } else { fail("array.setItem"); } a1.setItem(0,null); if (exists i=a1[0]) { fail("array.setItem (null)"); } }
//Array tests void testArrays() { assert(!nonempty array(), "arrayOfNone"); value a1 = array(1); assert(nonempty a1, "nonempty array"); assert(a1.size==1, "array.size"); assert(a1[0] exists, "array[0]"); assert(!a1.empty, "array.empty"); assert(a1.hash==1, "array.hash"); a1.setItem(0,10); if (exists i=a1[0]) { assert(i==10, "array.setItem"); } else { fail("array.setItem"); } a1.setItem(0,null); if (exists i=a1[0]) { fail("array.setItem (null)"); } value a2=array(1,2,3); value a3=arrayOfSome({1,2,3}); assert(a2==a3, "array.equals"); assert(a2.size==a3.size, "array.size"); assert(nonempty a2, "nonempty array 2"); a2.setItem(0,10); a3.setItem(0,null); if (exists i=a2[0]) { assert(i==10, "array.setItem 2"); } else { fail("array.setItem 2"); } if (exists i=a3[0]) { fail("array.setItem (null) 2"); } }
Remove java.tls import from ceylon.buffer
by ("Stéphane Épardaud", "Alex Szczuczko") module ceylon.buffer "1.2.1" { import ceylon.collection "1.2.1"; native ("jvm") import java.base "7"; native ("jvm") import java.tls "7"; native ("jvm") import ceylon.interop.java "1.2.1"; }
"This module defines character sets, for encoding and decoding bytes to strings, as well as buffers of bytes and characters for input/output." by ("Stéphane Épardaud", "Alex Szczuczko") module ceylon.buffer "1.2.1" { import ceylon.collection "1.2.1"; native ("jvm") import java.base "7"; native ("jvm") import ceylon.interop.java "1.2.1"; }
Update if expressions test for changed indentation
Anything ifExpression = if (true || false) then 1 else 2; void ifExpr() { print(if (true) then 1 else 0); }
Anything ifExpression = if (true || false) then 1 else 2; void ifExpr() { print(if (true) then 1 else 0); }
Remove unused dependency on ceylon.collection
"Date and Time library for Ceylon language SDK. This library is loosely modeled/inspired by the JodaTime/JSR-310 date/time library. " by ("Diego Coronel", "Roland Tepp") module ceylon.time "1.2.3" { import ceylon.collection "1.2.3"; }
"Date and Time library for Ceylon language SDK. This library is loosely modeled/inspired by the JodaTime/JSR-310 date/time library. " by ("Diego Coronel", "Roland Tepp") module ceylon.time "1.2.3" { }
Update to ceylon 1.3.1 + vertx 3.3.3
native("jvm") module org.otherone.vhostproxy.vertx "4" { shared import io.vertx.ceylon.core "3.3.2"; //shared import "io.vertx:vertx-lang-ceylon" "3.3.0-SNAPSHOT"; //shared import "io.vertx.lang.ceylon" "3.3.0-SNAPSHOT"; import ceylon.regex "1.2.2"; import ceylon.logging "1.2.2"; //import ceylon.time "1.2.1"; import java.base "7"; //import "it.zero11:acme-client" "0.1.2"; import ceylon.file "1.2.2"; import ceylon.buffer "1.2.2"; }
native("jvm") module org.otherone.vhostproxy.vertx "4" { shared import io.vertx.ceylon.core "3.3.3"; //shared import "io.vertx:vertx-lang-ceylon" "3.3.0-SNAPSHOT"; //shared import "io.vertx.lang.ceylon" "3.3.0-SNAPSHOT"; import ceylon.regex "1.3.1"; import ceylon.logging "1.3.1"; //import ceylon.time "1.2.1"; import java.base "7"; //import "it.zero11:acme-client" "0.1.2"; import ceylon.file "1.3.1"; import ceylon.buffer "1.3.1"; }
Fix source-gen bug: doc would be missing line breaks
import ceylon.collection { MutableList, ArrayList } "Run the module `source_gen.ceylon.ast`. See [this gist](https://gist.github.com/lucaswerkmeister/a4da0fa5d9d5b14cc3e9)." shared void run() { if (exists first = process.arguments.first, first == "--help") { print("https://gist.github.com/lucaswerkmeister/a4da0fa5d9d5b14cc3e9"); return; } assert (exists type = process.arguments[0], exists superType = process.arguments[1]); variable Integer i = 2; MutableList<String->String> params = ArrayList<String->String>(); while (i < process.arguments.size) { assert (exists paramType = process.arguments[i++]); assert (exists paramName = process.arguments[i++]); params.add(paramType->paramName); } variable String? line = process.readLine(); StringBuilder doc = StringBuilder(); while (exists l = line) { doc.append(l); line = process.readLine(); } Generator(type, superType, params.sequence(), doc.string).run(); }
import ceylon.collection { MutableList, ArrayList } "Run the module `source_gen.ceylon.ast`. See [this gist](https://gist.github.com/lucaswerkmeister/a4da0fa5d9d5b14cc3e9)." shared void run() { if (exists first = process.arguments.first, first == "--help") { print("https://gist.github.com/lucaswerkmeister/a4da0fa5d9d5b14cc3e9"); return; } assert (exists type = process.arguments[0], exists superType = process.arguments[1]); variable Integer i = 2; MutableList<String->String> params = ArrayList<String->String>(); while (i < process.arguments.size) { assert (exists paramType = process.arguments[i++]); assert (exists paramName = process.arguments[i++]); params.add(paramType->paramName); } variable String? line = process.readLine(); StringBuilder doc = StringBuilder(); while (exists l = line) { doc.append(l); doc.appendNewline(); line = process.readLine(); } Generator(type, superType, params.sequence(), doc.string).run(); }
Update doc and ceylon.math version
doc "Components for JDBC-based database connectivity." by "Enrique Zamudio" license "Apache Software License 2.0" module ceylon.dbc '0.1' { import ceylon.math '0.3.2'; }
doc "This module offers some components for JDBC-based database connectivity. The main component is simply called Sql and is meant to be used with a `DataSource` that has been already been configured. " by "Enrique Zamudio" license "Apache Software License 2.0" module ceylon.dbc '0.1' { import ceylon.math '0.3.3'; }
Format source code (ws in license annotation)
"A formatter for the Ceylon programming language." by ("Lucas Werkmeister <mail@lucaswerkmeister.de>") license("http://www.apache.org/licenses/LICENSE-2.0.html") module ceylon.formatter "1.1.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.1.0"; shared import com.redhat.ceylon.common "1.1.0"; shared import ceylon.file "1.1.0"; import ceylon.interop.java "1.1.0"; import ceylon.collection "1.1.0"; optional import ceylon.test "1.1.0"; // for tests only, remove for release! }
"A formatter for the Ceylon programming language." by ("Lucas Werkmeister <mail@lucaswerkmeister.de>") license ("http://www.apache.org/licenses/LICENSE-2.0.html") module ceylon.formatter "1.1.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.1.0"; shared import com.redhat.ceylon.common "1.1.0"; shared import ceylon.file "1.1.0"; import ceylon.interop.java "1.1.0"; import ceylon.collection "1.1.0"; optional import ceylon.test "1.1.0"; // for tests only, remove for release! }
Update for Ceylon 1.1 (typechecker version)
"A formatter for the Ceylon programming language." module ceylon.formatter "1.0.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.0.0"; shared import ceylon.file "1.0.0"; import ceylon.time "1.0.0"; import ceylon.interop.java "1.0.0"; import ceylon.collection "1.0.0"; }
"A formatter for the Ceylon programming language." module ceylon.formatter "1.0.0" { shared import java.base "7"; shared import com.redhat.ceylon.typechecker "1.1.0"; shared import ceylon.file "1.0.0"; import ceylon.time "1.0.0"; import ceylon.interop.java "1.0.0"; import ceylon.collection "1.0.0"; }
Fix ceylon.ast(.api) link in test.ceylon.ast.api doc
"Tests for the [[ceylon.ast module|module ceylon.ast]]" by ("Lucas Werkmeister <mail@lucaswerkmeister.de>") license("http://www.apache.org/licenses/LICENSE-2.0.html") module test.ceylon.ast.api "1.1.0" { shared import ceylon.test "1.1.0"; import ceylon.ast.api "1.1.0"; }
"Tests for the [[ceylon.ast.api module|module ceylon.ast.api]]" by ("Lucas Werkmeister <mail@lucaswerkmeister.de>") license("http://www.apache.org/licenses/LICENSE-2.0.html") module test.ceylon.ast.api "1.1.0" { shared import ceylon.test "1.1.0"; import ceylon.ast.api "1.1.0"; }
Fix a test for Array.ofSize
@test shared void bug713() { value t = `Array<String>.OfSize` == `Array<String>.OfSize`; }
@test shared void bug713() { value t = `Array<String>.ofSize` == `Array<String>.ofSize`; }
Add create parameter lists internal function
import ceylon.ast.core { Parameter, Parameters } "Converts a stream of [[parameters]] to a [[Parameters]] object." Parameters parameters_internal(Parameters|{Parameter*} parameters) { if (is Parameters parameters) { return parameters; } else { assert (is {Parameter*} parameters); return Parameters(parameters.sequence()); } }
import ceylon.ast.core { Parameter, Parameters } "Converts a stream of [[parameters]] to a [[Parameters]] object." Parameters parameters_internal(Parameters|{Parameter*} parameters) { if (is Parameters parameters) { return parameters; } else { assert (is {Parameter*} parameters); return Parameters(parameters.sequence()); } } [Parameters+] parameterLists_internal({Parameters+}|Parameters|{Parameter*} parameters) { if (is Parameters parameters) { return [parameters]; } else if (is {Parameters+} parameters) { assert (nonempty ret = parameters.sequence()); return ret; } else { assert (is {Parameter*} parameters); return [parameters_internal(parameters)]; } }
Remove unused imports in tests
import ceylon.ast.core { Annotations, Artifact, Module, ModuleImport, ModuleSpecifier, Repository, StringLiteral } import ceylon.ast.redhat { RedHatTransformer, moduleImportToCeylon, parseModuleImport } import com.redhat.ceylon.compiler.typechecker.tree { Tree { JImportModule=ImportModule } } shared object moduleImport satisfies ConcreteTest<ModuleImport,JImportModule> { String->ModuleImport construct(String->Module|ModuleSpecifier name, String->StringLiteral version, String->Annotations annotations = package.annotations.emptyAnnotations) => "``annotations.key`` import ``name.key`` ``version.key``;" -> ModuleImport(name.item, version.item, annotations.item); shared String->ModuleImport ceylonAstCore100ModuleImport = construct(fullPackageName.ceylonAstCorePackageName, stringLiteral._100VersionStringLiteral, annotations.sharedAnnotations); shared String->ModuleImport mavenCommonsCodecModuleImport = construct(moduleSpecifier.mavenCommonsCodecModuleSpecifier, stringLiteral._14VersionStringLiteral, annotations.emptyAnnotations); parse = parseModuleImport; fromCeylon = RedHatTransformer.transformModuleImport; toCeylon = moduleImportToCeylon; codes = [ceylonAstCore100ModuleImport, mavenCommonsCodecModuleImport]; }
import ceylon.ast.core { Annotations, Module, ModuleImport, ModuleSpecifier, StringLiteral } import ceylon.ast.redhat { RedHatTransformer, moduleImportToCeylon, parseModuleImport } import com.redhat.ceylon.compiler.typechecker.tree { Tree { JImportModule=ImportModule } } shared object moduleImport satisfies ConcreteTest<ModuleImport,JImportModule> { String->ModuleImport construct(String->Module|ModuleSpecifier name, String->StringLiteral version, String->Annotations annotations = package.annotations.emptyAnnotations) => "``annotations.key`` import ``name.key`` ``version.key``;" -> ModuleImport(name.item, version.item, annotations.item); shared String->ModuleImport ceylonAstCore100ModuleImport = construct(fullPackageName.ceylonAstCorePackageName, stringLiteral._100VersionStringLiteral, annotations.sharedAnnotations); shared String->ModuleImport mavenCommonsCodecModuleImport = construct(moduleSpecifier.mavenCommonsCodecModuleSpecifier, stringLiteral._14VersionStringLiteral, annotations.emptyAnnotations); parse = parseModuleImport; fromCeylon = RedHatTransformer.transformModuleImport; toCeylon = moduleImportToCeylon; codes = [ceylonAstCore100ModuleImport, mavenCommonsCodecModuleImport]; }
Fix doc typo: langauge -> language
"The Ceylon language module containing the core definitions referred to by the [language specification][spec], along with some basic functionality of use to most programs: - The [[root package|package ceylon.language]] defines general-purpose functionality including support for [[numbers|Numeric]] and [[character strings|String]], [[streams|Iterable]] and [[sequences|Sequential]], [[exceptions|Throwable]], and [[null values|Null]]. - The Ceylon _metamodel_ is defined in [[package ceylon.language.meta]] and its subpackages [[package ceylon.language.meta.model]] and [[package ceylon.language.meta.declaration]], which define interfaces for interacting with applied types and unapplied type declarations respectively. This module defines an abstraction over the basic facilities of the Java or JavaScript virtual machine, containing only functionality that can be easily implemented on both platforms. Thus, certain functionality, for example, concurrency, for which there is no common virtual machine-agnostic model, is not covered by the langauge module. The language module is an implicit dependency of every other Ceylon module, and may not be explicitly imported. [spec]: http://ceylon-lang.org/documentation/current/spec" by ("Gavin King", "Tom Bentley", "Tako Schotanus", "Stephane Epardaud", "Enrique Zamudio") license ("http://www.apache.org/licenses/LICENSE-2.0.html") module ceylon.language "1.1.0" {}
"The Ceylon language module containing the core definitions referred to by the [language specification][spec], along with some basic functionality of use to most programs: - The [[root package|package ceylon.language]] defines general-purpose functionality including support for [[numbers|Numeric]] and [[character strings|String]], [[streams|Iterable]] and [[sequences|Sequential]], [[exceptions|Throwable]], and [[null values|Null]]. - The Ceylon _metamodel_ is defined in [[package ceylon.language.meta]] and its subpackages [[package ceylon.language.meta.model]] and [[package ceylon.language.meta.declaration]], which define interfaces for interacting with applied types and unapplied type declarations respectively. This module defines an abstraction over the basic facilities of the Java or JavaScript virtual machine, containing only functionality that can be easily implemented on both platforms. Thus, certain functionality, for example, concurrency, for which there is no common virtual machine-agnostic model, is not covered by the language module. The language module is an implicit dependency of every other Ceylon module, and may not be explicitly imported. [spec]: http://ceylon-lang.org/documentation/current/spec" by ("Gavin King", "Tom Bentley", "Tako Schotanus", "Stephane Epardaud", "Enrique Zamudio") license ("http://www.apache.org/licenses/LICENSE-2.0.html") module ceylon.language "1.1.0" {}
Add usage example to ScopedKey documentation
import ceylon.language.meta.declaration { AnnotatedDeclaration } "A key by which a [[Node]]’s additional information can be accessed." shared class Key<Type>(name) given Type satisfies Object { "The name of this key. To avoid collisions with other keys, some use-site ID should be included, e. g. the name of the module that uses this key." see (`class ScopedKey`) String name; "A unique ID of this key, composed of the [[name]] argument and the [[Type]] type argument." shared String id = "`` `Type`.string ``:::``name``"; string => id; shared actual Boolean equals(Object that) { if (is Key<Type> that) { return id == that.id; } else { return false; } } hash => id.hash; } "A [[Key]] with an explicitly provided scope, to avoid name collisions." shared class ScopedKey<Type>(scope, name) extends Key<Type>("``scope.string``:::``name.string``") given Type satisfies Object { "The scope of this key, that is, the declaration of the program element that uses it. Most commonly the declaration of the enclosing class, package or module." AnnotatedDeclaration scope; "The name of this key. Unlike [[Key.name]], this name shouldn’t include some use-site ID, because that’s already provided by [[scope]]." String name; }
import ceylon.language.meta.declaration { AnnotatedDeclaration } "A key by which a [[Node]]’s additional information can be accessed." shared class Key<Type>(name) given Type satisfies Object { "The name of this key. To avoid collisions with other keys, some use-site ID should be included, e. g. the name of the module that uses this key." see (`class ScopedKey`) String name; "A unique ID of this key, composed of the [[name]] argument and the [[Type]] type argument." shared String id = "`` `Type`.string ``:::``name``"; string => id; shared actual Boolean equals(Object that) { if (is Key<Type> that) { return id == that.id; } else { return false; } } hash => id.hash; } "A [[Key]] with an explicitly provided scope, to avoid name collisions. Usage example: shared Key<Token[]> tokensKey = ScopedKey<Token[]>(`class CeylonParser`, \"tokens\");" shared class ScopedKey<Type>(scope, name) extends Key<Type>("``scope.string``:::``name.string``") given Type satisfies Object { "The scope of this key, that is, the declaration of the program element that uses it. Most commonly the declaration of the enclosing class, package or module." AnnotatedDeclaration scope; "The name of this key. Unlike [[Key.name]], this name shouldn’t include some use-site ID, because that’s already provided by [[scope]]." String name; }
Add test for callable parameters with type parameters
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); }
interface SecondOrder<Box> given Box<Value> { shared formal Box<Float> createBox(Float float); } void takesCallableParamWithTypeParam(T f<T>(T t)) {}
Fix typo in doc text
import ceylon.io.impl { InputStreamAdapter, OutputStreamAdapter } import java.lang { System { javaIn=\iin, javaOut=\iout, javaErr=err } } "A [[ReadableFileDescriptor]] for the virtual machine's standard input" ReadableFileDescriptor stdin = InputStreamAdapter(javaIn); "A [[WritableFileDescriptor]] for the virtual machine's standard output stream." WritableFileDescriptor stdout = OutputStreamAdapter(javaOut); "A [[WritableFileDescriptor]] for the virtual machine's standard error stream." WritableFileDescriptor stderr = OutputStreamAdapter(javaErr);
import ceylon.io.impl { InputStreamAdapter, OutputStreamAdapter } import java.lang { System { javaIn=\iin, javaOut=\iout, javaErr=err } } "A [[ReadableFileDescriptor]] for the virtual machine's standard input stream." ReadableFileDescriptor stdin = InputStreamAdapter(javaIn); "A [[WritableFileDescriptor]] for the virtual machine's standard output stream." WritableFileDescriptor stdout = OutputStreamAdapter(javaOut); "A [[WritableFileDescriptor]] for the virtual machine's standard error stream." WritableFileDescriptor stderr = OutputStreamAdapter(javaErr);
Add missing switch type cases to typeToCeylon
import ceylon.ast.api { Type } import com.redhat.ceylon.compiler.typechecker.tree { Tree { JGroupedType=GroupedType, JSimpleType=SimpleType, JStaticType=StaticType } } import ceylon.ast.redhat { groupedTypeToCeylon, createParser, simpleTypeToCeylon } "Converts a RedHat AST [[StaticType|JStaticType]] to a `ceylon.ast` [[Type]]." shared Type typeToCeylon(JStaticType type) { switch (type) case (is JSimpleType) { return simpleTypeToCeylon(type); } case (is JGroupedType) { return groupedTypeToCeylon(type); } else { throw Error("Not yet implemented!"); // TODO } } "Compiles the given [[code]] for a Type into a [[Type]] using the Ceylon compiler (more specifically, the rule for a `type`)." shared Type? compileType(String code) { if (exists jType = createParser(code).type()) { return typeToCeylon(jType); } else { return null; } }
import ceylon.ast.api { Type } import com.redhat.ceylon.compiler.typechecker.tree { Tree { JGroupedType=GroupedType, JIterableType=IterableType, JOptionalType=OptionalType, JSequenceType=SequenceType, JSimpleType=SimpleType, JStaticType=StaticType, JTupleType=TupleType } } import ceylon.ast.redhat { groupedTypeToCeylon, createParser, simpleTypeToCeylon } "Converts a RedHat AST [[StaticType|JStaticType]] to a `ceylon.ast` [[Type]]." shared Type typeToCeylon(JStaticType type) { switch (type) case (is JSimpleType) { return simpleTypeToCeylon(type); } case (is JTupleType) { return tupleTypeToCeylon(type); } case (is JIterableType) { return iterableTypeToCeylon(type); } case (is JGroupedType) { return groupedTypeToCeylon(type); } case (is JOptionalType) { return optionalTypeToCeylon(type); } case (is JSequenceType) { return sequentialTypeToCeylon(type); } else { throw Error("Not yet implemented!"); // TODO } } "Compiles the given [[code]] for a Type into a [[Type]] using the Ceylon compiler (more specifically, the rule for a `type`)." shared Type? compileType(String code) { if (exists jType = createParser(code).type()) { return typeToCeylon(jType); } else { return null; } }
Fix for sequenced args and iterables
import ceylon.file { ... } import java.nio.file { JPath=Path, Files { movePath=move, newDirectoryStream } } class ConcreteDirectory(JPath jpath) extends ConcreteExistingResource(jpath) satisfies Directory { shared actual Iterable<Path> childPaths(String filter) { //TODO: efficient impl value sb = SequenceBuilder<Path>(); value stream = newDirectoryStream(jpath, filter); value iter = stream.iterator(); while (iter.hasNext()) { sb.append(ConcretePath(iter.next())); } stream.close(); return sb.sequence; } shared actual Iterable<ExistingResource> children(String filter) { return elements { for (p in childPaths(filter)) if (is ExistingResource r=p.resource) r }; } shared actual Iterable<File> files(String filter) { return elements { for (p in childPaths(filter)) if (is File r=p.resource) r }; } shared actual Iterable<Directory> childDirectories(String filter) { return elements { for (p in childPaths(filter)) if (is Directory r=p.resource) r }; } shared actual Resource childResource(Path|String subpath) { return path.childPath(subpath).resource; } shared actual Directory move(Nil target) { return ConcreteDirectory( movePath(jpath, asJPath(target.path)) ); } }
import ceylon.file { ... } import java.nio.file { JPath=Path, Files { movePath=move, newDirectoryStream } } class ConcreteDirectory(JPath jpath) extends ConcreteExistingResource(jpath) satisfies Directory { shared actual Iterable<Path> childPaths(String filter) { //TODO: efficient impl value sb = SequenceBuilder<Path>(); value stream = newDirectoryStream(jpath, filter); value iter = stream.iterator(); while (iter.hasNext()) { sb.append(ConcretePath(iter.next())); } stream.close(); return sb.sequence; } shared actual Iterable<ExistingResource> children(String filter) { return elements { {for (p in childPaths(filter)) if (is ExistingResource r=p.resource) r}... }; } shared actual Iterable<File> files(String filter) { return elements { {for (p in childPaths(filter)) if (is File r=p.resource) r}... }; } shared actual Iterable<Directory> childDirectories(String filter) { return elements { {for (p in childPaths(filter)) if (is Directory r=p.resource) r}... }; } shared actual Resource childResource(Path|String subpath) { return path.childPath(subpath).resource; } shared actual Directory move(Nil target) { return ConcreteDirectory( movePath(jpath, asJPath(target.path)) ); } }
Fix whole array assign test
use myrecord; proc myfunction() { var A:[1..10] R; for i in 1..10 { A[i].verify(); A[i].init(x=i); A[i].verify(); assert(A[i].x == i); } } myfunction();
use myrecord; proc myfunction() { var A:[1..10] R; for i in 1..10 { A[i].verify(); A[i].init(x=i); A[i].verify(); assert(A[i].x == i); } var B:[1..10] R; B = A; for i in 1..10 { B[i].verify(); assert(B[i].x == i); } } myfunction();
Add record with secondary method to chpldoc/ tests.
/* This class will declare a method inside itself, but will have a method declared outside it as well */ class Foo { proc internalMeth() { } } // We expect these two methods to be printed outside of the class indentation // level proc Foo.externalMeth1() { } /* This method has a comment attached to it */ proc Foo.externalMeth2() { }
/* This class will declare a method inside itself, but will have a method declared outside it as well */ class Foo { proc internalMeth() { } } // We expect these two methods to be printed outside of the class indentation // level proc Foo.externalMeth1() { } /* This method has a comment attached to it */ proc Foo.externalMeth2() { } /* Declares one primary and one secondary method... */ record Bar { /* A primary method declaration. */ proc internal() {} } /* A secondary method declaration. */ proc Bar.external() {}
Set up svn:ignore on a directory
def foo() { } def bar() { } var done: single bool; def timeout(n: uint) { use Time; begin { sleep(n); exit(1); } begin { done; exit(0); } } timeout(30); // exit after 30 seconds or when done is set. for i in 1..100000 { cobegin { cobegin { bar(); foo(); } cobegin { bar(); foo(); } cobegin { bar(); foo(); } cobegin { bar(); foo(); } } if i % 10000 == 0 then writeln("iteration ", i, " done."); } done = true;
def foo() { } def bar() { } var done: single bool; def timeout(n: uint) { use Time; begin { sleep(n); writeln("Timeout"); exit(1); } begin { done; exit(0); } } timeout(30); // exit after 30 seconds or when done is set. for i in 1..100000 { cobegin { cobegin { bar(); foo(); } cobegin { bar(); foo(); } cobegin { bar(); foo(); } cobegin { bar(); foo(); } } if i % 10000 == 0 then writeln("iteration ", i, " done."); } done = true;
Update solution 5 to work with new-and-improved constness checking.
/* * Smallest multiple */ config const rangeMax = 20; const values: [{1..rangeMax}] int; forall i in 1..rangeMax { values[i] = i; } proc isMultiple(value: int, numbers: [] int) { for num in numbers { if value % num != 0 { return false; } } return true; } // Return least common multiple for list of ints. proc lcm(numbers: [] int) { var maxNum = max reduce numbers, value = maxNum; while (!isMultiple(value, numbers)) { value += maxNum; } return value; } writeln(lcm(values));
/* * Smallest multiple */ config const rangeMax = 20; const values: [{1..rangeMax}] int = [i in 1..rangeMax] i; proc isMultiple(value: int, numbers: [] int) { for num in numbers { if value % num != 0 { return false; } } return true; } // Return least common multiple for list of ints. proc lcm(numbers: [] int) { var maxNum = max reduce numbers, value = maxNum; while (!isMultiple(value, numbers)) { value += maxNum; } return value; } writeln(lcm(values));
Update one last test to the new task intent syntax
config const n = 11; var s0 = "kiss kiss"; var l0: atomic int; var l1: atomic int; writeln(s0); begin ref(s0) { l0.waitFor(1); s0 = "bang bang"; l1.write(1); } on Locales[numLocales-1] { l0.write(1); l1.waitFor(1); writeln(s0); }
config const n = 11; var s0 = "kiss kiss"; var l0: atomic int; var l1: atomic int; writeln(s0); begin with (ref s0) { l0.waitFor(1); s0 = "bang bang"; l1.write(1); } on Locales[numLocales-1] { l0.write(1); l1.waitFor(1); writeln(s0); }
Update solution 12 to avoid overflow.
/* * Highly divisible triangular number */ config const minDivisors = 500, printNumbers = false; proc main() { for t in triangleNumbers() { if printNumbers then writef("%di: ", t); var count = 0; for f in factors(t) { count += 1; if printNumbers then writef("%di, ", f); } if printNumbers then writeln(); if count > minDivisors { writeln(t); break; } } } // Yield all the factors of n. iter factors(n) { // Yield 1 and n first, then all intermediate factors. yield 1; yield n; var i = 2; while (i < sqrt(n)) { if n % i == 0 { yield i; yield n / i; } i += 1; } if i ** 2 == n { yield i; } } // Yield triangle numbers infinitely. Up to caller to break iteration. iter triangleNumbers() { var num = 1, triangleNum = num; for i in 1..max(int) { yield triangleNum; num += 1; triangleNum += num; } }
/* * Highly divisible triangular number */ config const minDivisors = 500, printNumbers = false; proc main() { for t in triangleNumbers() { if printNumbers then writef("%n: ", t); var count = 0; for f in factors(t) { count += 1; if printNumbers then writef("%n, ", f); } if printNumbers then writeln(); if count > minDivisors { writeln(t); break; } } } // Yield all the factors of n. iter factors(n) { // Yield 1 and n first, then all intermediate factors. yield 1; yield n; var i = 2; while (i < sqrt(n)) { if n % i == 0 { yield i; yield n / i; } i += 1; } if i ** 2 == n { yield i; } } // Yield triangle numbers for all integer values. Up to caller to break // iteration. iter triangleNumbers() { var triangleNum = 1; for num in 2..max(int)-1 { yield triangleNum; triangleNum += num; } }
Change extern prototypes to specify c_string instead of string
extern proc return_string_test():string; extern proc return_string_arg_test(ref string); writeln("returned string ",return_string_test()); stdout.flush(); var s:string; on Locales(1) do return_string_arg_test(s); writeln("returned string arg ",s);
extern proc return_string_test():c_string; extern proc return_string_arg_test(ref c_string); writeln("returned string ",return_string_test()); stdout.flush(); var s:string; on Locales(1) do return_string_arg_test(s); writeln("returned string arg ",s);
Use a ref instead of an alias operation
var %(aname)s__defaultRect = pych_to_chpl1D(%(aname)s_pych); var %(aname)s => _getArray(%(aname)s__defaultRect);
var %(aname)s__defaultRect = pych_to_chpl1D(%(aname)s_pych); ref %(aname)s = _getArray(%(aname)s__defaultRect);
Update to new zip() syntax.
iter foo(n: int) { for i in 1..n do yield i; } iter foo(param tag: iterKind, n: int) where tag == iterKind.leader { cobegin { on Locales(0) do yield tuple(0..n-1 by 2); on Locales(1) do yield tuple(1..n-1 by 2); } } iter foo(param tag: iterKind, followThis, n: int) where tag == iterKind.follower { for i in followThis(1)+1 do yield i; } config var n: int = 8; var A: [1..n] int; forall i in foo(n) do A(i) = here.id * 100 + i; writeln(A); use Random; { var B: [1..n] real; var rs = new RandomStream(seed=315); forall (i, r) in ({1..n}, rs.iterate({1..n})) do B(i) = r; writeln(B); } { var B: [1..n] real; var rs = new RandomStream(seed=315); forall (f, r) in (foo(n), rs.iterate({1..n})) do B(f) = r; writeln(B); }
iter foo(n: int) { for i in 1..n do yield i; } iter foo(param tag: iterKind, n: int) where tag == iterKind.leader { cobegin { on Locales(0) do yield tuple(0..n-1 by 2); on Locales(1) do yield tuple(1..n-1 by 2); } } iter foo(param tag: iterKind, followThis, n: int) where tag == iterKind.follower { for i in followThis(1)+1 do yield i; } config var n: int = 8; var A: [1..n] int; forall i in foo(n) do A(i) = here.id * 100 + i; writeln(A); use Random; { var B: [1..n] real; var rs = new RandomStream(seed=315); forall (i, r) in zip({1..n}, rs.iterate({1..n})) do B(i) = r; writeln(B); } { var B: [1..n] real; var rs = new RandomStream(seed=315); forall (f, r) in zip(foo(n), rs.iterate({1..n})) do B(f) = r; writeln(B); }
Fix race condition that was causing valgrind testing non-determinism
use Time; config const numIters = 100000; proc main() { begin doSomeWork(); // while original task exits writeln("Original task falling out of main"); } proc doSomeWork() { for i in 1..numIters { write(""); stdout.flush(); } writeln("done working"); }
use Time; config const numIters = 100000; var s$: sync bool; proc main() { begin doSomeWork(); // while original task exits writeln("Original task falling out of main"); s$ = true; } proc doSomeWork() { s$; for i in 1..numIters { write(""); stdout.flush(); } writeln("done working"); }
Fix nondeterministic output from walkdir() by requesting sorted output
use Filerator; for dir in walkdirs("subdir") { writeln("dir ", dir, " contains:"); for file in glob(dir+"/*") do writeln(" ", file); }
use Filerator; for dir in walkdirs("subdir", sort=true) { writeln("dir ", dir, " contains:"); for file in glob(dir+"/*") do writeln(" ", file); }
Change an incorrect bracket syntax forall expression into a for expression for a loop that needs to be serial.
// Calcuate pi using a monte carlo simulation use Random, Time; config const n = 10000, seed = 314159; config const verbose: bool = false; var count:int; var pi, startTime, totalTime: real; var rs = RandomStream(seed); startTime = getCurrentTime(microseconds); // Find random points on the complex plane in (0..1+i) // and count how many are outside the unit circle. count = + reduce [1..n] abs(rs.getNext()**2 + rs.getNext()**2):int; // The probability a point is inside the unit circle is pi / 4. pi = 4 * (n-count):real(64) / n; // Write out the results writeln(pi); totalTime = (getCurrentTime(microseconds) - startTime) / 1000000; if (verbose) then writeln("Calculation took: ", totalTime, " seconds");
// Calcuate pi using a monte carlo simulation use Random, Time; config const n = 10000, seed = 314159; config const verbose: bool = false; var count:int; var pi, startTime, totalTime: real; var rs = RandomStream(seed); startTime = getCurrentTime(microseconds); // Find random points on the complex plane in (0..1+i) // and count how many are outside the unit circle. count = + reduce for 1..n do abs(rs.getNext()**2 + rs.getNext()**2):int; // The probability a point is inside the unit circle is pi / 4. pi = 4 * (n-count):real(64) / n; // Write out the results writeln(pi); totalTime = (getCurrentTime(microseconds) - startTime) / 1000000; if (verbose) then writeln("Calculation took: ", totalTime, " seconds");
Change the last forall loop in this reduction test to make it deterministic.
// Test logical AND and OR reductions param M = 10; var D: domain(1) = [1..M]; var B: [D] bool; forall i in D do { B(i) = true; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B); forall i in D do { B(i) = false; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B); var toggle: sync bool = false; forall i in D do { var my_toggle = !toggle; toggle = my_toggle; B(i) = my_toggle; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B);
// Test logical AND and OR reductions param M = 10; var D: domain(1) = [1..M]; var B: [D] bool; forall i in D do { B(i) = true; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B); forall i in D do { B(i) = false; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B); forall i in D do { var toggle: bool = i % 2 == 1; B(i) = toggle; } writeln( "\nB[D] = ", B); writeln( "&& reduce B[D] = ", && reduce B); writeln( "|| reduce B[D] = ", || reduce B);
Add test from commit message
writef("###\n", 1.1); writef("###.\n", 1.1); writef("###..\n", 1.1); writef("###.##\n", 1.1); writef("%{###}.##\n", 1.1, 2.2); writef("%{###.}##\n", 1.1, 2.2); writef("%{###}%{###}\n", 1.1, 2.2); writef("%{#.#}#.#%{#.#}\n", 1.1, 2.2, 3.3); writef("%{#}#%{#}\n", 1.1, 2.2, 3.3);
writef("###\n", 1.1); writef("###.\n", 1.1); writef("###..\n", 1.1); writef("###.##\n", 1.1); writef("%{###}.##\n", 1.1, 2.2); writef("%{###.}##\n", 1.1, 2.2); writef("%{###}%{###}\n", 1.1, 2.2); writef("%{#.#}#.#%{#.#}\n", 1.1, 2.2, 3.3); writef("%{#}#%{#}\n", 1.1, 2.2, 3.3); writef("%{#.#}.%{#.#}\n", 1.2, 3.4);
Make the seed to the RandomStream class in my QuickSort test be set to something that causes the "infinite" loop failure instead of the current time.
// A test of the QuickSort function in the Sort module use Sort; use Random; config const size = 4096; def main() { var A: [1..size] int; var rands: [1..size] real; var randomStream = RandomStream(); // Fill A with random int values in [0, 99999] randomStream.fillRandom(rands); [i in 1..size] A(i) = (100000 * rands(i)):int; QuickSort(A); // Check that A is sorted [i in 1..size-1] { if A(i) > A(i+1) then writeln(A(i), " ", A(i+1)); } }
// A test of the QuickSort function in the Sort module use Sort; use Random; config const size = 4096; config const seed = 27; def main() { var A: [1..size] int; var rands: [1..size] real; var randomStream = RandomStream(seed); // Fill A with random int values in [0, 99999] randomStream.fillRandom(rands); [i in 1..size] A(i) = (100000 * rands(i)):int; QuickSort(A); // Check that A is sorted [i in 1..size-1] { if A(i) > A(i+1) then writeln(A(i), " ", A(i+1)); } }
Set a maximum problem size to avoid timeouts
// // Measures both array iteration and array access time // use Memory, Time, Types; config const zipIter = false; config const memFraction = 100; config const printPerf = false; type elemType = uint(8); const totalMem = here.physicalMemory(unit = MemUnits.Bytes); const n = (totalMem / numBytes(elemType)) / memFraction; const space = 1..n; var data : [space] elemType; var x : elemType = 2; var time : Timer; time.start(); if zipIter { forall (i, j) in zip(data, data) with (ref x) do x *= i; } else { forall i in data with (ref x) do x *= i; } time.stop(); if printPerf then writeln("Time: ", time.elapsed());
// // Measures both array iteration and array access time // use Memory, Time, Types; config const zipIter = false; config const memFraction = 100; config const printPerf = false; type elemType = uint(8); const totalMem = here.physicalMemory(unit = MemUnits.Bytes); const target = (totalMem / numBytes(elemType)) / memFraction; // set a maximum problem size const n = min(target, 8 * 1e9) : int; const space = 1..n; var data : [space] elemType; var x : elemType = 2; var time : Timer; time.start(); if zipIter { forall (i, j) in zip(data, data) with (ref x) do x *= i; } else { forall i in data with (ref x) do x *= i; } time.stop(); if printPerf then writeln("Time: ", time.elapsed());
Change initialization to avoid numerical instability.
config const n = 100; config const shift = 2; config type myType = real; use Random; var randlist = new RandomStream(314159265); var T: [1..n] real; randlist.fillRandom(T); proc foo(type myType) { var A = (T*(1<<shift):real):myType; var x: sync myType = 0:myType; forall i in 1..n do x += A[i]; var sum = + reduce A; // This check could run into troubles with floating point types if x.readXX() != sum then writeln("ERROR: sums do not match for ", typeToString(myType), " (should be ", sum, ", result is ", x.readXX(), ")"); } foo(int(32)); foo(int(64)); foo(uint(32)); foo(uint(64)); foo(real(32)); foo(real(64));
config const n = 100; config type myType = real; var T: [1..n] real; [i in 1..n] T[i] = i*1.01; proc foo(type myType) { var A = T:myType; var x: sync myType = 0:myType; forall i in 1..n do x += A[i]; var sum = + reduce A; if x.readXX() != sum then writeln("ERROR: sums do not match for ", typeToString(myType), " (should be ", sum, ", result is ", x.readXX(), ")"); } foo(int(32)); foo(int(64)); foo(uint(32)); foo(uint(64)); foo(real(32)); foo(real(64));
Update error message to be more helpful.
/* * Open a file and confirm its FS type is lustre. */ use IO; var fp = open("SKIPIF", iomode.r), fileType = fp.fstype(); if fileType == FTYPE_LUSTRE { writeln("SUCCESS"); } else { writeln("FAILURE"); }
/* * Open a file and confirm its FS type is lustre. */ use IO; const fsTypes: [{0..3}] string = [ "none", "hdfs", "UNKNOWN", // lustre is LUSTRE_SUPER_MAGIC (whatever that is) "curl" ]; var fp = open("SKIPIF", iomode.r), fileType = fp.fstype(); if fileType == FTYPE_LUSTRE { writeln("SUCCESS"); } else { writef("FAILURE: Expected FTYPE_LUSTRE (%n), actual: %s (%n)\n", FTYPE_LUSTRE, fsTypes[fileType], fileType); }
Fix my spin wait -> sync var change
var a: sync int; var b = 0; cobegin { { b = 1; while (a < 3) { b = 2; } } a = 1; a += 1; a += 1; } if (b==2) then { writeln ("b is good"); } else { writeln ("b is bad"); }
var a: sync int; var b = 0; cobegin { { b = 1; while (a < 3) { b = 2; } } { a = 1; a = 2; a = 3; } } if (b==2) then { writeln ("b is good"); } else { writeln ("b is bad: ", b); }
Reduce problem size to avoid timeouts on non-performance configurations
// // Measures both array iteration and array access time // use Memory, Time, Types; config const zipIter = false; config const memFraction = 16; config const printPerf = false; type elemType = uint(8); const totalMem = here.physicalMemory(unit = MemUnits.Bytes); const n = (totalMem / numBytes(elemType)) / memFraction; const space = 1..n; var data : [space] elemType; var x : elemType = 2; var time : Timer; time.start(); if zipIter { forall (i, j) in zip(data, data) with (ref x) do x *= i; } else { forall i in data with (ref x) do x *= i; } time.stop(); if printPerf then writeln("Time: ", time.elapsed());
// // Measures both array iteration and array access time // use Memory, Time, Types; config const zipIter = false; config const memFraction = 100; config const printPerf = false; type elemType = uint(8); const totalMem = here.physicalMemory(unit = MemUnits.Bytes); const n = (totalMem / numBytes(elemType)) / memFraction; const space = 1..n; var data : [space] elemType; var x : elemType = 2; var time : Timer; time.start(); if zipIter { forall (i, j) in zip(data, data) with (ref x) do x *= i; } else { forall i in data with (ref x) do x *= i; } time.stop(); if printPerf then writeln("Time: ", time.elapsed());
Test script for VMS (eol=CR; not sure if that is necessary; native might be better)
$!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $! $! 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. $! $!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $! $! Run the test suite $! $ create/directory [.target] $ java "-Dorg.apache.commons.exec.lenient=false" "-Dorg.apache.commons.exec.debug=false" - -cp "./lib/junit-3.8.1.jar:./lib/exec-test-1.0-SNAPSHOT.jar:./lib/exec-1.0-SNAPSHOT.jar" - "org.apache.commons.exec.TestRunner"
Use yada's new stop method
;; Copyright © 2016, JUXT LTD. (ns edge.server (:require [aleph.http :as http] [bidi.vhosts :refer [make-handler vhosts-model]] [clojure.java.io :as io] [clojure.tools.logging :refer :all] [com.stuartsierra.component :refer [Lifecycle using]] [schema.core :as s] [yada.yada :refer [yada resource] :as yada]) (:import [bidi.vhosts VHostsModel])) (s/defrecord HttpServer [port :- s/Int routes server] Lifecycle (start [component] (assoc component :server (yada/server routes {:port port}))) (stop [component] (when-let [server (:server component)] (.close server)) component)) (defn new-http-server [options] (map->HttpServer options))
;; Copyright © 2016, JUXT LTD. (ns edge.server (:require [aleph.http :as http] [bidi.vhosts :refer [make-handler vhosts-model]] [clojure.java.io :as io] [clojure.tools.logging :refer :all] [com.stuartsierra.component :refer [Lifecycle using]] [schema.core :as s] [yada.yada :refer [yada resource] :as yada]) (:import [bidi.vhosts VHostsModel])) (s/defrecord HttpServer [port :- s/Int routes server] Lifecycle (start [component] (assoc component :server (yada/server routes {:port port}))) (stop [component] (when-let [close (get-in component [:server :close])] (close)) component)) (defn new-http-server [options] (map->HttpServer options))
Implement break function for newline/paragraph breaks
(ns merkki.core) (defn header "Given a number and a string, tags the string as that header level and adds a new line" [n s] (str (reduce str (take n (repeat "#"))) " " s " \n")) ;; Pre-provided curried versions of header for quicker use (def h1 (partial header 1)) (def h2 (partial header 2)) (def h3 (partial header 3)) (def h4 (partial header 4)) (def h5 (partial header 5)) (def h6 (partial header 6)) (defn u-header "Generates an underlined, multi-line setext style header, using the given underline character" [ch s] (str s " \n" (reduce str (take (count s) (repeat ch))) " \n")) ;; Pre-provided curried versions of u-header for h1 and h2 (def uh1 (partial u-header "=")) (def uh2 (partial u-header "-")) (defn em "Wraps string for emphasis" [s] (str "*" s "*")) (defn strong "Wraps string for strong emphasis" [s] (str "**" s "**"))
(ns merkki.core) (defn break "Markdown standard allows hard-wrapping by not creating a new paragraph block automatically on new line. In order to guarantee that a <br>/newline is produced, a line must end in two spaces followed by new line. See: https://daringfireball.net/projects/markdown/syntax#p" [s] (str s " \n")) (defn header "Given a number and a string, tags the string as that header level and adds a new line" [n s] (str (reduce str (take n (repeat "#"))) " " (break s))) ;; Pre-provided curried versions of header for quicker use (def h1 (partial header 1)) (def h2 (partial header 2)) (def h3 (partial header 3)) (def h4 (partial header 4)) (def h5 (partial header 5)) (def h6 (partial header 6)) (defn u-header "Generates an underlined, multi-line setext style header, using the given underline character" [ch s] (str (break s) (break (reduce str (take (count s) (repeat ch)))))) ;; Pre-provided curried versions of u-header for h1 and h2 (def uh1 (partial u-header "=")) (def uh2 (partial u-header "-")) (defn em "Wraps string for emphasis" [s] (str "*" s "*")) (defn strong "Wraps string for strong emphasis" [s] (str "**" s "**"))
Revert "(SERVER-262) Remove JARS_NO_REQUIRE failing test"
(ns puppetlabs.puppetserver.cli.gem-test (:require [clojure.test :refer :all] [puppetlabs.puppetserver.cli.gem :refer :all])) (deftest cli-gem-environment-test (let [fake-config {:jruby-puppet {:gem-home "/fake/path"}} fake-env {"PATH" "/bin:/usr/bin", "FOO_DEBUG" "1"}] (testing "The environment intended for the gem subcommand" (is (not (empty? ((cli-gem-environment fake-config fake-env) "PATH"))) "has a non-empty PATH originating from the System") (is (= "/bin:/usr/bin" ((cli-gem-environment fake-config fake-env) "PATH")) "does not modify the PATH environment variable") (is (= "/fake/path" ((cli-gem-environment fake-config fake-env) "GEM_HOME")) "has GEM_HOME set to /fake/path from the provided config") (is (= "1" ((cli-gem-environment fake-config fake-env) "FOO_DEBUG")) "preserves arbitrary environment vars for the end user"))))
(ns puppetlabs.puppetserver.cli.gem-test (:require [clojure.test :refer :all] [puppetlabs.puppetserver.cli.gem :refer :all])) (deftest cli-gem-environment-test (let [fake-config {:jruby-puppet {:gem-home "/fake/path"}} fake-env {"PATH" "/bin:/usr/bin", "FOO_DEBUG" "1"}] (testing "The environment intended for the gem subcommand" (is (not (empty? ((cli-gem-environment fake-config fake-env) "PATH"))) "has a non-empty PATH originating from the System") (is (= "/bin:/usr/bin" ((cli-gem-environment fake-config fake-env) "PATH")) "does not modify the PATH environment variable") (is (= "/fake/path" ((cli-gem-environment fake-config fake-env) "GEM_HOME")) "has GEM_HOME set to /fake/path from the provided config") (is (= "true" ((cli-gem-environment fake-config fake-env) "JARS_NO_REQUIRE")) "has JARS_NO_REQUIRE set to true") (is (= "1" ((cli-gem-environment fake-config fake-env) "FOO_DEBUG")) "preserves arbitrary environment vars for the end user"))))
Update to latest tesla microservice version
(defproject de.otto/tesla-httpkit "0.1.5" :description "httpkit addon for tesla-microservice." :url "https://github.com/otto-de/tesla-httpkit" :license {:name "Apache License 2.0" :url "http://www.apache.org/license/LICENSE-2.0.html"} :scm {:name "git" :url "https://github.com/otto-de/tesla-httpkit"} :dependencies [[org.clojure/clojure "1.7.0"] [http-kit "2.1.19"]] :exclusions [org.clojure/clojure org.slf4j/slf4j-nop org.slf4j/slf4j-log4j12 log4j commons-logging/commons-logging] :profiles {:provided {:dependencies [[de.otto/tesla-microservice "0.1.26"] [com.stuartsierra/component "0.3.1"]]} :dev {:dependencies [[javax.servlet/servlet-api "2.5"] [org.slf4j/slf4j-api "1.7.14"] [ch.qos.logback/logback-core "1.1.3"] [ch.qos.logback/logback-classic "1.1.3"] [ring-mock "0.1.5"]] :plugins [[lein-ancient "0.5.4"]]}} :test-paths ["test" "test-resources"])
(defproject de.otto/tesla-httpkit "0.1.5" :description "httpkit addon for tesla-microservice." :url "https://github.com/otto-de/tesla-httpkit" :license {:name "Apache License 2.0" :url "http://www.apache.org/license/LICENSE-2.0.html"} :scm {:name "git" :url "https://github.com/otto-de/tesla-httpkit"} :dependencies [[org.clojure/clojure "1.7.0"] [http-kit "2.1.19"]] :exclusions [org.clojure/clojure org.slf4j/slf4j-nop org.slf4j/slf4j-log4j12 log4j commons-logging/commons-logging] :profiles {:provided {:dependencies [[de.otto/tesla-microservice "0.1.32"] [com.stuartsierra/component "0.3.1"]]} :dev {:dependencies [[javax.servlet/servlet-api "2.5"] [org.slf4j/slf4j-api "1.7.14"] [ch.qos.logback/logback-core "1.1.3"] [ch.qos.logback/logback-classic "1.1.3"] [ring-mock "0.1.5"]] :plugins [[lein-ancient "0.5.4"]]}} :test-paths ["test" "test-resources"])