content
stringlengths
128
6.74k
<commit_msg>Remove redundant access modifiers. PL-11097. <commit_before>package com.amee.restlet; import org.restlet.data.Status; public interface Fault { public String getMessage(); public Status getStatus(); public String getCode(); } <commit_after>package com.amee.restlet; import org.restlet.data.Status; public interface Fault { String getMessage(); Status getStatus(); String getCode(); }
<commit_msg>Add empty constructor for Word object <commit_before>/** * word.cpp * Copyright (C) 2015 Tony Lim <atomictheorist@gmail.com> * * Distributed under terms of the MIT license. */ #include "word.h" namespace NLP { Word::Word(const Token &other, set<WordType> tags, set<string> defs) : Token::Token(other), mTypes(tags), mDefinitions(defs) { } Word::Word(const Word &other) : Token ( other.getTokenString() , other.getType() ), mTypes ( other.getTypes() ), mDefinitions ( other.getDefinitions() ) { } std::set<WordType> Word::getTypes() const { return mTypes; } string Word::getRawtypes() const { string rawT; for(WordType WT : mTypes) rawT += WordStringMap[WT] + string(" ,"); return rawT.substr(0,rawT.length() - 2); } std::set<string> Word::getDefinitions() const { return mDefinitions; } string Word::getName() const { return getTokenString(); } /** * @brief Do nothing */ Word::~Word() { } } /* NLP */ <commit_after>/** * word.cpp * Copyright (C) 2015 Tony Lim <atomictheorist@gmail.com> * * Distributed under terms of the MIT license. */ #include "word.h" namespace NLP { Word::Word() : Token() { } Word::Word(const Token &other, set<WordType> tags, set<string> defs) : Token::Token(other), mTypes(tags), mDefinitions(defs) { } Word::Word(const Word &other) : Token ( other.getTokenString() , other.getType() ), mTypes ( other.getTypes() ), mDefinitions ( other.getDefinitions() ) { } Word &Word::operator =(const Word &newToken) { this->mType = newToken.getType(); mTypes = newToken.getTypes(); mDefinitions = newToken.getDefinitions(); } std::set<WordType> Word::getTypes() const { return mTypes; } string Word::getRawtypes() const { string rawT; for(WordType WT : mTypes) rawT += WordStringMap[WT] + string(" ,"); return rawT.substr(0,rawT.length() - 2); } std::set<string> Word::getDefinitions() const { return mDefinitions; } string Word::getName() const { return getTokenString(); } /** * @brief Do nothing */ Word::~Word() { } } /* NLP */
<commit_msg>Remove temp var allocation code. <commit_before>class Scope(object): tmp_index = 0 def __init__(self, parent=None): self.parent = parent self.prefix = [] self.declarations = {} self.globals = set() self.inherited = True def prefixed(self, name): return '.'.join(self.prefix + [name]) def declare(self, name, var=True): self.declarations[name] = var def get_scope(self, name, inherit=False): if name in self.declarations and (not inherit or self.inherited): return self elif self.parent is not None: return self.parent.get_scope(name, True) else: return None def declare_global(self, name): self.globals.add(name) def is_global(self, name): return name in self.globals def get_global_scope(self): if self.parent: return self.parent.get_global_scope() else: return self @classmethod def alloc_temp(cls): cls.tmp_index += 1 return '__jpx_tmp_%i' % cls.tmp_index <commit_after>class Scope(object): def __init__(self, parent=None): self.parent = parent self.prefix = [] self.declarations = {} self.globals = set() self.inherited = True def prefixed(self, name): return '.'.join(self.prefix + [name]) def declare(self, name, var=True): self.declarations[name] = var def get_scope(self, name, inherit=False): if name in self.declarations and (not inherit or self.inherited): return self elif self.parent is not None: return self.parent.get_scope(name, True) else: return None def declare_global(self, name): self.globals.add(name) def is_global(self, name): return name in self.globals def get_global_scope(self): if self.parent: return self.parent.get_global_scope() else: return self
<commit_msg>Upgrade Blink to milliseconds-based last modified filetimes, part 4. Have content::FileInfoToWebFileInfo() set the temporarily Blink-unused field WebFileInfo::modificationTime to something milliseconds-based Once landed, this is to allow Blink to switch to no longer using WebFileInfo::modificationTimeMS, but modificationTime only (again.) This is the fourth patch in the following series, 1: [blink] add WebFileInfo::modificationTimeMS [ https://codereview.chromium.org/873723004/ ] 2: [chromium] fill in modificationTimeMS [ https://codereview.chromium.org/884413002/ ] 3: [blink] make use of modificationTimeMS [ https://codereview.chromium.org/884393002/ ] 4: [chromium] *this one* [ https://codereview.chromium.org/862203003/ ] 5: [blink] switch to using modificationTime instead of *MS [ https://codereview.chromium.org/882343002/ ] 6: [chromium] stop setting modificationTimeMS [ https://codereview.chromium.org/890523002/ ] 7: [blink] remove modificationTimeMS [ https://codereview.chromium.org/869613005/ ] R=jochen BUG=451747 Review URL: https://codereview.chromium.org/862203003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#315322} <commit_before>// Copyright 2014 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 "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // WebKit now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToDoubleT(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content <commit_after>// Copyright 2014 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 "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // Blink now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToJsTime(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
<commit_msg>Add a prefix to the statsd key We have loads of stats at the top leve of our statsd stats in graphite. It makes looking for things that aren't created by backdrop really hard. <commit_before>import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv("GOVUK_STATSD_PREFIX"))) <commit_after>import os import statsd as _statsd __all__ = ['statsd'] class StatsClient(object): """Wrap statsd.StatsClient to allow data_set to be added to stat""" def __init__(self, statsd): self._statsd = statsd def __getattr__(self, item): if item in ['timer', 'timing', 'incr', 'decr', 'gauge']: def func(stat, *args, **kwargs): data_set = kwargs.pop('data_set', 'unknown') stat = '%s.%s' % (data_set, stat) return getattr(self._statsd, item)(stat, *args, **kwargs) return func else: return getattr(self._statsd, item) statsd = StatsClient( _statsd.StatsClient(prefix=os.getenv( "GOVUK_STATSD_PREFIX", "pp.apps.backdrop")))
<commit_msg>Make it work for Python 2 Gabbi is designed to work with both Python 2.7 and 3.4. <commit_before>"""Share utility functions.""" from urllib import parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/') <commit_after>"""Share utility functions.""" try: from urllib import parse except ImportError: import urllib as parse def get_route_value(environ, name): value = environ['wsgiorg.routing_args'][1][name] value = parse.unquote(value) return value.replace('%2F', '/')
<commit_msg>Remove need to set environment variables in test <commit_before>from contextlib import contextmanager from os import environ from unittest import TestCase class DownloadTests(TestCase): def test_denies_unknown_client(self): with self._given_clients('{"client1": "id1"}') as download: message, status = download('unknown_client') self.assertEqual(status, 403) @classmethod @contextmanager def _given_clients(cls, clients: str): environ['LOKOLE_CLIENTS'] = clients from opwen_email_server.api import client_read yield client_read.download del client_read <commit_after>from contextlib import contextmanager from unittest import TestCase from opwen_email_server.api import client_read from opwen_email_server.services.auth import EnvironmentAuth class DownloadTests(TestCase): def test_denies_unknown_client(self): with self.given_clients({'client1': 'id1'}): message, status = client_read.download('unknown_client') self.assertEqual(status, 403) @contextmanager def given_clients(self, clients): original_clients = client_read.CLIENTS client_read.CLIENTS = EnvironmentAuth(clients) yield client_read.CLIENTS = original_clients
<commit_msg>Add an IPI used for testing proper operation of delivering IPIs. <commit_before>/* * $FreeBSD$ */ #ifndef _MACHINE_SMP_H_ #define _MACHINE_SMP_H_ #ifdef _KERNEL /* * Interprocessor interrupts for SMP. The following values are indices * into the IPI vector table. The SAL gives us the vector used for AP * wake-up. Keep the IPI_AP_WAKEUP at index 0. */ #define IPI_AP_WAKEUP 0 #define IPI_AST 1 #define IPI_CHECKSTATE 2 #define IPI_INVLTLB 3 #define IPI_RENDEZVOUS 4 #define IPI_STOP 5 #define IPI_COUNT 6 #ifndef LOCORE extern int mp_hardware; extern int mp_ipi_vector[]; void ipi_all(int ipi); void ipi_all_but_self(int ipi); void ipi_selected(u_int64_t cpus, int ipi); void ipi_self(int ipi); #endif /* !LOCORE */ #endif /* _KERNEL */ #endif /* !_MACHINE_SMP_H */ <commit_after>/* * $FreeBSD$ */ #ifndef _MACHINE_SMP_H_ #define _MACHINE_SMP_H_ #ifdef _KERNEL /* * Interprocessor interrupts for SMP. The following values are indices * into the IPI vector table. The SAL gives us the vector used for AP * wake-up. Keep the IPI_AP_WAKEUP at index 0. */ #define IPI_AP_WAKEUP 0 #define IPI_AST 1 #define IPI_CHECKSTATE 2 #define IPI_INVLTLB 3 #define IPI_RENDEZVOUS 4 #define IPI_STOP 5 #define IPI_TEST 6 #define IPI_COUNT 7 #ifndef LOCORE extern int mp_hardware; extern int mp_ipi_vector[]; void ipi_all(int ipi); void ipi_all_but_self(int ipi); void ipi_selected(u_int64_t cpus, int ipi); void ipi_self(int ipi); #endif /* !LOCORE */ #endif /* _KERNEL */ #endif /* !_MACHINE_SMP_H */
<commit_msg>Split the start_date for better data entry (and Javascript date pickers). <commit_before>from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): class Meta: model = Budget fields = ('name', 'start_date') def save(self): if not self.instance.slug: self.instance.slug = slugify(self.cleaned_data['name']) super(BudgetForm, self).save() class BudgetEstimateForm(forms.ModelForm): class Meta: model = BudgetEstimate fields = ('category', 'amount') def save(self, budget): self.instance.budget = budget super(BudgetEstimateForm, self).save() <commit_after>import datetime from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget) class Meta: model = Budget fields = ('name', 'start_date') def save(self): if not self.instance.slug: self.instance.slug = slugify(self.cleaned_data['name']) super(BudgetForm, self).save() class BudgetEstimateForm(forms.ModelForm): class Meta: model = BudgetEstimate fields = ('category', 'amount') def save(self, budget): self.instance.budget = budget super(BudgetEstimateForm, self).save()
<commit_msg>Add not equals test for version function <commit_before>import shutil import tempfile from os import path import unittest from libs.qpanel.upgrader import __first_line as firstline, get_current_version class UpgradeTestClass(unittest.TestCase): def setUp(self): # Create a temporary directory self.test_dir = tempfile.mkdtemp() def tearDown(self): # Remove the directory after the test shutil.rmtree(self.test_dir) def test_first_line(self): content = 'a\n\b\t\b' self.assertEqual(firstline(content), 'a') self.assertNotEqual(firstline(content), 'ab') def test_version(self): version = '0.10' version_file = path.join(self.test_dir, 'VERSION') f = open(version_file, 'w') f.write(version) f.close() self.assertEqual(get_current_version(version_file), version) # runs the unit tests if __name__ == '__main__': unittest.main() <commit_after>import shutil import tempfile from os import path import unittest from libs.qpanel.upgrader import __first_line as firstline, get_current_version class UpgradeTestClass(unittest.TestCase): def setUp(self): # Create a temporary directory self.test_dir = tempfile.mkdtemp() def tearDown(self): # Remove the directory after the test shutil.rmtree(self.test_dir) def test_first_line(self): content = 'a\n\b\t\b' self.assertEqual(firstline(content), 'a') self.assertNotEqual(firstline(content), 'ab') def test_version(self): version = '0.10' version_file = path.join(self.test_dir, 'VERSION') f = open(version_file, 'w') f.write(version) f.close() self.assertEqual(get_current_version(version_file), version) self.assertNotEqual(get_current_version(version_file), '0.11.0') # runs the unit tests if __name__ == '__main__': unittest.main()
<commit_msg>Update of the dtypes unit-test. <commit_before>from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=None), all_dtypes) some_dtypes = [np.float64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=['x', 'mi', 'name', 'obj']), some_dtypes) <commit_after>from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all()
<commit_msg>Add tests which test default parameters for nap api <commit_before> import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) <commit_after> from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') )
<commit_msg>Make mocked relay error more obvious <commit_before>import { AppStoreProvider } from "lib/store/AppStore" import { Theme } from "palette" import React from "react" import ReactTestRenderer from "react-test-renderer" import { ReactElement } from "simple-markdown" /** * Renders a React Component with our page wrappers * only <Theme> for now * @param component */ export const renderWithWrappers = (component: ReactElement) => { const wrappedComponent = componentWithWrappers(component) // tslint:disable-next-line:use-wrapped-components const renderedComponent = ReactTestRenderer.create(wrappedComponent) // monkey patch update method to wrap components const originalUpdate = renderedComponent.update renderedComponent.update = (nextElement: ReactElement) => { originalUpdate(componentWithWrappers(nextElement)) } return renderedComponent } /** * Returns given component wrapped with our page wrappers * only <Theme> for now * @param component */ export const componentWithWrappers = (component: ReactElement) => { return ( <AppStoreProvider> <Theme>{component}</Theme> </AppStoreProvider> ) } <commit_after>import { AppStoreProvider } from "lib/store/AppStore" import { Theme } from "palette" import React from "react" import ReactTestRenderer from "react-test-renderer" import { ReactElement } from "simple-markdown" /** * Renders a React Component with our page wrappers * only <Theme> for now * @param component */ export const renderWithWrappers = (component: ReactElement) => { const wrappedComponent = componentWithWrappers(component) try { // tslint:disable-next-line:use-wrapped-components const renderedComponent = ReactTestRenderer.create(wrappedComponent) // monkey patch update method to wrap components const originalUpdate = renderedComponent.update renderedComponent.update = (nextElement: ReactElement) => { originalUpdate(componentWithWrappers(nextElement)) } return renderedComponent } catch (error) { if (error.message.includes("Element type is invalid")) { throw new Error( 'Error: Relay test component failed to render. Did you forget to add `jest.unmock("react-relay")` at the top ' + "of your test?" + "\n\n" + error ) } else { throw new Error(error.message) } } } /** * Returns given component wrapped with our page wrappers * only <Theme> for now * @param component */ export const componentWithWrappers = (component: ReactElement) => { return ( <AppStoreProvider> <Theme>{component}</Theme> </AppStoreProvider> ) }
<commit_msg>Add link to autopilot guide in operator autopilot CLI help text <commit_before>package command import ( "strings" "github.com/mitchellh/cli" ) type OperatorAutopilotCommand struct { Meta } func (c *OperatorAutopilotCommand) Run(args []string) int { return cli.RunResultHelp } func (c *OperatorAutopilotCommand) Synopsis() string { return "Provides tools for modifying Autopilot configuration" } func (c *OperatorAutopilotCommand) Help() string { helpText := ` Usage: nomad operator autopilot <subcommand> [options] This command groups subcommands for interacting with Nomad's Autopilot subsystem. Autopilot provides automatic, operator-friendly management of Nomad servers. The command can be used to view or modify the current Autopilot configuration. Get the current Autopilot configuration: $ nomad operator autopilot get-config Set a new Autopilot configuration, enabling automatic dead server cleanup: $ nomad operator autopilot set-config -cleanup-dead-servers=true Please see the individual subcommand help for detailed usage information. ` return strings.TrimSpace(helpText) } <commit_after>package command import ( "strings" "github.com/mitchellh/cli" ) type OperatorAutopilotCommand struct { Meta } func (c *OperatorAutopilotCommand) Run(args []string) int { return cli.RunResultHelp } func (c *OperatorAutopilotCommand) Synopsis() string { return "Provides tools for modifying Autopilot configuration" } func (c *OperatorAutopilotCommand) Help() string { helpText := ` Usage: nomad operator autopilot <subcommand> [options] This command groups subcommands for interacting with Nomad's Autopilot subsystem. Autopilot provides automatic, operator-friendly management of Nomad servers. The command can be used to view or modify the current Autopilot configuration. For a full guide see: https://www.nomadproject.io/guides/autopilot.html Get the current Autopilot configuration: $ nomad operator autopilot get-config Set a new Autopilot configuration, enabling automatic dead server cleanup: $ nomad operator autopilot set-config -cleanup-dead-servers=true Please see the individual subcommand help for detailed usage information. ` return strings.TrimSpace(helpText) }
<commit_msg>Test for presence of new sodium_runtime_has_*() functions <commit_before> int main(void) { printf("%d\n", sodium_init()); (void)sodium_runtime_has_neon(); (void)sodium_runtime_has_sse2(); (void)sodium_runtime_has_sse3(); return 0; } <commit_after> int main(void) { printf("%d\n", sodium_init()); (void)sodium_runtime_has_neon(); (void)sodium_runtime_has_sse2(); (void)sodium_runtime_has_sse3(); (void)sodium_runtime_has_pclmul(); (void)sodium_runtime_has_aesni(); return 0; }
<commit_msg>Relocate core status codes to the 450-499 range <commit_before>JOB_OK = 200 JOB_FAILED = 400 # Status codes for a task TASK_OK = 200 TASK_FAILED = 400 TASK_NOT_ASSIGNABLE = 401 # "ok" code for WorkerInfo.getScore() -- when can this task be assigned? A_NOW = 0 A_LATER = 1 A_NEVER = 2 A_WRONG_ZONE = 3 <commit_after>JOB_OK = 200 # Generic failure. Core failure codes will be in the range 450-499 and 550-599. # All others are reserved for plugins. JOB_FAILED = 450 # Status codes for a task TASK_OK = 200 # See above note about core failure codes. TASK_FAILED = 450 TASK_NOT_ASSIGNABLE = 451 # "ok" code for WorkerInfo.getScore() -- when can this task be assigned? A_NOW = 0 A_LATER = 1 A_NEVER = 2 A_WRONG_ZONE = 3
<commit_msg>Add conditional before wait statement in synchronize block. <commit_before>package com.novoda.downloadmanager; import android.support.annotation.Nullable; import com.novoda.notils.logger.simple.Log; final class WaitForDownloadServiceThenPerform { interface Action<T> { T performAction(); } private WaitForDownloadServiceThenPerform() { // Uses static factory method. } static <T> WaitForDownloadServiceThenPerformAction<T> waitFor(@Nullable DownloadService downloadService, Object downloadServiceLock) { return new WaitForDownloadServiceThenPerformAction<>(downloadService, downloadServiceLock); } static class WaitForDownloadServiceThenPerformAction<T> { private final DownloadService downloadService; private final Object lock; WaitForDownloadServiceThenPerformAction(DownloadService downloadService, Object lock) { this.downloadService = downloadService; this.lock = lock; } T thenPerform(final Action<T> action) { if (downloadService == null) { try { synchronized (lock) { lock.wait(); } } catch (InterruptedException e) { Log.e(e, "Interrupted waiting for download service."); } } return action.performAction(); } } } <commit_after>package com.novoda.downloadmanager; import android.support.annotation.Nullable; import com.novoda.notils.logger.simple.Log; final class WaitForDownloadServiceThenPerform { interface Action<T> { T performAction(); } private WaitForDownloadServiceThenPerform() { // Uses static factory method. } static <T> WaitForDownloadServiceThenPerformAction<T> waitFor(@Nullable DownloadService downloadService, Object downloadServiceLock) { return new WaitForDownloadServiceThenPerformAction<>(downloadService, downloadServiceLock); } static class WaitForDownloadServiceThenPerformAction<T> { private final DownloadService downloadService; private final Object downloadServiceLock; WaitForDownloadServiceThenPerformAction(DownloadService downloadService, Object downloadServiceLock) { this.downloadService = downloadService; this.downloadServiceLock = downloadServiceLock; } T thenPerform(final Action<T> action) { if (downloadService == null) { waitForLock(); } return action.performAction(); } private void waitForLock() { try { synchronized (downloadServiceLock) { if (downloadService == null) { downloadServiceLock.wait(); } } } catch (InterruptedException e) { Log.e(e, "Interrupted waiting for download service."); } } } }
<commit_msg>Add constexpr keyword to inline inited variable Signed-off-by: Robert Young <42c59959a3f4413d6a1b4d7b4f99db457d199e49@gmail.com> <commit_before> namespace Ab { const MemoryConfig Memory::defaultConfig_; } // namespace Ab <commit_after> namespace Ab { constexpr const MemoryConfig Memory::defaultConfig_; } // namespace Ab
<commit_msg>Remove start main activity task from handler if back button is pressed during loading process. <commit_before>package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); new Handler().postDelayed(new Runnable() { @Override public void run() { startMainActivity(); } }, LOADING_TIME_IN_MILLIS); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } } <commit_after>package com.tuenti.tuentitv.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; import butterknife.InjectView; import com.tuenti.tuentitv.R; import java.util.LinkedList; import java.util.List; /** * @author Pedro Vicente Gómez Sánchez. */ public class LoadingActivity extends BaseActivity { private static final long LOADING_TIME_IN_MILLIS = 3000; @InjectView(R.id.pb_loading) ProgressBar pb_loading; private Runnable startMainActivity; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.loading_activity); super.onCreate(savedInstanceState); pb_loading.getIndeterminateDrawable() .setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY); handler = new Handler(); startMainActivity = new Runnable() { @Override public void run() { startMainActivity(); } }; handler.postDelayed(startMainActivity, LOADING_TIME_IN_MILLIS); } @Override public void onBackPressed() { super.onBackPressed(); handler.removeCallbacks(startMainActivity); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } @Override protected List getModules() { return new LinkedList(); } }
<commit_msg>Add some little tests for lexer <commit_before>package edu.kit.stc.lexer; import edu.kit.stc.vocabulary.terminal.Token; import java.util.ArrayList; import java.util.Queue; import static org.junit.Assert.*; /** * Created by florian on 08.05.16. */ public class LexerTest { @org.junit.Test public void testLex() throws Exception { final String SAMPLE_INPUT = "abc(56.23e45L+42.)/"; Lexer lxr = new Lexer(SAMPLE_INPUT); Queue<Token> tokens = lxr.lex(); for (Token t : tokens) { System.out.println(t.toString()); } } }<commit_after>package edu.kit.stc.lexer; import edu.kit.stc.lexer.exception.LException; import edu.kit.stc.vocabulary.terminal.Token; import java.util.ArrayList; import java.util.Queue; import static org.junit.Assert.*; /** * Created by florian on 08.05.16. */ public class LexerTest { @org.junit.Test public void simpleArithOperands() throws Exception { final String SAMPLE_INPUT = "-+==*/"; Lexer lxr = new Lexer(SAMPLE_INPUT); Queue<Token> tokens = lxr.lex(); for (Token t : tokens) { System.out.println(t.toString()); } } @org.junit.Test(expected = LException.class) public void faultyFloat() throws Exception { final String SAMPLE_INPUT = "42"; Lexer lxr = new Lexer(SAMPLE_INPUT); lxr.lex(); } @org.junit.Test public void floatWithNachkommaanteil() throws Exception { final String SAMPLE_INPUT = "42.42l"; Lexer lxr = new Lexer(SAMPLE_INPUT); Queue<Token> tokens = lxr.lex(); for (Token t : tokens) { System.out.println(t.toString()); } } @org.junit.Test public void complexFloatWithExponent() throws Exception { final String SAMPLE_INPUT = "42.41e-14L"; Lexer lxr = new Lexer(SAMPLE_INPUT); Queue<Token> tokens = lxr.lex(); for (Token t : tokens) { System.out.println(t.toString()); } } }
<commit_msg>Fix the raw paths for Gitorious Gitorious have changed the raw orl paths, making impossible to use a Gitorious repository. This patch has been tested in production at http://reviewboard.chakra-project.org/r/27/diff/#index_header Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header <commit_before>from django import forms from django.utils.translation import ugettext_lazy as _ from reviewboard.hostingsvcs.forms import HostingServiceForm from reviewboard.hostingsvcs.service import HostingService class GitoriousForm(HostingServiceForm): gitorious_project_name = forms.CharField( label=_('Project name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) gitorious_repo_name = forms.CharField( label=_('Repository name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) class Gitorious(HostingService): name = 'Gitorious' form = GitoriousForm supported_scmtools = ['Git'] supports_repositories = True repository_fields = { 'Git': { 'path': 'git://gitorious.org/%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'mirror_path': 'http://git.gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'raw_file_url': 'http://git.gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s/blobs/raw/<revision>' }, } <commit_after>from django import forms from django.utils.translation import ugettext_lazy as _ from reviewboard.hostingsvcs.forms import HostingServiceForm from reviewboard.hostingsvcs.service import HostingService class GitoriousForm(HostingServiceForm): gitorious_project_name = forms.CharField( label=_('Project name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) gitorious_repo_name = forms.CharField( label=_('Repository name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) class Gitorious(HostingService): name = 'Gitorious' form = GitoriousForm supported_scmtools = ['Git'] supports_repositories = True repository_fields = { 'Git': { 'path': 'git://gitorious.org/%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'mirror_path': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'raw_file_url': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s/blobs/raw/<revision>' }, }
<commit_msg>Remove dependency on the future lib. <commit_before>from __future__ import absolute_import import django_rq from ievv_opensource.ievv_batchframework.models import BatchOperation from ievv_opensource.ievv_batchframework import batchregistry import logging class BatchActionGroupTask(object): abstract = True def run_actiongroup(self, actiongroup_name, batchoperation_id, **kwargs): try: batchoperation = BatchOperation.objects\ .get(id=batchoperation_id, status=BatchOperation.STATUS_UNPROCESSED) except BatchOperation.DoesNotExist: logging.warning('BatchOperation with id={} does not exist, or is already running.') return else: batchoperation.mark_as_running() registry = batchregistry.Registry.get_instance() full_kwargs = { 'started_by': batchoperation.started_by, 'context_object': batchoperation.context_object, } full_kwargs.update(kwargs) actiongroupresult = registry.get_actiongroup(actiongroup_name)\ .run_blocking(**full_kwargs) batchoperation.finish(failed=actiongroupresult.failed, output_data=actiongroupresult.to_dict()) @django_rq.job('default') def default(**kwargs): BatchActionGroupTask().run_actiongroup(**kwargs) @django_rq.job('highpriority') def highpriority(**kwargs): BatchActionGroupTask().run_actiongroup(**kwargs) <commit_after>import django_rq from ievv_opensource.ievv_batchframework.models import BatchOperation from ievv_opensource.ievv_batchframework import batchregistry import logging class BatchActionGroupTask(object): abstract = True def run_actiongroup(self, actiongroup_name, batchoperation_id, **kwargs): try: batchoperation = BatchOperation.objects\ .get(id=batchoperation_id, status=BatchOperation.STATUS_UNPROCESSED) except BatchOperation.DoesNotExist: logging.warning('BatchOperation with id={} does not exist, or is already running.') return else: batchoperation.mark_as_running() registry = batchregistry.Registry.get_instance() full_kwargs = { 'started_by': batchoperation.started_by, 'context_object': batchoperation.context_object, } full_kwargs.update(kwargs) actiongroupresult = registry.get_actiongroup(actiongroup_name)\ .run_blocking(**full_kwargs) batchoperation.finish(failed=actiongroupresult.failed, output_data=actiongroupresult.to_dict()) @django_rq.job('default') def default(**kwargs): BatchActionGroupTask().run_actiongroup(**kwargs) @django_rq.job('highpriority') def highpriority(**kwargs): BatchActionGroupTask().run_actiongroup(**kwargs)
<commit_msg>Clear screenshot CDN cache after reuploading <commit_before>// eslint-disable-next-line import _temp from "temp"; import fs from "fs"; import fetch from "node-fetch"; import md5Buffer from "md5"; import * as S3 from "../s3"; import * as Skins from "../data/skins"; const Shooter = require("../shooter"); const temp = _temp.track(); export async function screenshot(md5: string, shooter: typeof Shooter) { const url = Skins.getSkinUrl(md5); const response = await fetch(url); if (!response.ok) { await Skins.recordScreenshotUpdate(md5, `Failed to download from ${url}.`); console.error(`Failed to download skin from "${url}".`); return; } const buffer = await response.buffer(); const actualMd5 = md5Buffer(buffer); if (md5 !== actualMd5) { throw new Error("Downloaded skin had a different md5."); } const tempFile = temp.path({ suffix: ".wsz" }); const tempScreenshotPath = temp.path({ suffix: ".png" }); fs.writeFileSync(tempFile, buffer); console.log("Starting screenshot"); const success = await shooter.takeScreenshot(tempFile, tempScreenshotPath, { minify: true, md5, }); if (success) { console.log("Completed screenshot"); await S3.putScreenshot(md5, fs.readFileSync(tempScreenshotPath)); } else { console.log(`Screenshot failed ${md5}`); } } <commit_after>// eslint-disable-next-line import _temp from "temp"; import fs from "fs"; import fetch from "node-fetch"; import md5Buffer from "md5"; import * as S3 from "../s3"; import * as Skins from "../data/skins"; import * as CloudFlare from "../CloudFlare"; const Shooter = require("../shooter"); const temp = _temp.track(); export async function screenshot(md5: string, shooter: typeof Shooter) { const url = Skins.getSkinUrl(md5); const response = await fetch(url); if (!response.ok) { await Skins.recordScreenshotUpdate(md5, `Failed to download from ${url}.`); console.error(`Failed to download skin from "${url}".`); return; } const buffer = await response.buffer(); const actualMd5 = md5Buffer(buffer); if (md5 !== actualMd5) { throw new Error("Downloaded skin had a different md5."); } const tempFile = temp.path({ suffix: ".wsz" }); const tempScreenshotPath = temp.path({ suffix: ".png" }); fs.writeFileSync(tempFile, buffer); console.log("Starting screenshot"); const success = await shooter.takeScreenshot(tempFile, tempScreenshotPath, { minify: true, md5, }); if (success) { console.log("Completed screenshot"); await S3.putScreenshot(md5, fs.readFileSync(tempScreenshotPath)); await CloudFlare.purgeFiles([Skins.getScreenshotUrl(actualMd5)]); } else { console.log(`Screenshot failed ${md5}`); } }
<commit_msg>Remove custom project name, since it changes copyright statements. R=qyearsley@chromium.org Review URL: https://codereview.chromium.org/1212843006. <commit_before> def GetPreferredTryMasters(project, change): return { 'tryserver.client.catapult': { 'Catapult Linux Tryserver': set(['defaulttests']), 'Catapult Mac Tryserver': set(['defaulttests']), 'Catapult Windows Tryserver': set(['defaulttests']), } } def _CommonChecks(input_api, output_api): results = [] results.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api, project_name='catapult')) return results def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results def CheckChangeOnCommit(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results <commit_after> def GetPreferredTryMasters(project, change): return { 'tryserver.client.catapult': { 'Catapult Linux Tryserver': set(['defaulttests']), 'Catapult Mac Tryserver': set(['defaulttests']), 'Catapult Windows Tryserver': set(['defaulttests']), } } def _CommonChecks(input_api, output_api): results = [] results.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return results def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results def CheckChangeOnCommit(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results
<commit_msg>Add examples of ways to use FileDropInput <commit_before>from base.form_utils import RequiredFieldForm from .models import Document from base.form_utils import FileDropInput class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()} <commit_after>from django import forms from base.form_utils import RequiredFieldForm, FileDropInput from .models import Document class DocumentForm(RequiredFieldForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) # Not required RequiredFieldForm uses FileDropInput for FileField # widgets = {'file': FileDropInput()} # this is an example of how to use in a basic ModelForm class BasicDocumentModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} ) class Meta: model = Document fields = ( 'file', 'description', ) widgets = {'file': FileDropInput()} # this is an example of how to use in a basic Form class NonModelForm(forms.Form): file = forms.FileField(widget=FileDropInput) description = forms.CharField(max_length=200) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name in ('file', 'description'): self.fields[name].widget.attrs.update( {'class': 'pure-input-2-3'} )
<commit_msg>Use compat.NUM_TYPES due to removal of long in py3k <commit_before>import statsd import decimal class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, (int, long, float, decimal.Decimal)) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value}) <commit_after>import statsd from . import compat class Gauge(statsd.Client): '''Class to implement a statsd gauge ''' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM_TYPES) name = self._get_name(self.name, subname) self.logger.info('%s: %s', name, value) return statsd.Client._send(self, {name: '%s|g' % value})
<commit_msg>Add note about adding/removing packages to/from pytest header<commit_before> from astropy.tests.pytest_plugins import * ## Uncomment the following line to treat all DeprecationWarnings as ## exceptions # enable_deprecations_as_exceptions() <commit_after> from astropy.tests.pytest_plugins import * ## Uncomment the following line to treat all DeprecationWarnings as ## exceptions # enable_deprecations_as_exceptions() ## Uncomment and customize the following lines to add/remove entries ## from the list of packages for which version numbers are displayed ## when running the tests # PYTEST_HEADER_MODULES['scikit-image'] = 'skimage' # del PYTEST_HEADER_MODULES['h5py']
<commit_msg>Add check that test.sh exists and is executable <commit_before>module Main where import Check import Commandline import System.Environment main :: IO () main = do opts <- getArgs >>= commandLineOptions checkWord opts <commit_after>module Main where import Check import Commandline import Control.Monad import Error import System.Directory import System.Environment import System.IO.Error -- |Wrapper around catchIOError that prints error messages and terminates the program on error catchIO :: (FilePath -> IO a) -> FilePath -> IO a catchIO action path = catchIOError (action path) handler where handler e | isPermissionError e = exitWithError $ "Error: permission to access file '" ++ path ++ "' denied." | otherwise = exitWithError $ "Error: unknown error while accessing file '" ++ path ++ "'." -- |Check whether file at specified path exists and is executable checkTestScript :: FilePath -> IO () checkTestScript path = do exists <- doesPathExist path unless (exists) $ exitWithError $ "Error: no test scipt '" ++ path ++ "' found in present working directory." permissions <- getPermissions path unless (executable permissions) $ exitWithError $ "Error: test scipt '" ++ path ++ "' is not executable." main :: IO () main = do opts <- getArgs >>= commandLineOptions catchIO checkTestScript "./test.sh" checkWord opts
<commit_msg>Update parseLxcInfo to comply with new lxc1.0 format Docker-DCO-1.1-Signed-off-by: Guillaume J. Charmes <guillaume@charmes.net> (github: creack) <commit_before>package lxc import ( "bufio" "errors" "strconv" "strings" ) var ( ErrCannotParse = errors.New("cannot parse raw input") ) type lxcInfo struct { Running bool Pid int } func parseLxcInfo(raw string) (*lxcInfo, error) { if raw == "" { return nil, ErrCannotParse } var ( err error s = bufio.NewScanner(strings.NewReader(raw)) info = &lxcInfo{} ) for s.Scan() { text := s.Text() if s.Err() != nil { return nil, s.Err() } parts := strings.Split(text, ":") if len(parts) < 2 { continue } switch strings.TrimSpace(parts[0]) { case "state": info.Running = strings.TrimSpace(parts[1]) == "RUNNING" case "pid": info.Pid, err = strconv.Atoi(strings.TrimSpace(parts[1])) if err != nil { return nil, err } } } return info, nil } <commit_after>package lxc import ( "bufio" "errors" "strconv" "strings" ) var ( ErrCannotParse = errors.New("cannot parse raw input") ) type lxcInfo struct { Running bool Pid int } func parseLxcInfo(raw string) (*lxcInfo, error) { if raw == "" { return nil, ErrCannotParse } var ( err error s = bufio.NewScanner(strings.NewReader(raw)) info = &lxcInfo{} ) for s.Scan() { text := s.Text() if s.Err() != nil { return nil, s.Err() } parts := strings.Split(text, ":") if len(parts) < 2 { continue } switch strings.ToLower(strings.TrimSpace(parts[0])) { case "state": info.Running = strings.TrimSpace(parts[1]) == "RUNNING" case "pid": info.Pid, err = strconv.Atoi(strings.TrimSpace(parts[1])) if err != nil { return nil, err } } } return info, nil }
<commit_msg>Replace json for flask.json to manage the Response <commit_before>import json from flask import Response as SimpleResponse from .status_codes import HTTP_200_OK from .serializers import BaseSerializer class Response(SimpleResponse): def __init__(self, data, headers=None, status_code=HTTP_200_OK): """ For now the content/type always will be application/json. We can change it to make a Web Browseable API """ if isinstance(data, BaseSerializer): msg = ( 'You passed a Serializer instance as data, but ' 'probably meant to pass serialized `.data` or ' '`.errors`. representation.' ) raise AssertionError(msg) data = json.dumps(data) content_type = "application/json" super(Response, self).__init__( data, headers=None, content_type=content_type, status=status_code ) <commit_after>from flask import Response as SimpleResponse from flask import json from .status_codes import HTTP_200_OK from .serializers import BaseSerializer class Response(SimpleResponse): def __init__(self, data, headers=None, status_code=HTTP_200_OK): """ For now the content/type always will be application/json. We can change it to make a Web Browseable API """ if isinstance(data, BaseSerializer): msg = ( 'You passed a Serializer instance as data, but ' 'probably meant to pass serialized `.data` or ' '`.errors`. representation.' ) raise AssertionError(msg) data = json.dumps(data) content_type = "application/json" super(Response, self).__init__( data, headers=None, content_type=content_type, status=status_code )
<commit_msg>[TRAVIS] Correct the usage of nose.run. nose.run returns whether the test run was sucessful or not. <commit_before> import os import sys from os.path import join, realpath # Third Party modules import nose import coverage cov = coverage.coverage(branch=True) cov.start() result = nose.run(defaultTest=realpath(join(__file__, "..", "..", "py2c"))) cov.stop() cov.save() if result == 0: # If we are in CI environment, don't write an HTML report. if os.environ.get("CI", None) is None: cov.html_report() cov.report() sys.exit(result) <commit_after> import os import sys from os.path import join, realpath # Third Party modules import nose import coverage cov = coverage.coverage(branch=True) cov.start() success = nose.run(defaultTest=realpath(join(__file__, "..", "..", "py2c"))) cov.stop() cov.save() if success: # If we are in CI environment, don't write an HTML report. if os.environ.get("CI", None) is None: cov.html_report() cov.report() sys.exit(0 if success else 1)
<commit_msg>Add utility function to write pvs to file <commit_before> import pkg_resources pkg_resources.require('aphla') import aphla as ap def get_pv_names(mode): ''' Given a certain ring mode as a string, return all available pvs ''' ap.machines.load(mode) result = set() elements = ap.getElements('*') for element in elements: pvs = element.pv() if(len(pvs) > 0): pv_name = pvs[0].split(':')[0] result.add(pv_name) return result def get_pvs_from_file(filepath): ''' Return a list of pvs from a given file ''' with open(filepath) as f: contents = f.read().splitlines() return contents <commit_after> import pkg_resources pkg_resources.require('aphla') import aphla as ap def get_pv_names(mode): ''' Given a certain ring mode as a string, return all available pvs ''' ap.machines.load(mode) result = set() elements = ap.getElements('*') for element in elements: pvs = element.pv() if(len(pvs) > 0): pv_name = pvs[0].split(':')[0] result.add(pv_name) return result def get_pvs_from_file(filepath): ''' Return a list of pvs from a given file ''' with open(filepath) as f: contents = f.read().splitlines() return contents def write_pvs_to_file(filename, data): ''' Write given pvs to file ''' f = open(filename, 'w') for element in data: f.write(element, '\n') f.close()
<commit_msg>Add default BUFFER_SIZE for feeds <commit_before> class Strategy(object): TIMEFRAMES = [] # e.g. ['M30', 'H2'] def __init__(self, instrument): self.instrument = instrument if not self.TIMEFRAMES: raise ValueError('Please define TIMEFRAMES variable.') def start(self): """Called on strategy start.""" raise NotImplementedError() def new_bar(self, instrument, cur_index): """Called on every bar of every instrument that client is subscribed on.""" raise NotImplementedError() def execute(self, engine, instruments, cur_index): """Called on after all indicators have been updated for this bar's index""" raise NotImplementedError() def end(self, engine): """Called on strategy stop.""" raise NotImplementedError() <commit_after> from collections import deque from logbook import Logger log = Logger('pyFxTrader') class Strategy(object): TIMEFRAMES = [] # e.g. ['M30', 'H2'] BUFFER_SIZE = 500 feeds = {} def __init__(self, instrument): self.instrument = instrument if not self.TIMEFRAMES: raise ValueError('Please define TIMEFRAMES variable.') for tf in self.TIMEFRAMES: self.feeds[tf] = deque(maxlen=self.BUFFER_SIZE) log.info('Initialized %s feed for %s' % (tf, self.instrument)) def start(self): """Called on strategy start.""" raise NotImplementedError() def new_bar(self, instrument, cur_index): """Called on every bar of every instrument that client is subscribed on.""" raise NotImplementedError() def execute(self, engine, instruments, cur_index): """Called on after all indicators have been updated for this bar's index""" raise NotImplementedError() def end(self, engine): """Called on strategy stop.""" raise NotImplementedError()
<commit_msg>Add functions to add shapes and iterate over each shape to render. <commit_before>import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) <commit_after>import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) #Create a function to add a shape def addshape(self, s): self.shapes.append(s) #Create a function to render the shapes def render(self): #For each of the shapes, check the type and render it for s in shapes: #If the shape is a cube, call the rendercube method if s.type == Shape.CUBE: rendercube(s)
<commit_msg>Enable spray to find sbt <commit_before> import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) time.sleep(5) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0 <commit_after> import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0
<commit_msg>Add basic validation function for Literature <commit_before>/** * @author Thomas Kleinke */ export interface Literature { quotation: string; zenonId?: string; } export module Literature { export function generateLabel(literature: Literature, getTranslation: (key: string) => string): string { return literature.quotation + (literature.zenonId ? ' (' + getTranslation('zenonId') + ': ' + literature.zenonId + ')' : ''); } }<commit_after>/** * @author Thomas Kleinke */ export interface Literature { quotation: string; zenonId?: string; } export module Literature { export function generateLabel(literature: Literature, getTranslation: (key: string) => string): string { return literature.quotation + (literature.zenonId ? ' (' + getTranslation('zenonId') + ': ' + literature.zenonId + ')' : ''); } export function isValid(literature: Literature): boolean { return literature.quotation !== undefined && literature.quotation.length > 0; } }
<commit_msg>Add in the first checkin date if it doesn't exist <commit_before>from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('server', '0005_auto_20150717_1827'), ] operations = [ migrations.AddField( model_name='machine', name='first_checkin', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='machine', name='sal_version', field=models.TextField(null=True, blank=True), ), ] <commit_after>from __future__ import unicode_literals from django.shortcuts import get_object_or_404 from django.db import models, migrations def add_initial_date(apps, schema_editor): Machine = apps.get_model("server", "Machine") for machine in Machine.objects.all(): if not machine.first_checkin: machine.first_checkin = machine.last_checkin machine.save() class Migration(migrations.Migration): dependencies = [ ('server', '0005_auto_20150717_1827'), ] operations = [ migrations.AddField( model_name='machine', name='first_checkin', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='machine', name='sal_version', field=models.TextField(null=True, blank=True), ), migrations.RunPython(add_initial_date), ]
<commit_msg>Add a standard API reply interface <commit_before>from flask import jsonify, request from ..main import app @app.route('/api/ip') def api_ip(): return jsonify({'Success': True, 'ipAddress': get_client_ip()}) def get_client_ip(): return request.headers.get('X-Forwarded-For') or request.remote_addr <commit_after>from flask import jsonify, request from ..main import app @app.route('/api/ip') def api_ip(): """Return client IP""" return api_reply({'ipAddress': get_client_ip()}) def get_client_ip(): """Return the client x-forwarded-for header or IP address""" return request.headers.get('X-Forwarded-For') or request.remote_addr def api_reply(body={}, success=True): """Create a standard API reply interface""" return jsonify({**body, 'success': success})
<commit_msg>Fix Nano (m() stuff and add nick name <commit_before>import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(ishilight): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat Hilight', buffer+": "+message) elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat MSG from '+buffer, buffer+": "+message) return weechat.WEECHAT_RC_OK weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "") <commit_after>import weechat from yapbl import PushBullet apikey = "" p = PushBullet(apikey) weechat.register("pushbullet", "kekskurse", "1.0", "GPL3", "Test Skript", "", "") weechat.prnt("", "Hallo, von einem python Skript!") def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if(ishilight): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat Hilight', buffer+": <"+prefix+"> "+message) elif(weechat.buffer_get_string(bufferp, "localvar_type") == "private"): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) p.push_note('Weechat MSG from '+buffer, buffer+": "+message) return weechat.WEECHAT_RC_OK weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "")
<commit_msg>Add context=None to render as well. <commit_before>from django.utils.safestring import mark_safe from pygments import highlight from pygments.formatters import get_formatter_by_name from pygments.lexers import get_lexer_by_name from wagtail.wagtailcore import blocks class CodeBlock(blocks.StructBlock): """ Code Highlighting Block """ LANGUAGE_CHOICES = ( ('python', 'Python'), ('javascript', 'Javascript'), ('json', 'JSON'), ('bash', 'Bash/Shell'), ('html', 'HTML'), ('css', 'CSS'), ('scss', 'SCSS'), ('yaml', 'YAML'), ) language = blocks.ChoiceBlock(choices=LANGUAGE_CHOICES) code = blocks.TextBlock() class Meta: icon = 'code' def render(self, value): src = value['code'].strip('\n') lang = value['language'] lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name( 'html', linenos=None, cssclass='codehilite', style='default', noclasses=False, ) return mark_safe(highlight(src, lexer, formatter)) <commit_after>from django.utils.safestring import mark_safe from pygments import highlight from pygments.formatters import get_formatter_by_name from pygments.lexers import get_lexer_by_name from wagtail.wagtailcore import blocks class CodeBlock(blocks.StructBlock): """ Code Highlighting Block """ LANGUAGE_CHOICES = ( ('python', 'Python'), ('javascript', 'Javascript'), ('json', 'JSON'), ('bash', 'Bash/Shell'), ('html', 'HTML'), ('css', 'CSS'), ('scss', 'SCSS'), ('yaml', 'YAML'), ) language = blocks.ChoiceBlock(choices=LANGUAGE_CHOICES) code = blocks.TextBlock() class Meta: icon = 'code' def render(self, value, context=None): src = value['code'].strip('\n') lang = value['language'] lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name( 'html', linenos=None, cssclass='codehilite', style='default', noclasses=False, ) return mark_safe(highlight(src, lexer, formatter))
<commit_msg>Add title to Graph object constructor <commit_before>from datetime import datetime from app import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String()) pw_hash = db.Column(db.String()) graphs = db.relationship("Graph", backref="user", lazy="dynamic") def __init__(self, username, email, name, password): self.username = username self.email = email self.name = name self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8") def __repr__(self): return self.username def check_password(self, password): return bcrypt.check_password_hash(self.pw_hash, password) class Graph(db.Model): __tablename__ = "graphs" id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime) title = db.Column(db.String()) serialized_string = db.Column(db.String()) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) def __init__(self, serialized_string): self.created_at = datetime.utcnow() self.serialized_string = serialized_string def __repr__(self): return self.title <commit_after>from datetime import datetime from app import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String()) pw_hash = db.Column(db.String()) graphs = db.relationship("Graph", backref="user", lazy="dynamic") def __init__(self, username, email, name, password): self.username = username self.email = email self.name = name self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8") def __repr__(self): return self.username def check_password(self, password): return bcrypt.check_password_hash(self.pw_hash, password) class Graph(db.Model): __tablename__ = "graphs" id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime) title = db.Column(db.String()) serialized_string = db.Column(db.String()) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) def __init__(self, title, serialized_string): self.created_at = datetime.utcnow() self.title = title self.serialized_string = serialized_string def __repr__(self): return self.title
<commit_msg>Remove unused code from test case <commit_before>package com.crawljax.core.configuration; import static com.crawljax.core.configuration.CrawlElementMatcher.withXpath; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.crawljax.core.state.Eventable.EventType; public class XPathEscapeApostropheTest { private CrawlActionsBuilder actions; private CrawlElement element; @Before public void setup() { element = new CrawlElement(EventType.click, "button"); } @Test public void testStringNoApostrophes() { String test = "Test String"; test = element.escapeApostrophes(test); assertEquals("'Test String'", test); } @Test public void testStringConcat() { String test = "I'm Feeling Lucky"; test = element.escapeApostrophes(test); assertEquals("concat('I',\"'\",'m Feeling Lucky')", test); } } <commit_after>package com.crawljax.core.configuration; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.crawljax.core.state.Eventable.EventType; public class XPathEscapeApostropheTest { private CrawlElement element; @Before public void setup() { element = new CrawlElement(EventType.click, "button"); } @Test public void testStringNoApostrophes() { String test = "Test String"; test = element.escapeApostrophes(test); assertEquals("'Test String'", test); } @Test public void testStringConcat() { String test = "I'm Feeling Lucky"; test = element.escapeApostrophes(test); assertEquals("concat('I',\"'\",'m Feeling Lucky')", test); } }
<commit_msg>Use a realistic User-Agent for reddit<commit_before>from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) response = requests.get(url) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url <commit_after>from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36' response = requests.get(url, headers={ 'User-Agent': agent }) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url
<commit_msg>Reorder the code so FROMs are iterated over only once Signed-off-by: Remy Suen <553f7e7fc51e9ff47ae89d5a0ebd06651241b998@gmail.com> <commit_before>/* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; import { TextDocument, Position, Location } from 'vscode-languageserver'; import { DockerfileParser } from './parser/dockerfileParser'; export class DockerDefinition { public computeDefinition(document: TextDocument, position: Position): Location | null { let parser = new DockerfileParser(); let dockerfile = parser.parse(document); for (let instruction of dockerfile.getFROMs()) { let range = instruction.getBuildStageRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { return Location.create(document.uri, range); } } let source = undefined; for (let instruction of dockerfile.getCOPYs()) { let range = instruction.getFromValueRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { source = instruction.getFromValue(); break; } } if (source) { for (let instruction of dockerfile.getFROMs()) { if (instruction.getBuildStage() === source) { let range = instruction.getBuildStageRange(); return Location.create(document.uri, range); } } } return null; } } <commit_after>/* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; import { TextDocument, Position, Location } from 'vscode-languageserver'; import { DockerfileParser } from './parser/dockerfileParser'; export class DockerDefinition { public computeDefinition(document: TextDocument, position: Position): Location | null { let parser = new DockerfileParser(); let dockerfile = parser.parse(document); let source = undefined; for (let instruction of dockerfile.getCOPYs()) { let range = instruction.getFromValueRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { source = instruction.getFromValue(); break; } } for (let instruction of dockerfile.getFROMs()) { let range = instruction.getBuildStageRange(); if (range && ((range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) || (instruction.getBuildStage() === source))) { return Location.create(document.uri, range); } } return null; } }
<commit_msg>Add README.rst contents to PyPI page That is to say, what is visible at https://pypi.org/project/serenata-toolbox/ <commit_before>from setuptools import setup REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox' setup( author='Serenata de Amor', author_email='contato@serenata.ai', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'python-decouple>=3.1', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL), name='serenata-toolbox', packages=[ 'serenata_toolbox', 'serenata_toolbox.federal_senate', 'serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets' ], url=REPO_URL, python_requires='>=3.6', version='15.0.2', ) <commit_after>from setuptools import setup REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox' with open('README.rst') as fobj: long_description = fobj.read() setup( author='Serenata de Amor', author_email='contato@serenata.ai', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', ], description='Toolbox for Serenata de Amor project', zip_safe=False, install_requires=[ 'aiofiles', 'aiohttp', 'beautifulsoup4>=4.4', 'lxml>=3.6', 'pandas>=0.18', 'python-decouple>=3.1', 'tqdm' ], keywords='serenata de amor, data science, brazil, corruption', license='MIT', long_description=long_description, name='serenata-toolbox', packages=[ 'serenata_toolbox', 'serenata_toolbox.federal_senate', 'serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets' ], url=REPO_URL, python_requires='>=3.6', version='15.0.3', )
<commit_msg>Improve vector property error message <commit_before>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six from .base import Property from . import vmath class Vector(Property): """class properties.Vector Vector property, using properties.vmath.Vector """ _sphinx_prefix = 'properties.spatial' @property def default(self): return getattr(self, '_default', [] if self.repeated else None) @default.setter def default(self, value): self._default = self.validator(None, value).copy() def validator(self, instance, value): """return a Vector based on input if input is valid""" if isinstance(value, vmath.Vector): return value if isinstance(value, six.string_types): if value.upper() == 'X': return vmath.Vector(1, 0, 0) if value.upper() == 'Y': return vmath.Vector(0, 1, 0) if value.upper() == 'Z': return vmath.Vector(0, 0, 1) try: return vmath.Vector(value) except Exception: raise ValueError('{} must be a Vector'.format(self.name)) def from_json(self, value): return vmath.Vector(*value) <commit_after>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six from .base import Property from . import vmath class Vector(Property): """class properties.Vector Vector property, using properties.vmath.Vector """ _sphinx_prefix = 'properties.spatial' @property def default(self): return getattr(self, '_default', [] if self.repeated else None) @default.setter def default(self, value): self._default = self.validator(None, value).copy() def validator(self, instance, value): """return a Vector based on input if input is valid""" if isinstance(value, vmath.Vector): return value if isinstance(value, six.string_types): if value.upper() == 'X': return vmath.Vector(1, 0, 0) if value.upper() == 'Y': return vmath.Vector(0, 1, 0) if value.upper() == 'Z': return vmath.Vector(0, 0, 1) try: return vmath.Vector(value) except Exception: raise ValueError('{}: must be Vector with ' '3 elements'.format(self.name)) def from_json(self, value): return vmath.Vector(*value)
<commit_msg>[fix] Update project cost for draft project only <commit_before> from __future__ import unicode_literals import frappe def execute(): for p in frappe.get_all("Project"): project = frappe.get_doc("Project", p.name) project.update_purchase_costing() project.save()<commit_after> from __future__ import unicode_literals import frappe def execute(): for p in frappe.get_all("Project", filters={"docstatus": 0}): project = frappe.get_doc("Project", p.name) project.update_purchase_costing() project.save()
<commit_msg>Add ifThenElse to linear toolbox <commit_before>{-# LANGUAGE Trustworthy #-} {-# LANGUAGE GADTs#-} module Data.Linear where import Prelude (Show(..), Eq(..)) id :: a ⊸ a id a = a liftUnit :: a ⊸ () ⊸ a liftUnit a () = a flip :: (a ⊸ b ⊸ c ) ⊸ b ⊸ a ⊸ c flip f b a = f a b infixr 0 $ ($) :: (a ⊸ b) ⊸ a ⊸ b f $ x = f x {-# INLINE ($) #-} (.) :: (b ⊸ c) ⊸ (a ⊸ b) ⊸ a ⊸ c (.) f g a = f $ g a data Unrestricted a where Unrestricted :: a -> Unrestricted a deriving (Show, Eq) getUnrestricted :: Unrestricted a ⊸ a getUnrestricted (Unrestricted a) = a <commit_after>{-# LANGUAGE Trustworthy #-} {-# LANGUAGE GADTs#-} module Data.Linear where import Prelude (Show(..), Eq(..)) import Data.Bool(Bool(..), bool) id :: a ⊸ a id a = a liftUnit :: a ⊸ () ⊸ a liftUnit a () = a flip :: (a ⊸ b ⊸ c ) ⊸ b ⊸ a ⊸ c flip f b a = f a b infixr 0 $ ($) :: (a ⊸ b) ⊸ a ⊸ b f $ x = f x {-# INLINE ($) #-} (.) :: (b ⊸ c) ⊸ (a ⊸ b) ⊸ a ⊸ c (.) f g a = f $ g a data Unrestricted a where Unrestricted :: a -> Unrestricted a deriving (Show, Eq) getUnrestricted :: Unrestricted a ⊸ a getUnrestricted (Unrestricted a) = a -- | This is not linear, but since LMonad with friends rely on -- -XRebindableSyntax, the default ifThenElse goes out of scope and this is -- useful anyway. ifThenElse :: Bool -> a -> a -> a ifThenElse b x y = bool y x b
<commit_msg>Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936 <commit_before>class A: pass a = A() print(a.f<caret>oo) x = A() or None print(x.foo)<commit_after>class A: pass a = A() print(a.f<caret>oo) def func(c): x = A() if c else None return x.foo
<commit_msg>Fix test case to unbreak testing git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@91551 91177308-0d34-0410-b5e6-96231b3b80d8 <commit_before>// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s struct A { virtual ~A(); }; struct B : A { }; struct C { int i; B b; }; // CHECK: _Z15test_value_initv void test_value_init() { // This value initialization requires zero initialization of the 'B' // subobject followed by a call to its constructor. // PR5800 // CHECK: store i32 17 // CHECK: call void @llvm.memset.i64 // CHECK: call void @_ZN1BC1Ev(%struct.A* %tmp1) C c = { 17 } ; // CHECK: call void @_ZN1CD1Ev(%struct.C* %c) } <commit_after>// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s struct A { virtual ~A(); }; struct B : A { }; struct C { int i; B b; }; // CHECK: _Z15test_value_initv void test_value_init() { // This value initialization requires zero initialization of the 'B' // subobject followed by a call to its constructor. // PR5800 // CHECK: store i32 17 // CHECK: call void @llvm.memset.i64 // CHECK: call void @_ZN1BC1Ev C c = { 17 } ; // CHECK: call void @_ZN1CD1Ev }
<commit_msg>Add a legacy version for older versions of Django. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com> <commit_before>from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transaction.commit() def process_exception(self, job, time_taken, *exc_info): if not connection.in_atomic_block: transaction.rollback() <commit_after>from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transaction.commit() def process_exception(self, job, time_taken, *exc_info): if not connection.in_atomic_block: transaction.rollback() # Legacy if not hasattr(connection, 'in_atomic_block'): class TransactionMiddleware(object): def process_job(self, job): transaction.enter_transaction_management() transaction.managed(True) def process_result(self, job, result, duration): if not transaction.is_managed(): return if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() def process_exception(self, job, time_taken, *exc_info): if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management()
<commit_msg>Fix bug: log dir path: set it thru file location, not current working path <commit_before>import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.getcwd(),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_name= os.path.join(log_dir, log_name) f_d=open(file_name,"w+") p = Popen(args, stdout=f_d, stdin=PIPE, stderr=f_d) #Dump stdout and stderr to log file output = p.communicate() print command_line+ " " + "executed!" f_d.close() def create_thread(argv_list): io_thread=[] for argv in argv_list: thread=threading.Thread(target=exe_cmd,kwargs =argv) io_thread.append(thread) for thread in io_thread: #Add this "for loop" for better understanding thread.start() for thread in io_thread: thread.join() <commit_after>import shlex, os from subprocess import Popen, PIPE #from time import sleep import threading def exe_cmd(log_name, command_line): args = shlex.split(command_line) log_dir=os.path.join(os.path.dirname(__file__),"..", "log") if not os.path.isdir(log_dir): os.mkdir(log_dir) file_name= os.path.join(log_dir, log_name) f_d=open(file_name,"w+") p = Popen(args, stdout=f_d, stdin=PIPE, stderr=f_d) #Dump stdout and stderr to log file output = p.communicate() print command_line+ " " + "executed!" f_d.close() def create_thread(argv_list): io_thread=[] for argv in argv_list: thread=threading.Thread(target=exe_cmd,kwargs =argv) io_thread.append(thread) for thread in io_thread: #Add this "for loop" for better understanding thread.start() for thread in io_thread: thread.join()
<commit_msg>Fix so that reactors properly return the EU/t on output. <commit_before>package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } } <commit_after>package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import ic2.api.IC2Reactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } }
<commit_msg>Java: Put patterns directly in function call to follow style of the rest of benchmarks <commit_before>import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Benchmark { private static final String PATTERN_EMAIL = "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+"; private static final String PATTERN_URI = "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?"; private static final String PATTERN_IP = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}" + "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])"; public static void main(String... args) throws IOException { if (args.length != 1) { System.out.println("Usage: java Benchmark <filename>"); System.exit(1); } final String data = Files.readString(Paths.get(args[0])); measure(data, PATTERN_EMAIL); measure(data, PATTERN_URI); measure(data, PATTERN_IP); } private static void measure(String data, String pattern) { long startTime = System.nanoTime(); final Matcher matcher = Pattern.compile(pattern).matcher(data); int count = 0; while (matcher.find()) { ++count; } long elapsed = System.nanoTime() - startTime; System.out.println(elapsed / 1e6 + " - " + count); } } <commit_after>import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Benchmark { public static void main(String... args) throws IOException { if (args.length != 1) { System.out.println("Usage: java Benchmark <filename>"); System.exit(1); } final String data = Files.readString(Paths.get(args[0])); measure(data, "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+"); measure(data, "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?"); measure(data, "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])"); } private static void measure(String data, String pattern) { long startTime = System.nanoTime(); final Matcher matcher = Pattern.compile(pattern).matcher(data); int count = 0; while (matcher.find()) { ++count; } long elapsed = System.nanoTime() - startTime; System.out.println(elapsed / 1e6 + " - " + count); } }
<commit_msg>Configure django correctly when we setup our env <commit_before> import multiprocessing import optparse from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_stopped def run(self): parser = optparse.OptionParser() parser.add_option('--settings', dest='settings') options, args = parser.parse_args() if not options.settings: raise ImproperlyConfigured("You didn't provide a settings module.") settings = import_module(options.settings) self.producer_queue = multiprocessing.Queue() for producer in settings.PRODUCERS: ProducerClass = import_module(producer).Producer producer = ProducerClass(settings, self.producer_queue) multiprocessing.Process(target=producer.run).start() self.receiver_queues = [] for consumer in settings.CONSUMERS: ConsumerClass = import_module(consumer).Consumer recv_queue = multiprocessing.Queue() consumer = ConsumerClass(settings, recv_queue) self.receiver_queues.append(recv_queue) multiprocessing.Process(target=consumer.run).start() while True: item = self.producer_queue.get() for recv_queue in self.receiver_queues: recv_queue.put(item) if __name__ == '__main__': app = ApplicationManager() app.run() <commit_after> import multiprocessing import optparse from django.conf import settings as django_settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_stopped def run(self): parser = optparse.OptionParser() parser.add_option('--settings', dest='settings') options, args = parser.parse_args() if not options.settings: raise ImproperlyConfigured("You didn't provide a settings module.") settings = import_module(options.settings) django_settings.configure(settings) self.producer_queue = multiprocessing.Queue() for producer in settings.PRODUCERS: ProducerClass = import_module(producer).Producer producer = ProducerClass(settings, self.producer_queue) multiprocessing.Process(target=producer.run).start() self.receiver_queues = [] for consumer in settings.CONSUMERS: ConsumerClass = import_module(consumer).Consumer recv_queue = multiprocessing.Queue() consumer = ConsumerClass(settings, recv_queue) self.receiver_queues.append(recv_queue) multiprocessing.Process(target=consumer.run).start() while True: item = self.producer_queue.get() for recv_queue in self.receiver_queues: recv_queue.put(item) if __name__ == '__main__': app = ApplicationManager() app.run()
<commit_msg>Fix last version writing in aboutWindow<commit_before> aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow) { ui->setupUi(this); ui->labelCurrent->setText(version); m_version = version.replace(".", "").toInt(); QNetworkAccessManager *m = new QNetworkAccessManager(); connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION"))); setFixedSize(400, 170); } aboutWindow::~aboutWindow() { delete ui; } void aboutWindow::finished(QNetworkReply *r) { QString l = r->readAll(); int latest = l.replace(".", "").toInt(); if (latest <= m_version) { ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Grabber est jour")+"</p>"); } else { ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Une nouvelle version est disponible : %1").arg(l)+"</p>"); } } <commit_after> aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow) { ui->setupUi(this); ui->labelCurrent->setText(version); m_version = version.replace(".", "").toInt(); QNetworkAccessManager *m = new QNetworkAccessManager(); connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION"))); setFixedSize(400, 170); } aboutWindow::~aboutWindow() { delete ui; } void aboutWindow::finished(QNetworkReply *r) { QString l = r->readAll(), last = l; int latest = last.replace(".", "").toInt(); if (latest <= m_version) { ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Grabber est jour")+"</p>"); } else { ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Une nouvelle version est disponible : %1").arg(l)+"</p>"); } }
<commit_msg>Increase number of robot names that can be generated. <commit_before> using namespace std; namespace robot_name { namespace { string next_prefix(string prefix) { string next{prefix}; const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}; if (prefix[1] == letters.back()) { if (prefix[0] == letters.back()) { throw range_error("prefix combinations exhausted"); } next[1] = letters[0]; next[0] = letters[letters.find(next[0]) + 1]; } else { next[1] = letters[letters.find(next[1]) + 1]; } return next; } string generate_name() { static string prefix = "AA"; static int unit_number = 100; ostringstream buff; if (unit_number > 999) { prefix = next_prefix(prefix); unit_number = 100; } buff << prefix << unit_number++; return buff.str(); } } robot::robot() : name_(generate_name()) { } void robot::reset() { name_ = generate_name(); } } <commit_after> using namespace std; namespace robot_name { namespace { string next_prefix(string prefix) { string next{prefix}; const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}; if (prefix[1] == letters.back()) { if (prefix[0] == letters.back()) { throw range_error("prefix combinations exhausted"); } next[1] = letters[0]; next[0] = letters[letters.find(next[0]) + 1]; } else { next[1] = letters[letters.find(next[1]) + 1]; } return next; } string generate_name() { static string prefix = "AA"; static int unit_number = 0; ostringstream buff; if (unit_number > 999) { prefix = next_prefix(prefix); unit_number = 0; } buff << prefix << setw(3) << setfill('0') << unit_number++; return buff.str(); } } robot::robot() : name_(generate_name()) { } void robot::reset() { name_ = generate_name(); } }
<commit_msg>Fix matchMedia mock for tests <commit_before>import createFetchMock from 'vitest-fetch-mock'; import '@testing-library/jest-dom'; // Suppress oaf-react-router warning about missing title document.title = 'React Starter'; // Mock fetch createFetchMock(vi).enableMocks(); // Mock matchMedia Object.defineProperty(window, 'matchMedia', { writable: true, value: vi.fn().mockImplementation((query: string) => ({ matches: false, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), })), }); // eslint-disable-next-line import/first import 'common/i18next'; <commit_after>import createFetchMock from 'vitest-fetch-mock'; import '@testing-library/jest-dom'; // Suppress oaf-react-router warning about missing title document.title = 'React Starter'; // Mock fetch createFetchMock(vi).enableMocks(); // Mock matchMedia vi.stubGlobal('matchMedia', (query: string) => ({ matches: false, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), })); // eslint-disable-next-line import/first import 'common/i18next';
<commit_msg>Add validation to example script. <commit_before> import sys from docopt import docopt from path_and_address import resolve, split_address def main(args=None): """The entry point of the application.""" if args is None: args = sys.argv[1:] # Parse command-line args = docopt(__doc__, argv=args) # Parse arguments path, address = resolve(args['<path>'], args['<address>']) host, port = split_address(address) if path is None: path = '.' if host is None: host = 'localhost' if port is None: port = 5000 # Run server print ' * Serving %s on http://%s:%s/' % (path, host, port) if __name__ == '__main__': main() <commit_after> import sys from docopt import docopt from path_and_address import resolve, split_address def main(args=None): """The entry point of the application.""" if args is None: args = sys.argv[1:] # Parse command-line args = docopt(__doc__, argv=args) # Parse arguments path, address = resolve(args['<path>'], args['<address>']) host, port = split_address(address) # Validate arguments if address and not (host or port): print 'Error: Invalid address', repr(address) return # Default values if path is None: path = '.' if host is None: host = 'localhost' if port is None: port = 5000 # Run server print ' * Serving %s on http://%s:%s/' % (path, host, port) if __name__ == '__main__': main()
<commit_msg>Make the CreateResponse typedef public <commit_before> namespace ApiMock { class Server { typedef std::function<ResponseData(RequestData)> CreateResponse; struct ServerImpl; std::unique_ptr<ServerImpl> _impl; Server& operator=(const Server&); Server(const Server&); public: Server(); ~Server(); void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse); }; } #endif<commit_after> namespace ApiMock { class Server { struct ServerImpl; std::unique_ptr<ServerImpl> _impl; Server& operator=(const Server&); Server(const Server&); public: typedef std::function<ResponseData(RequestData)> CreateResponse; Server(); ~Server(); void startServer(const std::string& address, int port, int bufferSize, CreateResponse createResponse); }; } #endif
<commit_msg>[x]: Fix Import Error for relative Import <commit_before>import os import six import ckanserviceprovider.web as web from . import jobs # check whether jobs have been imported properly assert(jobs.push_to_datastore) def serve(): web.init() web.app.run(web.app.config.get('HOST'), web.app.config.get('PORT')) def serve_test(): web.init() return web.app.test_client() def main(): import argparse argparser = argparse.ArgumentParser( description='Service that allows automatic migration of data to the CKAN DataStore', epilog='''"He reached out and pressed an invitingly large red button on a nearby panel. The panel lit up with the words Please do not press this button again."''') if six.PY3: argparser.add_argument('config', metavar='CONFIG', type=argparse.FileType('r'), help='configuration file') if six.PY2: argparser.add_argument('config', metavar='CONFIG', type=file, help='configuration file') args = argparser.parse_args() os.environ['JOB_CONFIG'] = os.path.abspath(args.config.name) serve() if __name__ == '__main__': main() <commit_after>import os import six import ckanserviceprovider.web as web from datapusher import jobs # check whether jobs have been imported properly assert(jobs.push_to_datastore) def serve(): web.init() web.app.run(web.app.config.get('HOST'), web.app.config.get('PORT')) def serve_test(): web.init() return web.app.test_client() def main(): import argparse argparser = argparse.ArgumentParser( description='Service that allows automatic migration of data to the CKAN DataStore', epilog='''"He reached out and pressed an invitingly large red button on a nearby panel. The panel lit up with the words Please do not press this button again."''') if six.PY3: argparser.add_argument('config', metavar='CONFIG', type=argparse.FileType('r'), help='configuration file') if six.PY2: argparser.add_argument('config', metavar='CONFIG', type=file, help='configuration file') args = argparser.parse_args() os.environ['JOB_CONFIG'] = os.path.abspath(args.config.name) serve() if __name__ == '__main__': main()
<commit_msg>Test for transcript before scraping from PUA <commit_before>import logging from django.core.management.base import BaseCommand from django.conf import settings from popuparchive.client import Client from ...models import Transcript from ...tasks import process_transcript logger = logging.getLogger('pua_scraper') class Command(BaseCommand): help = 'scrapes the popup archive poll for information' def handle(self, *args, **options): client = Client( settings.PUA_KEY, settings.PUA_SECRET, ) for collection in client.get_collections(): logger.info('collection id: ' + str(collection['id'])) for item_id in collection['item_ids']: logger.info('item id: ' + str(item_id)) item = client.get_item(collection['id'], item_id) process_transcript(item) <commit_after>import logging from django.core.management.base import BaseCommand from django.conf import settings from popuparchive.client import Client from ...models import Transcript from ...tasks import process_transcript logger = logging.getLogger('pua_scraper') class Command(BaseCommand): help = 'scrapes the popup archive poll for information' def handle(self, *args, **options): client = Client( settings.PUA_KEY, settings.PUA_SECRET, ) for collection in client.get_collections(): logger.info('processing collection id: ' + str(collection['id'])) for item_id in collection['item_ids']: logger.info('processing item id: ' + str(item_id)) try: Transcript.objects.get(id_number=item_id) except Transcript.DoesNotExist: item = client.get_item(collection['id'], item_id) process_transcript(item)
<commit_msg>Allow level param in Django SentryHandler.__init__ For consistency with superclass and with logging.Handler <commit_before> from __future__ import absolute_import import logging from raven.handlers.logging import SentryHandler as BaseSentryHandler class SentryHandler(BaseSentryHandler): def __init__(self): logging.Handler.__init__(self) def _get_client(self): from raven.contrib.django.models import client return client client = property(_get_client) def _emit(self, record): request = getattr(record, 'request', None) return super(SentryHandler, self)._emit(record, request=request) <commit_after> from __future__ import absolute_import import logging from raven.handlers.logging import SentryHandler as BaseSentryHandler class SentryHandler(BaseSentryHandler): def __init__(self, level=logging.NOTSET): logging.Handler.__init__(self, level=level) def _get_client(self): from raven.contrib.django.models import client return client client = property(_get_client) def _emit(self, record): request = getattr(record, 'request', None) return super(SentryHandler, self)._emit(record, request=request)
<commit_msg>Remove sdbus++ template search workaround sdbus++ was fixed upstream to find its templates automatically. Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf Signed-off-by: Brad Bishop <713d098c0be4c8fd2bf36a94cd08699466677ecd@fuzziesquirrel.com> <commit_before> import os import sys import yaml import subprocess class SDBUSPlus(object): def __init__(self, path): self.path = path def __call__(self, *a, **kw): args = [ os.path.join(self.path, 'sdbus++'), '-t', os.path.join(self.path, 'templates') ] subprocess.call(args + list(a), **kw) if __name__ == '__main__': sdbusplus = None for p in os.environ.get('PATH', "").split(os.pathsep): if os.path.exists(os.path.join(p, 'sdbus++')): sdbusplus = SDBUSPlus(p) break if sdbusplus is None: sys.stderr.write('Cannot find sdbus++\n') sys.exit(1) genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: sdbusplus( '-r', os.path.join('example', 'interfaces'), 'interface', process, i, stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <commit_after> import os import sys import yaml import subprocess if __name__ == '__main__': genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: subprocess.call([ 'sdbus++', '-r', os.path.join('example', 'interfaces'), 'interface', process, i], stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<commit_msg>Make sure slug gets updated on date change <commit_before>"""Unit tests for events models.""" import datetime from app.events.factories import EventFactory from app.events.models import Event def test_event_factory(db): # noqa: D103 # GIVEN an empty database assert Event.objects.count() == 0 # WHEN saving a new event instance to the database EventFactory.create(title='five') # THEN it's there assert Event.objects.count() == 1 def test_event_has_all_the_attributes(): # noqa: D103 # GIVEN an event e = EventFactory.build() # THEN it has … assert e.title assert e.date assert e.venue assert e.description assert e.fb_event_url def test_event_has_slug(db): # noqa: D103 # GIVEN an event e = EventFactory.build( title='One Happy Family', date=datetime.date(2018, 1, 1), venue=None, ) assert e.slug == '' # WHEN saving the event e.save() # THEN it gets a slug generated from its date and title assert e.slug == '2018-01-01-one-happy-family' <commit_after>"""Unit tests for events models.""" import datetime from app.events.factories import EventFactory from app.events.models import Event def test_event_factory(db): # noqa: D103 # GIVEN an empty database assert Event.objects.count() == 0 # WHEN saving a new event instance to the database EventFactory.create(title='five') # THEN it's there assert Event.objects.count() == 1 def test_event_has_all_the_attributes(): # noqa: D103 # GIVEN an event e = EventFactory.build() # THEN it has … assert e.title assert e.date assert e.venue assert e.description assert e.fb_event_url def test_event_has_slug(db): # noqa: D103 # GIVEN an event e = EventFactory.build( title='One Happy Family', date=datetime.date(2018, 1, 1), venue=None, ) assert e.slug == '' # WHEN saving the event e.save() # THEN it gets a slug generated from its date and title assert e.slug == '2018-01-01-one-happy-family' def test_event_slug_gets_updated_on_date_change(db): # noqa: D103 # GIVEN an event e = EventFactory.create( date=datetime.date(2018, 1, 1), venue=None, ) # WHEN changing the date assert e.slug.startswith('2018-01-01') e.date = datetime.date(2018, 1, 2) e.save() # THEN the slug changes to reflect the new date assert e.slug.startswith('2018-01-02')
<commit_msg>Fix reading log/report templates/dependencies in UTF-8. Some of the updated js dependencies (#2419) had non-ASCII data in UTF-8 format but our code reading these files didn't take that into account. <commit_before> import os from os.path import abspath, dirname, join, normpath class HtmlTemplate(object): _base_dir = join(dirname(abspath(__file__)), '..', 'htmldata') def __init__(self, filename): self._path = normpath(join(self._base_dir, filename.replace('/', os.sep))) def __iter__(self): with open(self._path) as file: for line in file: yield line.rstrip() <commit_after> import codecs import os from os.path import abspath, dirname, join, normpath class HtmlTemplate(object): _base_dir = join(dirname(abspath(__file__)), '..', 'htmldata') def __init__(self, filename): self._path = normpath(join(self._base_dir, filename.replace('/', os.sep))) def __iter__(self): with codecs.open(self._path, encoding='UTF-8') as file: for line in file: yield line.rstrip()
<commit_msg>Make root node able to execute itself <commit_before>package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.SourceSection; import org.hummingbirdlang.HBLanguage; import org.hummingbirdlang.types.realize.InferenceVisitor; import org.hummingbirdlang.types.realize.Visitable; public class HBSourceRootNode extends RootNode implements Visitable { @Child private HBBlockNode bodyNode; public HBSourceRootNode(SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) { super(HBLanguage.class, sourceSection, frameDescriptor); this.bodyNode = bodyNode; } public void accept(InferenceVisitor visitor) { visitor.enter(this); this.bodyNode.accept(visitor); visitor.leave(this); } @Override public Object execute(VirtualFrame frame) { return null; } @Override public String toString() { StringBuilder result = new StringBuilder("HBSourceRootNode("); result.append(bodyNode.toString()); result.append(")"); return result.toString(); } } <commit_after>package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.SourceSection; import org.hummingbirdlang.HBLanguage; import org.hummingbirdlang.types.realize.InferenceVisitor; import org.hummingbirdlang.types.realize.Visitable; public class HBSourceRootNode extends RootNode implements Visitable { @Child private HBBlockNode bodyNode; public HBSourceRootNode(SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) { super(HBLanguage.class, sourceSection, frameDescriptor); this.bodyNode = bodyNode; } public void accept(InferenceVisitor visitor) { visitor.enter(this); this.bodyNode.accept(visitor); visitor.leave(this); } @Override public Object execute(VirtualFrame frame) { this.bodyNode.executeVoid(frame); return null; } @Override public String toString() { StringBuilder result = new StringBuilder("HBSourceRootNode("); result.append(bodyNode.toString()); result.append(")"); return result.toString(); } }
<commit_msg>Add new lab_members fieldset_website to fieldsets for cms_lab_members <commit_before>from django.contrib import admin from cms.admin.placeholderadmin import PlaceholderAdminMixin from lab_members.models import Scientist from lab_members.admin import ScientistAdmin class CMSScientistAdmin(PlaceholderAdminMixin, ScientistAdmin): fieldsets = [ ScientistAdmin.fieldset_basic, ScientistAdmin.fieldset_advanced, ] admin.site.unregister(Scientist) admin.site.register(Scientist, CMSScientistAdmin) <commit_after>from django.contrib import admin from cms.admin.placeholderadmin import PlaceholderAdminMixin from lab_members.models import Scientist from lab_members.admin import ScientistAdmin class CMSScientistAdmin(PlaceholderAdminMixin, ScientistAdmin): fieldsets = [ ScientistAdmin.fieldset_basic, ScientistAdmin.fieldset_website, ScientistAdmin.fieldset_advanced, ] admin.site.unregister(Scientist) admin.site.register(Scientist, CMSScientistAdmin)
<commit_msg>nth-prime: Fix comment to say that is matches x-common. <commit_before>{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Prime (nth) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "nth-prime" $ describe "nth" $ for_ cases test where test Case{..} = it description assertion where assertion = nth (fromIntegral input) `shouldBe` expected -- As of 2016-09-06, there was no reference file for the test cases in -- `exercism/x-common`, so we adapted the test cases available in the -- pull request `exercism/x-common#332`. data Case = Case { description :: String , input :: Integer , expected :: Maybe Integer } cases :: [Case] cases = [ Case { description = "first prime" , input = 1 , expected = Just 2 } , Case { description = "second prime" , input = 2 , expected = Just 3 } , Case { description = "sixth prime" , input = 6 , expected = Just 13 } , Case { description = "big prime" , input = 10001 , expected = Just 104743 } , Case { description = "there is no zeroth prime" , input = 0 , expected = Nothing } ] <commit_after>{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Prime (nth) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "nth-prime" $ describe "nth" $ for_ cases test where test Case{..} = it description assertion where assertion = nth (fromIntegral input) `shouldBe` expected -- Test cases adapted from `exercism/x-common` on 2016-09-19. data Case = Case { description :: String , input :: Integer , expected :: Maybe Integer } cases :: [Case] cases = [ Case { description = "first prime" , input = 1 , expected = Just 2 } , Case { description = "second prime" , input = 2 , expected = Just 3 } , Case { description = "sixth prime" , input = 6 , expected = Just 13 } , Case { description = "big prime" , input = 10001 , expected = Just 104743 } , Case { description = "there is no zeroth prime" , input = 0 , expected = Nothing } ]
<commit_msg>Change subtext on main page <commit_before>from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'home.html' def get(self, request, *args, **kwargs): context = { 'some_dynamic_value': 'Now available as a web application!', } return self.render_to_response(context) <commit_after>from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'home.html' def get(self, request, *args, **kwargs): context = { 'some_dynamic_value': 'Coming soon as a web application!', } return self.render_to_response(context)
<commit_msg>Use Convert() to simplify code <commit_before>def main(): try: fileName = "MengZi_Traditional.md" filePath = "../../source/" + fileName content = None with open(filePath,'r') as file: content = file.read().decode("utf-8") content = content.replace(u"「",u'“') content = content.replace(u"」",u'”') content = content.replace(u"『",u'‘') content = content.replace(u"』",u'’') with open(filePath,'w') as file: file.write(content.encode("utf-8")) print "OK" except IOError: print ("IOError occurs while handling the file (" + filePath + ").") if __name__ == '__main__': main()<commit_after> def Convert(content): tradtionalToSimplified = { u"「":u"“", u"」":u"”", u"『":u"‘", u"』":u"’", } for key in tradtionalToSimplified: content = content.replace(key, tradtionalToSimplified[key]) return content def main(): try: fileName = "MengZi_Traditional - Test.md" filePath = "../../source/" + fileName content = None with open(filePath,'r') as file: content = file.read().decode("utf-8") content = Convert(content) with open(filePath,'w') as file: file.write(content.encode("utf-8")) print "OK" except IOError: print ("IOError occurs while handling the file (" + filePath + ").") if __name__ == '__main__': main()
<commit_msg>Use iopoll instead of poll directly. <commit_before> int iobuf_timeout(iobuf* io, int poll_out) { struct pollfd pfd; int result; if (!io->timeout) return 1; pfd.fd = io->fd; pfd.events = poll_out ? POLLOUT : POLLIN; while ((result = poll(&pfd, 1, io->timeout)) == -1) { if (errno == EAGAIN) continue; IOBUF_SET_ERROR(io); } if (result) return 1; io->flags |= IOBUF_TIMEOUT; return 0; } <commit_after> int iobuf_timeout(iobuf* io, int poll_out) { iopoll_fd pfd; int result; if (!io->timeout) return 1; pfd.fd = io->fd; pfd.events = poll_out ? IOPOLL_WRITE : IOPOLL_READ; while ((result = iopoll(&pfd, 1, io->timeout)) == -1) { if (errno == EAGAIN) continue; IOBUF_SET_ERROR(io); } if (result) return 1; io->flags |= IOBUF_TIMEOUT; return 0; }
<commit_msg>Update JSONGeneratorEncoder to subclass DjangoJSONEncoder This handles Decimals and datetimes<commit_before>import json import inspect from _base import BaseExporter class JSONGeneratorEncoder(json.JSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff <commit_after>import inspect from django.core.serializers.json import DjangoJSONEncoder from _base import BaseExporter class JSONGeneratorEncoder(DjangoJSONEncoder): "Handle generator objects and expressions." def default(self, obj): if inspect.isgenerator(obj): return list(obj) return super(JSONGeneratorEncoder, self).default(obj) class JSONExporter(BaseExporter): file_extension = 'json' content_type = 'application/json' preferred_formats = ('number', 'string') def write(self, iterable, buff=None): buff = self.get_file_obj(buff) encoder = JSONGeneratorEncoder() for chunk in encoder.iterencode(self.read(iterable)): buff.write(chunk) return buff
<commit_msg>Create the waypoint structure operating function prototype <commit_before> struct waypoint_t mission_wp_list = {0}; int waypoint_cnt = 0; int cur_waypoint = 0; mavlink_message_t msg; uint8_t buf[MAV_MAX_LEN]; void mission_read_waypoint_list() { } void mission_write_waypoint_list() { } void mission_clear_waypoint() { mavlink_msg_mission_ack_pack(1, 200, &msg, 255, 0, 0); send_package(buf, &msg); } void mission_set_new_current_waypoint() { } <commit_after> struct waypoint_t mission_wp_list = {0}; int waypoint_cnt = 0; int cur_waypoint = 0; mavlink_message_t msg; uint8_t buf[MAV_MAX_LEN]; void push_waypoint_node(struct waypoint_t *waypoint) { } void free_waypoint_list(struct waypoint_t *waypoint) { } void mission_read_waypoint_list() { } void mission_write_waypoint_list() { } void mission_clear_waypoint() { mavlink_msg_mission_ack_pack(1, 200, &msg, 255, 0, 0); send_package(buf, &msg); } void mission_set_new_current_waypoint() { }
<commit_msg>Return unique pointer to const tensor instead. <commit_before>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/eval/eval/tensor_spec.h> #include <vespa/eval/tensor/default_tensor_engine.h> #include <vespa/vespalib/testkit/test_kit.h> namespace vespalib::tensor::test { template <typename T> std::unique_ptr<T> makeTensor(const vespalib::eval::TensorSpec &spec) { auto value = DefaultTensorEngine::ref().from_spec(spec); const T *tensor = dynamic_cast<const T *>(value->as_tensor()); ASSERT_TRUE(tensor); value.release(); return std::unique_ptr<T>(const_cast<T *>(tensor)); } } <commit_after>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/eval/eval/tensor_spec.h> #include <vespa/eval/tensor/default_tensor_engine.h> #include <vespa/vespalib/testkit/test_kit.h> namespace vespalib::tensor::test { template <typename T> std::unique_ptr<const T> makeTensor(const vespalib::eval::TensorSpec &spec) { auto value = DefaultTensorEngine::ref().from_spec(spec); const T *tensor = dynamic_cast<const T *>(value->as_tensor()); ASSERT_TRUE(tensor); value.release(); return std::unique_ptr<const T>(tensor); } }
<commit_msg>Fix issue with config wiring <commit_before>package org.apereo.cas.token.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * This is {@link TokenCoreConfiguration}. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration("tokenAuthenticationConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class TokenCoreConfiguration { } <commit_after>package org.apereo.cas.token.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * This is {@link TokenCoreConfiguration}. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration("tokenCoreConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class TokenCoreConfiguration { }
<commit_msg>Make request a property on HTTPRequestContext. <commit_before>from asphalt.core import Context from typeguard import check_argument_types class HTTPRequestContext(Context): """ Sub-class of context used for HTTP requests. """ cfg = {} def __init__(self, request, parent: Context): assert check_argument_types() super().__init__(parent=parent) self.request = request <commit_after>from asphalt.core import Context from typeguard import check_argument_types import kyokai class HTTPRequestContext(Context): """ Sub-class of context used for HTTP requests. """ cfg = {} def __init__(self, request, parent: Context): assert check_argument_types() super().__init__(parent=parent) self._request = request @property def request(self) -> 'kyokai.Request': return self._request
<commit_msg>Define UIBackgroundTaskIdentifier if on OS X <commit_before>// // TMCacheBackgroundTaskManager.h // TMCache // // Created by Bryan Irace on 4/24/15. // Copyright (c) 2015 Tumblr. All rights reserved. // @import UIKit; /** A protocol that classes who can begin and end background tasks can conform to. This protocol provides an abstraction in order to avoid referencing `+ [UIApplication sharedApplication]` from within an iOS application extension. */ @protocol TMCacheBackgroundTaskManager <NSObject> /** Marks the beginning of a new long-running background task. @return A unique identifier for the new background task. You must pass this value to the `endBackgroundTask:` method to mark the end of this task. This method returns `UIBackgroundTaskInvalid` if running in the background is not possible. */ - (UIBackgroundTaskIdentifier)beginBackgroundTask; /** Marks the end of a specific long-running background task. @param identifier An identifier returned by the `beginBackgroundTaskWithExpirationHandler:` method. */ - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier; @end <commit_after>// // TMCacheBackgroundTaskManager.h // TMCache // // Created by Bryan Irace on 4/24/15. // Copyright (c) 2015 Tumblr. All rights reserved. // @import UIKit; #ifndef __IPHONE_OS_VERSION_MIN_REQUIRED typedef NSUInteger UIBackgroundTaskIdentifier; #endif /** A protocol that classes who can begin and end background tasks can conform to. This protocol provides an abstraction in order to avoid referencing `+ [UIApplication sharedApplication]` from within an iOS application extension. */ @protocol TMCacheBackgroundTaskManager <NSObject> /** Marks the beginning of a new long-running background task. @return A unique identifier for the new background task. You must pass this value to the `endBackgroundTask:` method to mark the end of this task. This method returns `UIBackgroundTaskInvalid` if running in the background is not possible. */ - (UIBackgroundTaskIdentifier)beginBackgroundTask; /** Marks the end of a specific long-running background task. @param identifier An identifier returned by the `beginBackgroundTaskWithExpirationHandler:` method. */ - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier; @end
<commit_msg>Add long description for PyPI upload <commit_before> try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='pyft232', version='0.8', description="Python bindings to d2xx and libftdi to access FT232 chips with " "the same interface as pyserial. Using this method gives easy access " "to the additional features on the chip like CBUS GPIO.", long_description=open('README.md', 'rt').read(), author='Logan Gunthorpe', author_email='logang@deltatee.com', packages=['ft232'], install_requires=[ 'pyusb >= 0.4', 'pyserial >= 2.5', ] ) <commit_after> try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='pyft232', version='0.8', description="Python bindings to d2xx and libftdi to access FT232 chips with " "the same interface as pyserial. Using this method gives easy access " "to the additional features on the chip like CBUS GPIO.", long_description=open('README.md', 'rt').read(), long_description_content_type="text/markdown", author='Logan Gunthorpe', author_email='logang@deltatee.com', packages=['ft232'], install_requires=[ 'pyusb >= 0.4', 'pyserial >= 2.5', ] )
<commit_msg>tests.features: Fix OS X test skip. <commit_before>from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: pass else: try: binary = subprocess.check_output(["which", exe]).decode('utf8').strip() except: pass if binary is None: print( "Skipping scenario", context.scenario, "(executable %s not found)" % exe, file = sys.stderr ) context.scenario.skip("The executable '%s' is not present" % exe) else: print( "Found executable '%s' at '%s'" % (exe, binary), file = sys.stderr ) @then('{exe} is a static executable') def step_impl(ctx, exe): if sys.platform.lower().startswith('darwin'): context.scenario.skip("Static runtime linking is not supported on OS X") if sys.platform.startswith('win'): lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n') for line in lines: if 'msvcrt' in line.lower(): assert False, 'Found MSVCRT: %s' % line else: out = subprocess.check_output(["file", exe]).decode('utf8') assert 'statically linked' in out, "Not a static executable: %s" % out <commit_after>from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: pass else: try: binary = subprocess.check_output(["which", exe]).decode('utf8').strip() except: pass if binary is None: print( "Skipping scenario", context.scenario, "(executable %s not found)" % exe, file = sys.stderr ) context.scenario.skip("The executable '%s' is not present" % exe) else: print( "Found executable '%s' at '%s'" % (exe, binary), file = sys.stderr ) @then('{exe} is a static executable') def step_impl(ctx, exe): if sys.platform.lower().startswith('darwin'): ctx.scenario.skip("Static runtime linking is not supported on OS X") return if sys.platform.startswith('win'): lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n') for line in lines: if 'msvcrt' in line.lower(): assert False, 'Found MSVCRT: %s' % line else: out = subprocess.check_output(["file", exe]).decode('utf8') assert 'statically linked' in out, "Not a static executable: %s" % out
<commit_msg>Copy template structure for the create command <commit_before>import os from finny.command import Command class GenerateStructure(Command): def __init__(self, name, path): self.name = name self.path = path def run(self): os.mkdir(self.path, 0755) """ You need to create: .gitignore requirements.txt README.md manage.py {{ app_name }}: initializers: app.py boot.py runners: default.py development.py test.py production.py monitors: api.py models.py tests: fixtures/ test_base.py utils.py """ <commit_after>import os from finny.command import Command BASE_FOLDER_TEMPLATES = [ ".gitignore", "requirements.txt", "README.md", "manage.py" ] CONFIG_INITIALIZERS_TEMPLATES = [ "app.py" ] CONFIG_RUNNERS_TEMPLATES = [ "default.py" ] CONFIG_TEMPLATES = [ "boot.py", "development.py.sample" "test.py.sample", "production.py.sample" ] TEMPLATES_PATH = "" class GenerateStructure(Command): def __init__(self, name, path): self.name = name self.path = path def _template(self, template_name, path): pass def _copy_template(self, source, src, dst): pass def run(self): os.mkdir(self.path, 0755) self._copy_templates(BASE_FOLDER_TEMPLATES, TEMPLATES_PATH, self.path) self._copy_templates(CONFIG_INITIALIZERS_TEMPLATES, TEMPLATES_PATH + "initializers", "%s/%s/initializers" % (self.path, self.name) ) self._copy_templates(CONFIG_RUNNERS_TEMPLATES, TEMPLATES_PATH + "runners", "%s/%s/runners" % (self.path, self.name) ) self._copy_templates(CONFIG_TEMPLATES, TEMPLATES_PATH + "config", "%s/%s/" % (self.path, self.name) )
<commit_msg>Add option to modify module in createApp mocking function <commit_before>import { run, deepmerge, Module } from '../core' export const ChildComp = { state: { count: 0 }, inputs: F => ({ inc: async () => { await F.toAct('Inc') await F.toIt('changed', F.stateOf().count) }, changed: async value => {}, }), actions: { Inc: () => s => { s.count++ return s }, }, interfaces: {}, } export const createApp = (comp?): Promise<Module> => { const Root = { state: { result: '' }, inputs: F => ({}), actions: {}, interfaces: {}, } const DEV = true return run({ Root: deepmerge(Root, comp || {}), record: DEV, log: DEV, interfaces: {}, }) } <commit_after>import { run, deepmerge, Module } from '../core' export const ChildComp = { state: { count: 0 }, inputs: F => ({ inc: async () => { await F.toAct('Inc') await F.toIt('changed', F.stateOf().count) }, changed: async value => {}, }), actions: { Inc: () => s => { s.count++ return s }, }, interfaces: {}, } export const createApp = (comp?, mod?): Promise<Module> => { const Root = { state: { result: '' }, inputs: F => ({}), actions: {}, interfaces: {}, } const DEV = true return run(deepmerge({ Root: deepmerge(Root, comp || {}), record: DEV, log: DEV, interfaces: {}, }, mod || {})) }
<commit_msg>Add a function to the card list for collapsing all child cards <commit_before>import { Component, Input, ContentChild } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; } <commit_after>import { Component, Input, ContentChild, ViewChildren, QueryList } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; @ViewChildren(Card) cards: QueryList<Card>; collapseAll() { this.cards.map((card: Card) => card.close()); } }
<commit_msg>Set waiting before io to stop repeat reads <commit_before>// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com> // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL was not // distributed with this file, You can obtain one at // http://mozilla.org/MPL/2.0/. #[macro_use] extern crate log; extern crate libc; extern crate errno; extern crate threadpool; extern crate simple_slab; use std::io::Error; use std::sync::Arc; use std::cell::UnsafeCell; use std::net::TcpListener; use std::os::unix::io::{RawFd, AsRawFd}; use config::Config; pub mod config; mod server; pub trait Stream : AsRawFd + Send + Sync { fn recv(&mut self) -> Result<Vec<Vec<u8>>, Error>; fn send(&mut self, buf: &[u8]) -> Result<(), Error>; } pub trait Handler { fn on_server_created(&mut self, fd: RawFd); fn on_new_connection(&mut self, fd: RawFd) -> Arc<UnsafeCell<Stream>>; fn on_data_received(&mut self, arc_stream: Arc<UnsafeCell<Stream>>, buf: Vec<u8>); fn on_connection_removed(&mut self, fd: RawFd); } pub fn begin<T>(handler: Box<T>, cfg: Config) where T: Handler + Send + Sync + 'static { server::begin(handler, cfg); } <commit_after>// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com> // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL was not // distributed with this file, You can obtain one at // http://mozilla.org/MPL/2.0/. #[macro_use] extern crate log; extern crate libc; extern crate errno; extern crate threadpool; extern crate simple_slab; use std::io::Error; use std::sync::Arc; use std::cell::UnsafeCell; use std::os::unix::io::{RawFd, AsRawFd}; use config::Config; pub mod config; mod server; pub trait Stream : AsRawFd + Send + Sync { fn recv(&mut self) -> Result<Vec<Vec<u8>>, Error>; fn send(&mut self, buf: &[u8]) -> Result<(), Error>; } pub trait Handler { fn on_server_created(&mut self, fd: RawFd); fn on_new_connection(&mut self, fd: RawFd) -> Arc<UnsafeCell<Stream>>; fn on_data_received(&mut self, arc_stream: Arc<UnsafeCell<Stream>>, buf: Vec<u8>); fn on_connection_removed(&mut self, fd: RawFd); } pub fn begin<T>(handler: Box<T>, cfg: Config) where T: Handler + Send + Sync + 'static { server::begin(handler, cfg); }
<commit_msg>Set default locale in test to avoid test failures when different default is used than expected. <commit_before> import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') self.app_context = app.app_context() self.app_context.push() self.client = app.test_client(use_cookies = True) def tearDown(self): self.app_context.pop() def test_index(self): response = self.client.get('/') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard!' in data) response = self.client.get('/BMeu') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard, BMeu!' in data) <commit_after> import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') app.config['BABEL_DEFAULT_LOCALE'] = 'en' self.app_context = app.app_context() self.app_context.push() self.client = app.test_client(use_cookies = True) def tearDown(self): self.app_context.pop() def test_index(self): response = self.client.get('/') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard!' in data) response = self.client.get('/BMeu') data = response.get_data(as_text = True) self.assertEqual(response.status_code, 200) self.assertTrue('Welcome to the Orchard, BMeu!' in data)
<commit_msg>Add long types to names. <commit_before> using JasonType = triagens::basics::JasonType; //////////////////////////////////////////////////////////////////////////////// /// @brief get the name for a Jason type //////////////////////////////////////////////////////////////////////////////// char const* triagens::basics::JasonTypeName (JasonType type) { switch (type) { case JasonType::None: return "none"; case JasonType::Null: return "null"; case JasonType::Bool: return "bool"; case JasonType::Double: return "double"; case JasonType::String: return "string"; case JasonType::Array: return "array"; case JasonType::Object: return "object"; case JasonType::External: return "external"; case JasonType::ID: return "id"; case JasonType::ArangoDB_id: return "arangodb_id"; case JasonType::UTCDate: return "utc-date"; case JasonType::Int: return "int"; case JasonType::UInt: return "uint"; case JasonType::Binary: return "binary"; } return "unknown"; } <commit_after> using JasonType = triagens::basics::JasonType; //////////////////////////////////////////////////////////////////////////////// /// @brief get the name for a Jason type //////////////////////////////////////////////////////////////////////////////// char const* triagens::basics::JasonTypeName (JasonType type) { switch (type) { case JasonType::None: return "none"; case JasonType::Null: return "null"; case JasonType::Bool: return "bool"; case JasonType::Double: return "double"; case JasonType::String: return "string"; case JasonType::Array: return "array"; case JasonType::ArrayLong: return "array_long"; case JasonType::Object: return "object"; case JasonType::ObjectLong: return "object_long"; case JasonType::External: return "external"; case JasonType::ID: return "id"; case JasonType::ArangoDB_id: return "arangodb_id"; case JasonType::UTCDate: return "utc-date"; case JasonType::Int: return "int"; case JasonType::UInt: return "uint"; case JasonType::Binary: return "binary"; } return "unknown"; }
<commit_msg>Add options for yearly sst data, move some other stuff around a bit <commit_before>C $Header$ C $Name$ c Ocean Exports c ------------------- common /ocean_exports/ sst, sice, ksst, kice _RL sst(1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nsx,Nsy) _RL sice(1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nsx,Nsy) integer ksst, kice <commit_after>C $Header$ C $Name$ c Ocean Parameters c ------------------- common /ocean_params/sstclim,sstfreq,siceclim,sicefreq,ksst,kice logical sstclim,sstfreq,siceclim,sicefreq integer ksst, kice c Ocean Exports c ------------------- common /ocean_exports/ sst, sice _RL sst(1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nsx,Nsy) _RL sice(1-OLx:sNx+OLx,1-OLy:sNy+OLy,Nsx,Nsy)
<commit_msg>Migrate phone numbers to E.164 format <commit_before>from __future__ import unicode_literals from django.db import models, migrations import two_factor.models class Migration(migrations.Migration): dependencies = [ ('two_factor', '0002_auto_20150110_0810'), ] operations = [ migrations.AlterField( model_name='phonedevice', name='number', field=two_factor.models.PhoneNumberField(max_length=16, verbose_name='number'), ), ] <commit_after>from __future__ import unicode_literals import logging from django.db import models, migrations import phonenumbers import two_factor.models logger = logging.getLogger(__name__) def migrate_phone_numbers(apps, schema_editor): PhoneDevice = apps.get_model("two_factor", "PhoneDevice") for device in PhoneDevice.objects.all(): try: number = phonenumbers.parse(device.number) if not phonenumbers.is_valid_number(number): logger.info("User '%s' has an invalid phone number '%s'." % (device.user.username, device.number)) device.number = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) device.save() except phonenumbers.NumberParseException as e: # Do not modify/delete the device, as it worked before. However this might result in issues elsewhere, # so do log a warning. logger.warning("User '%s' has an invalid phone number '%s': %s. Please resolve this issue, " "as it might result in errors." % (device.user.username, device.number, e)) class Migration(migrations.Migration): dependencies = [ ('two_factor', '0002_auto_20150110_0810'), ] operations = [ migrations.RunPython(migrate_phone_numbers, reverse_code=lambda apps, schema_editor: None), migrations.AlterField( model_name='phonedevice', name='number', field=two_factor.models.PhoneNumberField(max_length=16, verbose_name='number'), ), ]
<commit_msg>Fix humanReadableJoin not being a pure function <commit_before>/** * Joins a list of strings to produce a human readable string: * * > humanReadableJoin(["apple", "banana", "orange"]) * "apple, banana, and orange" */ export function humanReadableJoin(list: string[]) { return list.concat(list.splice(-2, 2).join(" and ")).join(", "); }<commit_after>/** * Joins a list of strings to produce a human readable string: * * > humanReadableJoin(["apple", "banana", "orange"]) * "apple, banana, and orange" */ export function humanReadableJoin(list: string[]) { list = list.slice(); return list.concat(list.splice(-2, 2).join(" and ")).join(", "); }
<commit_msg>Add nullable annotations to header <commit_before>// // JMAttributedFormat.h // JMAttributedFormat // // Created by Jonathon Mah on 2015-04-11. // This file is licensed under the MIT License. See LICENSE.txt for full details. // #import <Foundation/Foundation.h> @interface NSObject (JMAttributedFormat_Optional) - (NSAttributedString *)attributedDescription; @end @interface NSAttributedString (JMAttributedFormat) + (instancetype)attributedStringWithFormat:(NSString *)formatString, ... NS_FORMAT_FUNCTION(1,2); + (instancetype)attributedStringWithBaseAttributes:(NSDictionary *)baseAttributes format:(NSString *)formatString, ... NS_FORMAT_FUNCTION(2,3); - (instancetype)initWithBaseAttributes:(NSDictionary *)baseAttributes format:(NSString *)formatString, ... NS_FORMAT_FUNCTION(2,3); - (instancetype)initWithBaseAttributes:(NSDictionary *)baseAttributes format:(NSString *)formatString arguments:(va_list)argList NS_FORMAT_FUNCTION(2,0); @end <commit_after>// // JMAttributedFormat.h // JMAttributedFormat // // Created by Jonathon Mah on 2015-04-11. // This file is licensed under the MIT License. See LICENSE.txt for full details. // #import <Foundation/Foundation.h> @interface NSObject (JMAttributedFormat_Optional) - (nullable NSAttributedString *)attributedDescription; @end @interface NSAttributedString (JMAttributedFormat) + (nullable instancetype)attributedStringWithFormat:(nonnull NSString *)formatString, ... NS_FORMAT_FUNCTION(1,2); + (nullable instancetype)attributedStringWithBaseAttributes:(nullable NSDictionary *)baseAttributes format:(nonnull NSString *)formatString, ... NS_FORMAT_FUNCTION(2,3); - (nullable instancetype)initWithBaseAttributes:(nullable NSDictionary *)baseAttributes format:(nonnull NSString *)formatString, ... NS_FORMAT_FUNCTION(2,3); - (nullable instancetype)initWithBaseAttributes:(nullable NSDictionary *)baseAttributes format:(nonnull NSString *)formatString arguments:(va_list)argList NS_FORMAT_FUNCTION(2,0); @end
<commit_msg>Examples: Use more common technical term <commit_before>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete mappings inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; } <commit_after>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete key-value pairs inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; }
<commit_msg>Add Enum for PersonIdentifier Fields This is similar to the work to remove SimplePopoloFields from the database layer. The values here are all the values we want in the initial version of the "n-links" on the person page model. One day we want to enable any type of link, specified by the user. That's too big a change to do all at once, so step one is to remove ComplexPopoloFields in the database but still use a fixed list of fields. <commit_before>from .helpers.popolo_fields import simple_fields SIMPLE_POPOLO_FIELDS = simple_fields <commit_after>from enum import Enum, unique from .helpers.popolo_fields import simple_fields SIMPLE_POPOLO_FIELDS = simple_fields @unique class PersonIdentifierFields(Enum): email = "Email" facebook_page_url = "Facebook Page" facebook_personal_url = "Facebook Personal" homepage_url = "Homepage" linkedin_url = "Linkedin" party_ppc_page_url = "Party PPC Page" twitter_username = "Twitter" wikipedia_url = "Wikipedia" # party_candidate_page = "Party Candidate Page" # other = "Other"
<commit_msg>Fix incorrect description of returned dict entries <commit_before>import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with keys 'S1' and 'ST' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file <commit_after>import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
<commit_msg>Set default invalid/unset line to -1, to reduce confusion with 0 being interpreted as the first line. <commit_before>package io.collap.bryg.compiler.ast; import io.collap.bryg.compiler.context.Context; import java.io.PrintStream; public abstract class Node { protected Context context; private int line = 0; protected Node (Context context) { this.context = context; } /** * IMPORTANT NOTE: All (named) variables *must* be resolved in the Node constructors. Using any "current" Scope in the `compile` * method yields undefined behaviour! The root scope can be used to allocate space for anonymous temporal variables. */ public abstract void compile (); public void print (PrintStream out, int depth) { /* Print line number with indent. */ String lineStr; if (line > 0) { lineStr = line + ": "; }else { lineStr = " "; } for (int i = lineStr.length (); i < 7; ++i) { out.print (' '); } out.print (lineStr); /* Print depth node indent. */ for (int i = 0; i < depth; ++i) { out.print (" "); } /* Print class name. */ out.println (getClass ().getSimpleName ()); } public int getLine () { return line; } protected void setLine (int line) { this.line = line; } } <commit_after>package io.collap.bryg.compiler.ast; import io.collap.bryg.compiler.context.Context; import java.io.PrintStream; public abstract class Node { protected Context context; /** * A line of -1 indicates that the line has not been set! */ private int line = -1; protected Node (Context context) { this.context = context; } /** * IMPORTANT NOTE: All (named) variables *must* be resolved in the Node constructors. Using any "current" Scope in the `compile` * method yields undefined behaviour! The root scope can be used to allocate space for anonymous temporal variables. */ public abstract void compile (); public void print (PrintStream out, int depth) { /* Print line number with indent. */ String lineStr; if (line > 0) { lineStr = line + ": "; }else { lineStr = " "; } for (int i = lineStr.length (); i < 7; ++i) { out.print (' '); } out.print (lineStr); /* Print depth node indent. */ for (int i = 0; i < depth; ++i) { out.print (" "); } /* Print class name. */ out.println (getClass ().getSimpleName ()); } public int getLine () { return line; } protected void setLine (int line) { this.line = line; } }
<commit_msg>Remove comment. Just a trigger for a new build. <commit_before>// yaml-cpp includes #include "yaml-cpp/yaml.h" int main() { YAML::Emitter out; out << "Hello, World!"; std::cout << "Here's the output YAML:\n" << out.c_str(); return 0; } <commit_after> int main() { YAML::Emitter out; out << "Hello, World!"; std::cout << "Here's the output YAML:\n" << out.c_str(); return 0; }
<commit_msg>Convert the adapter into a pytest fixture <commit_before>from schematics.models import Model from schematics.types import IntType from hyp.adapters.schematics import SchematicsSerializerAdapter class Post(object): def __init__(self): self.id = 1 class Simple(Model): id = IntType() def test_object_conversion(): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive(Post())['id'] == 1 def test_dict_conversion(): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive({'id': 1})['id'] == 1 <commit_after>import pytest from schematics.models import Model from schematics.types import IntType from hyp.adapters.schematics import SchematicsSerializerAdapter class Post(object): def __init__(self): self.id = 1 class Simple(Model): id = IntType() @pytest.fixture def adapter(): return SchematicsSerializerAdapter(Simple) def test_object_conversion(adapter): assert adapter.to_primitive(Post())['id'] == 1 def test_dict_conversion(adapter): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive({'id': 1})['id'] == 1
<commit_msg>Update prototypes to make them more compliant. <commit_before> void PwmInit(uint8_t channel); void PwmSetPeriod(uint8_t channel, uint32_t frequency); void PwmSetDuty(uint8_t channel, uint8_t duty); typedef struct { uint32_t frequency; uint8_t duty; } PwmOutput; #endif //PWM_H <commit_after> extern void PwmInit(uint8_t channel); extern void PwmSetPeriod(uint8_t channel, uint32_t frequency); extern void PwmSetDuty(uint8_t channel, uint8_t duty); typedef struct { uint32_t frequency; uint8_t duty; } PwmOutput; #endif //PWM_H
<commit_msg>Add python2 specifically to classifier list. <commit_before>import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='nielsenb@jetfuse.net', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) <commit_after>import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='nielsenb@jetfuse.net', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
<commit_msg>Stop experimenting on this project for the moment<commit_before>''' Created on Jan 15, 2017 @author: Marlon_2 ''' import tkinter as tk # import from tkinter import ttk # impork ttk from tkinter win = tk.Tk(); # create instance #add a title win.title("Python Hospital Information System"); #add a label #ttk.Label(win, text="Welcome to Python Hospital Information System").grid(column=0,row=0); aLabel = ttk.Label(win, text="Welcome to Python Hospital Information System"); aLabel.grid(column=0,row=0); def clickMe(): action.configure(text="** I have been clicked **") aLabel.configure(foreground='red',background='yellow') #Adding a button action = ttk.Button(win, text="Click Me!", command=clickMe) action.grid(column=0, row=1); #button click event callback function #win.resizable(200, 100); # disable resizing of the GUI win.mainloop(); # start GUI<commit_after>''' Created on Jan 15, 2017 @author: Marlon_2 ''' import tkinter as tk # import from tkinter import ttk # impork ttk from tkinter win = tk.Tk(); # create instance #add a title win.title("Python Hospital Information System"); #add a label #ttk.Label(win, text="Welcome to Python Hospital Information System").grid(column=0,row=0); aLabel = ttk.Label(win, text="Welcome to Python Hospital Information System"); aLabel.grid(column=0,row=0); def clickMe(): action.configure(text="** I have been clicked **") aLabel.configure(foreground='red',background='yellow') # action = ttk.Button(win, command=clickMeReset) # action.grid(column=0, row=1); def clickMeReset(): action.configure(text="** Click Me! **") aLabel.configure(foreground='black',background='white') # action = ttk.Button(win, command=clickMe) # action.grid(column=0, row=1); #Adding a button action = ttk.Button(win, text="Click Me!", command=clickMe) action.grid(column=0, row=1); #button click event callback function #win.resizable(200, 100); # disable resizing of the GUI win.mainloop(); # start GUI
<commit_msg>Fix bug in loading of c* modules <commit_before>from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) <commit_after>from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): try: challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) except: continue