text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Set option to produce 'div's instead of 'p's
Summary:
Fixes issue with 78eb5ef0, I neglected change the setting.
Test Plan:
Open a perseus exercise, see questions are formatted with 'div's instead
of 'p's.
Auditors: alpert, jack | (function(undefined) {
var Util = require("./util.js");
var Perseus = window.Perseus = {
Util: Util
};
Perseus.init = function(options) {
_.defaults(options, {
// Pass skipMathJax: true if MathJax is already loaded and configured.
skipMathJax: false,
// A function which takes a file object (guaranteed to be an image) and
// a callback, then calls the callback with the url where the image
// will be hosted. Image drag and drop is disabled when imageUploader
// is null.
imageUploader: null
});
var deferred = $.Deferred();
markedReact.setOptions({
sanitize: true,
paragraphFn: function(text) {
return React.DOM.div({className: 'paragraph'}, text);
}
});
if (options.skipMathJax) {
deferred.resolve();
} else {
MathJax.Hub.Config({
messageStyle: "none",
skipStartupTypeset: "none",
"HTML-CSS": {
availableFonts: ["TeX"],
imageFont: null,
scale: 100,
showMathMenu: false
}
});
MathJax.Hub.Configured();
MathJax.Hub.Queue(deferred.resolve);
}
Perseus.imageUploader = options.imageUploader;
return deferred;
};
})();
| (function(undefined) {
var Util = require("./util.js");
var Perseus = window.Perseus = {
Util: Util
};
Perseus.init = function(options) {
_.defaults(options, {
// Pass skipMathJax: true if MathJax is already loaded and configured.
skipMathJax: false,
// A function which takes a file object (guaranteed to be an image) and
// a callback, then calls the callback with the url where the image
// will be hosted. Image drag and drop is disabled when imageUploader
// is null.
imageUploader: null
});
var deferred = $.Deferred();
markedReact.setOptions({
sanitize: true
});
if (options.skipMathJax) {
deferred.resolve();
} else {
MathJax.Hub.Config({
messageStyle: "none",
skipStartupTypeset: "none",
"HTML-CSS": {
availableFonts: ["TeX"],
imageFont: null,
scale: 100,
showMathMenu: false
}
});
MathJax.Hub.Configured();
MathJax.Hub.Queue(deferred.resolve);
}
Perseus.imageUploader = options.imageUploader;
return deferred;
};
})();
|
Update view model life cycle | package com.tehmou.rxbookapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tehmou.rxbookapp.data.DataStore;
import com.tehmou.rxbookapp.viewmodels.BookViewModel;
import com.tehmou.rxbookapp.views.BookInfoView;
/**
* Created by ttuo on 19/03/14.
*/
public class BookFragment extends Fragment {
private BookViewModel bookViewModel;
private BookInfoView bookInfoView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bookViewModel = new BookViewModel(DataStore.getInstance(), "436346");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bookInfoView = (BookInfoView) view.findViewById(R.id.book_info_view);
bookViewModel.subscribeToDataStore();
}
@Override
public void onDestroyView() {
super.onDestroyView();
bookViewModel.unsubscribeFromDataStore();
}
@Override
public void onResume() {
super.onResume();
bookInfoView.setViewModel(bookViewModel);
}
@Override
public void onPause() {
super.onPause();
bookInfoView.setViewModel(null);
}
}
| package com.tehmou.rxbookapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tehmou.rxbookapp.data.DataStore;
import com.tehmou.rxbookapp.viewmodels.BookViewModel;
import com.tehmou.rxbookapp.views.BookInfoView;
/**
* Created by ttuo on 19/03/14.
*/
public class BookFragment extends Fragment {
private BookViewModel bookViewModel;
private BookInfoView bookInfoView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bookViewModel = new BookViewModel(DataStore.getInstance(), "436346");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bookInfoView = (BookInfoView) view.findViewById(R.id.book_info_view);
bookInfoView.setViewModel(bookViewModel);
}
@Override
public void onResume() {
super.onResume();
bookViewModel.subscribeToDataStore();
}
@Override
public void onPause() {
super.onPause();
bookViewModel.unsubscribeFromDataStore();
}
}
|
Hide software keypad, when open registration form | package com.elpatika.stepic.view;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.elpatika.stepic.R;
import com.elpatika.stepic.base.BaseFragmentActivity;
import roboguice.inject.InjectView;
public class RegisterActivity extends BaseFragmentActivity {
@InjectView(R.id.createAccount_button_layout)
RelativeLayout mCreateAccountButton;
@InjectView (R.id.actionbar_close_btn)
View mCloseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_transition);
hideSoftKeypad();
mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAccount();
}
});
mCloseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom);
}
private void createAccount() {
//todo: create account
Toast toast = Toast.makeText(this, "Sorry, this function is unimplemented", Toast.LENGTH_SHORT);
toast.show();
}
}
| package com.elpatika.stepic.view;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.elpatika.stepic.R;
import com.elpatika.stepic.base.BaseFragmentActivity;
import roboguice.inject.InjectView;
public class RegisterActivity extends BaseFragmentActivity {
@InjectView(R.id.createAccount_button_layout)
RelativeLayout mCreateAccountButton;
@InjectView (R.id.actionbar_close_btn)
View mCloseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_transition);
mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAccount();
}
});
mCloseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom);
}
private void createAccount() {
//todo: create account
Toast toast = Toast.makeText(this, "Sorry, this function is unimplemented", Toast.LENGTH_SHORT);
toast.show();
}
}
|
Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738 | # -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
| # -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
|
Drop python 2.6 support from metadata | import codecs
import re
from os import path
from setuptools import setup
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def find_version(*parts):
version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='django-predicate',
version=find_version('predicate', '__init__.py'),
description='A predicate class constructed like Django Q objects, used to '
'test whether a new or modified model would match a query',
long_description=read('README.rst'),
author='Preston Holmes',
author_email='[email protected]',
license='BSD',
url='http://github.com/ptone/django-predicate',
packages=[
'predicate',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
test_suite='runtests.runtests'
)
| import codecs
import re
from os import path
from setuptools import setup
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def find_version(*parts):
version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='django-predicate',
version=find_version('predicate', '__init__.py'),
description='A predicate class constructed like Django Q objects, used to '
'test whether a new or modified model would match a query',
long_description=read('README.rst'),
author='Preston Holmes',
author_email='[email protected]',
license='BSD',
url='http://github.com/ptone/django-predicate',
packages=[
'predicate',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
test_suite='runtests.runtests'
)
|
Fix trade-type-picker click event leak to asset-picker | import React, { PureComponent } from 'react';
import { Label, DownArrow } from 'binary-components';
import DropDown from '../containers/DropDown';
import { actions } from '../_store';
import AssetPickerContainer from './AssetPickerContainer';
type Props = {
index: number,
selectedSymbol: string,
selectedSymbolName: string,
};
export default class AssetPickerDropDown extends PureComponent {
props: Props;
static contextTypes = {
router: () => undefined,
};
constructor(props: Props) {
super(props);
this.state = {
dropdownShown: false,
};
}
onClose = () =>
this.setState({ dropdownShown: false });
onSelect = newAsset => {
const { index } = this.props;
actions.reqSymbolChange(index, newAsset);
}
openPicker = () => {
actions.resetAssetPickerFilter();
this.setState({ dropdownShown: true });
}
render() {
const { index, selectedSymbol, selectedSymbolName } = this.props;
const { dropdownShown } = this.state;
return (
<div className="param-row">
<DropDown
shown={dropdownShown}
title="Assets"
onClose={this.onClose}
>
<AssetPickerContainer
index={index}
selectedAsset={selectedSymbol}
onSelect={this.onSelect}
/>
</DropDown>
<Label text="Asset" />
<div className="picker-label param-field" onClick={this.openPicker}>
<div className="picker-value">{selectedSymbolName}</div>
<DownArrow />
</div>
</div>
);
}
}
| import React, { PureComponent } from 'react';
import { Label, DownArrow } from 'binary-components';
import DropDown from '../containers/DropDown';
import { actions } from '../_store';
import AssetPickerContainer from './AssetPickerContainer';
type Props = {
index: number,
selectedSymbol: string,
selectedSymbolName: string,
};
export default class AssetPickerDropDown extends PureComponent {
props: Props;
static contextTypes = {
router: () => undefined,
};
constructor(props: Props) {
super(props);
this.state = {
dropdownShown: false,
};
}
onClose = () =>
this.setState({ dropdownShown: false });
onSelect = newAsset => {
const { index } = this.props;
actions.reqSymbolChange(index, newAsset);
}
openPicker = () => {
actions.resetAssetPickerFilter();
this.setState({ dropdownShown: true });
}
render() {
const { index, selectedSymbol, selectedSymbolName } = this.props;
const { dropdownShown } = this.state;
return (
<div className="param-row">
<DropDown
shown={dropdownShown}
title="Assets"
onClose={this.onClose}
>
<AssetPickerContainer
index={index}
selectedAsset={selectedSymbol}
onSelect={this.onSelect}
/>
</DropDown>
<Label text="Asset" />
<div className="picker-label param-field" onMouseDown={this.openPicker}>
<div className="picker-value">{selectedSymbolName}</div>
<DownArrow />
</div>
</div>
);
}
}
|
Check for existing configuration in setup command | <?php
namespace Propaganistas\LaravelFakeId\Commands;
use Illuminate\Console\Command;
use Jenssegers\Optimus\Energon;
class FakeIdSetupCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'fakeid:setup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configures FakeId for use';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// Write in environment file.
$path = base_path('.env');
if (! file_exists($path)) {
$this->error("Environment file (.env) not found. Aborting FakeId setup!");
return;
}
$env = file($path);
// Detect existing configuration.
if (str_contains(implode(' ', $env), 'FAKEID_')) {
if (! $this->confirm("Overwrite existing configuration?")) {
return;
}
foreach ($env as $k => $line) {
if (strpos($line, 'FAKEID_') === 0) {
unset($env[$k]);
}
}
}
list($prime, $inverse, $rand) = Energon::generate();
// Append new configuration.
$env[] = "\nFAKEID_PRIME=" . $prime;
$env[] = "\nFAKEID_INVERSE=" . $inverse;
$env[] = "\nFAKEID_RANDOM=" . $rand;
file_put_contents($path, implode('', $env), LOCK_EX);
$this->info("FakeId configured correctly.");
}
}
| <?php
namespace Propaganistas\LaravelFakeId\Commands;
use Illuminate\Console\Command;
use Jenssegers\Optimus\Energon;
class FakeIdSetupCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'fakeid:setup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configures FakeId for use';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
list($prime, $inverse, $rand) = Energon::generate();
// Write in environment file.
$path = base_path('.env');
if (!file_exists($path)) {
$this->error("Environment file (.env) not found. Aborting FakeId setup!");
return;
}
// Remove existing configuration.
$fileArray = file($path);
foreach ($fileArray as $k => $line) {
if (strpos($line, 'FAKEID_') === 0) {
unset($fileArray[$k]);
}
}
// Append new configuration.
$fileArray[] = "\nFAKEID_PRIME=" . $prime;
$fileArray[] = "\nFAKEID_INVERSE=" . $inverse;
$fileArray[] = "\nFAKEID_RANDOM=" . $rand;
file_put_contents($path, implode('', $fileArray), LOCK_EX);
$this->info("FakeId configured correctly.");
}
}
|
Comment out narratives email menu item | Ext.define('SlateAdmin.view.progress.NavPanel', {
extend: 'SlateAdmin.view.LinksNavPanel',
xtype: 'progress-navpanel',
title: 'Student Progress',
data: true,
applyData: function(data) {
if (data !== true) {
return data;
}
return [
{
text: 'Section Interim Reports',
href: '#progress/interims/report',
children: [
{
text: 'Print / Export',
href: '#progress/interims/print'
},
{
text: 'Email',
href: '#progress/interims/email'
}
]
},
{
text: 'Section Term Reports',
href: '#progress/terms/report',
children: [
{
text: 'Search & Print',
href: '#progress/terms/print'
}
// ,{
// text: 'Email',
// href: '#progress/terms/email'
// }
]
}
];
}
}); | Ext.define('SlateAdmin.view.progress.NavPanel', {
extend: 'SlateAdmin.view.LinksNavPanel',
xtype: 'progress-navpanel',
title: 'Student Progress',
data: true,
applyData: function(data) {
if (data !== true) {
return data;
}
return [
{
text: 'Section Interim Reports',
href: '#progress/interims/report',
children: [
{
text: 'Print / Export',
href: '#progress/interims/print'
},
{
text: 'Email',
href: '#progress/interims/email'
}
]
},
{
text: 'Section Term Reports',
href: '#progress/terms/report',
children: [
{
text: 'Search & Print',
href: '#progress/terms/print'
},
{
text: 'Email',
href: '#progress/terms/email'
}
]
}
];
}
}); |
Remove reliance on queryset based geocoding method | from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
| from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
Use in-place operations in ImageNormalize | """
Normalization class for Matplotlib that can be used to produce colorbars.
"""
import numpy as np
from numpy import ma
from matplotlib.colors import Normalize
__all__ = ['ImageNormalize']
class ImageNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, stretch=None, clip=True):
super(ImageNormalize, self).__init__(vmin=vmin, vmax=vmax, clip=clip)
self.vmin = vmin
self.vmax = vmax
self.stretch = stretch
self.inverse_stretch = stretch.inverted()
def __call__(self, values, clip=None):
if clip is None:
clip = self.clip
# Make sure scalars get broadcast to 1-d
if np.isscalar(values):
values = np.atleast_1d(values)
else:
values = values.copy() # copy because of in-place operations after
# Normalize based on vmin and vmax
np.subtract(values, self.vmin, out=values)
np.divide(values, self.vmax - self.vmin, out=values)
# Clip to the 0 to 1 range
if self.clip:
values = np.clip(values, 0., 1., out=values)
# Stretch values
values = self.stretch(values, out=values)
# Convert to masked array for matplotlib
return ma.array(values)
def inverse(self, values):
# Find unstretched values in range 0 to 1
values_norm = self.inverse_stretch(values)
# Scale to original range
return values_norm * (self.vmax - self.vmin) + self.vmin
| """
Normalization class for Matplotlib that can be used to produce colorbars.
"""
import numpy as np
from numpy import ma
from matplotlib.colors import Normalize
__all__ = ['ImageNormalize']
class ImageNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, stretch=None, clip=True):
super(ImageNormalize, self).__init__(vmin=vmin, vmax=vmax, clip=clip)
self.vmin = vmin
self.vmax = vmax
self.stretch = stretch
self.inverse_stretch = stretch.inverted()
def __call__(self, values, clip=None):
if clip is None:
clip = self.clip
# Convert to masked array and make sure scalars get broadcast to 1-d
values = np.atleast_1d(values)
# Normalize based on vmin and vmax
values_norm = (values - self.vmin) / (self.vmax - self.vmin)
# Clip to the 0 to 1 range
if self.clip:
values_norm = np.clip(values_norm, 0., 1.)
# Stretch values
new_values = self.stretch(values_norm)
# Don't assume stretch returned a masked array
return ma.asarray(new_values)
def inverse(self, values):
# Find unstretched values in range 0 to 1
values_norm = self.inverse_stretch(values)
# Scale to original range
return values_norm * (self.vmax - self.vmin) + self.vmin
|
Update dependencies so installation is simpler.
The pull request, and a new release of py-moneyed has occurred. | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_catalog": babel.update_catalog,}
except ImportError:
cmdclass = {}
setup(name="django-money",
version="0.1",
description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.",
url="https://github.com/jakewins/django-money",
packages=["djmoney",
"djmoney.forms",
"djmoney.models"],
install_requires=['setuptools',
'Django >= 1.2',
'py-moneyed > 0.4'],
cmdclass = cmdclass,
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",])
| from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_catalog": babel.update_catalog,}
except ImportError:
cmdclass = {}
setup(name="django-money",
version="0.1",
description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as money implementation, based on python-money django implementation.",
url="https://github.com/jakewins/django-money",
packages=["djmoney",
"djmoney.forms",
"djmoney.models"],
# Commented out, waiting for pull request to be fulfilled: https://github.com/limist/py-moneyed/pull/1
#install_requires=['setuptools',
# 'Django >= 1.2',
# 'py-moneyed > 0.3'],
# package_dir={"": ""},
cmdclass = cmdclass,
classifiers=["Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",])
|
Stop importing clearly duplicate operators (like the First Manchester operator without a name) | """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
return 'GB'
elif region_id in ('SC', 'YO', 'WA', 'LO'):
return region_id[0]
return region_id
@classmethod
def handle_row(cls, row):
"Given a CSV row (a list), returns an Operator object"
if row['Duplicate'] != 'OK':
return None
operator_id = row['NOCCODE'].replace('=', '')
if operator_id == 'TVSR':
return None
if row['OperatorPublicName'] in ('First', 'Arriva', 'Stagecoach') \
or row['OperatorPublicName'].startswith('inc.') \
or row['OperatorPublicName'].startswith('formerly'):
name = row['RefNm']
elif row['OperatorPublicName'] != '':
name = row['OperatorPublicName']
else:
name = row['OpNm']
name = name.replace('\'', u'\u2019') # Fancy apostrophe
operator = Operator.objects.update_or_create(
id=operator_id,
defaults=dict(
name=name.strip(),
vehicle_mode=row['Mode'].lower().replace('ct operator', 'community transport').replace('drt', 'demand responsive transport'),
region_id=cls.get_region_id(row['TLRegOwn']),
)
)
return operator
| """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
return 'GB'
elif region_id in ('SC', 'YO', 'WA', 'LO'):
return region_id[0]
return region_id
@classmethod
def handle_row(cls, row):
"Given a CSV row (a list), returns an Operator object"
operator_id = row['NOCCODE'].replace('=', '')
if operator_id == 'TVSR':
return None
if row['OperatorPublicName'] in ('First', 'Arriva', 'Stagecoach') \
or row['OperatorPublicName'].startswith('inc.') \
or row['OperatorPublicName'].startswith('formerly'):
name = row['RefNm']
elif row['OperatorPublicName'] != '':
name = row['OperatorPublicName']
else:
name = row['OpNm']
name = name.replace('\'', u'\u2019') # Fancy apostrophe
operator = Operator.objects.update_or_create(
id=operator_id,
defaults=dict(
name=name.strip(),
vehicle_mode=row['Mode'].lower().replace('ct operator', 'community transport').replace('drt', 'demand responsive transport'),
region_id=cls.get_region_id(row['TLRegOwn']),
)
)
return operator
|
Add css class to Opt-Out Information link | Kwf.onContentReady(function(body, param) {
if (!param.newRender) return;
// TODO: make default behaviour customizable
if (Kwf.Statistics.getDefaultOptValue() == 'out' && !Kwf.Statistics.issetUserOptValue()) {
var html = '<div class="' + Kwf.Statistics.cssClass + '">';
html += '<div class="inner">';
html += trlKwf('This website uses cookies to help us give you the best experience when you visit our website.');
if (Kwf.Statistics.optUrl) {
html += ' <a href="' + Kwf.Statistics.optUrl + '" class="info">' + trlKwf('More information about the use of cookies') + '</a>';
}
html += '<a href="" class="accept"><span>' + trlKwf('Accept and continue') + '</span></a>';
html += '<div></div>';
Ext.getBody().insertFirst(html);
Ext.query('a.accept', function(link) {
});
}
});
Kwf.onElementReady('.kwcStatisticsOptBox a.accept', function(link) {
link.on('click', function(e, el) {
e.stopEvent();
Kwf.Statistics.setUserOptValue('in');
Kwf.fireComponentEvent('cookieOptChanged', 'in');
});
}, {priority: 10});
Kwf.onComponentEvent('cookieOptChanged', function(value) {
if (Kwf.Statistics.reloadOnOptChanged) {
document.location.reload();
}
});
| Kwf.onContentReady(function(body, param) {
if (!param.newRender) return;
// TODO: make default behaviour customizable
if (Kwf.Statistics.getDefaultOptValue() == 'out' && !Kwf.Statistics.issetUserOptValue()) {
var html = '<div class="' + Kwf.Statistics.cssClass + '">';
html += '<div class="inner">';
html += trlKwf('This website uses cookies to help us give you the best experience when you visit our website.');
if (Kwf.Statistics.optUrl) {
html += ' <a href="' + Kwf.Statistics.optUrl + '">' + trlKwf('More information about the use of cookies') + '</a>';
}
html += '<a href="" class="accept"><span>' + trlKwf('Accept and continue') + '</span></a>';
html += '<div></div>';
Ext.getBody().insertFirst(html);
Ext.query('a.accept', function(link) {
});
}
});
Kwf.onElementReady('.kwcStatisticsOptBox a.accept', function(link) {
link.on('click', function(e, el) {
e.stopEvent();
Kwf.Statistics.setUserOptValue('in');
Kwf.fireComponentEvent('cookieOptChanged', 'in');
});
}, {priority: 10});
Kwf.onComponentEvent('cookieOptChanged', function(value) {
if (Kwf.Statistics.reloadOnOptChanged) {
document.location.reload();
}
});
|
Use global ioloop as we don't pass test ioloop to tornado redis | # -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION
from tornado import ioloop
class InsightApiHTTPTest(AsyncHTTPTestCase):
def get_new_ioloop(self):
return ioloop.IOLoop.instance()
def get_app(self):
return application
def test_api_version(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
body_json = json.loads(response.body)
self.assertIn('version', body_json)
self.assertIn('insight_reloaded', body_json)
self.assertEqual('insight-reloaded', body_json['name'])
self.assertEqual(VERSION, body_json['version'])
def test_api_request(self):
self.http_client.fetch(self.get_url('/') +
u'?url=http://my_file_url.com/file.pdf',
self.stop)
response = self.wait()
json_body = json.loads(response.body)
self.assertIn('insight_reloaded', json_body)
self.assertEqual(json_body['number_in_queue'], 1)
def test_api_url_missing(self):
self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop)
response = self.wait()
self.assertEqual(response.code, 404)
| # -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION
class InsightApiHTTPTest(AsyncHTTPTestCase):
def get_app(self):
return application
def test_api_version(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
body_json = json.loads(response.body)
self.assertIn('version', body_json)
self.assertIn('insight_reloaded', body_json)
self.assertEqual('insight-reloaded', body_json['name'])
self.assertEqual(VERSION, body_json['version'])
def test_api_request(self):
self.http_client.fetch(self.get_url('/') +
u'?url=http://my_file_url.com/file.pdf',
self.stop)
response = self.wait()
json_body = json.loads(response.body)
self.assertIn('insight_reloaded', json_body)
self.assertEqual(json_body['number_in_queue'], 1)
def test_api_url_missing(self):
self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop)
response = self.wait()
self.assertEqual(response.code, 404)
|
Change the log level to debug for File transports | import os from 'os';
const settings = {
backend: {
enable: true,
host: 'localhost',
port: 80,
route: 'api/'
},
livereload: {
enable: false
},
cluster: {
// note. node-inspector cannot debug child (forked) process
enable: false,
maxWorkers: os.cpus().length || 1
},
//sessionSecret: 'SessionSecretForDevelopment',
winston: {
prefix: '',
transports: {
Console: {
level: 'debug',
silent: false,
colorize: true,
timestamp: true, // or function()
json: false,
handleExceptions: true
},
File: {
level: 'info',
silent: false,
colorize: false,
timestamp: true, // or function()
filename: 'log/app%s.log',
maxsize: 104857600,
maxFiles: 10,
json: true,
handleExceptions: true
}
},
exceptionHandlers: {
File: {
timestamp: true, // or function()
filename: 'log/error%s.log',
maxsize: 104857600,
maxFiles: 10,
json: true
}
}
}
};
export default settings;
| import os from 'os';
const settings = {
backend: {
enable: true,
host: 'localhost',
port: 80,
route: 'api/'
},
livereload: {
enable: false
},
cluster: {
// note. node-inspector cannot debug child (forked) process
enable: false,
maxWorkers: os.cpus().length || 1
},
//sessionSecret: 'SessionSecretForDevelopment',
winston: {
prefix: '',
transports: {
Console: {
level: 'debug',
silent: false,
colorize: true,
timestamp: true, // or function()
json: false,
handleExceptions: true
},
File: {
level: 'debug',
silent: false,
colorize: false,
timestamp: true, // or function()
filename: 'log/app%s.log',
maxsize: 104857600,
maxFiles: 10,
json: true,
handleExceptions: true
}
},
exceptionHandlers: {
File: {
timestamp: true, // or function()
filename: 'log/error%s.log',
maxsize: 104857600,
maxFiles: 10,
json: true
}
}
}
};
export default settings;
|
Remove fields, users can just use filters | <?php
namespace App\Nova\Actions;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Actions\Action;
use Illuminate\Support\Collection;
use Laravel\Nova\Fields\ActionFields;
class ExportAttendance extends Action
{
/**
* The displayable name of the action.
*
* @var string
*/
public $name = 'Export for CoC';
/**
* Indicates if this action is available to run against the entire resource.
*
* @var bool
*/
public $availableForEntireResource = true;
public function __construct()
{
/*
$this->withFilename('RoboJacketsAttendance.csv')
->withWriterType(\Maatwebsite\Excel\Excel::CSV)
->withChunkCount(10000)
->only('gtid');
*/
}
/**
* Perform the action on the given models.
*
* @param \Laravel\Nova\Fields\ActionFields $fields
* @param \Illuminate\Support\Collection $models
* @return mixed
*/
public function handle(ActionFields $fields, Collection $models)
{
\Log::debug('fdsa'.$fields->start_date.'.'.$fields->end_date);
\Log::debug($fields);
return Action::message('Test!');
}
/**
* Get the fields available on the action.
*
* @return array
*/
public function fields()
{
return [];
}
}
| <?php
namespace App\Nova\Actions;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Actions\Action;
use Illuminate\Support\Collection;
use Laravel\Nova\Fields\ActionFields;
class ExportAttendance extends Action
{
/**
* The displayable name of the action.
*
* @var string
*/
public $name = 'Export for CoC';
/**
* Indicates if this action is available to run against the entire resource.
*
* @var bool
*/
public $availableForEntireResource = true;
public function __construct()
{
/*
$this->withFilename('RoboJacketsAttendance.csv')
->withWriterType(\Maatwebsite\Excel\Excel::CSV)
->withChunkCount(10000)
->only('gtid');
*/
}
/**
* Perform the action on the given models.
*
* @param \Laravel\Nova\Fields\ActionFields $fields
* @param \Illuminate\Support\Collection $models
* @return mixed
*/
public function handle(ActionFields $fields, Collection $models)
{
\Log::debug('fdsa'.$fields->start_date.'.'.$fields->end_date);
\Log::debug($fields);
return Action::message('Test!');
}
/**
* Get the fields available on the action.
*
* @return array
*/
public function fields()
{
return [
Date::make('Start Date')
->format('MM/DD/YYYY')
->help('Leave blank for two weeks ago'),
Date::make('End Date')
->format('MM/DD/YYYY')
->help('Leave blank for today'),
];
}
}
|
Use facade instead of alias | <?php
/*
* This file is part of the EmailChecker package.
*
* (c) Matthieu Moquet <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EmailChecker\Laravel;
use EmailChecker\EmailChecker;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
/**
* Laravel service provider.
*
* @author Oliver Green <[email protected]>
*/
class EmailCheckerServiceProvider extends ServiceProvider
{
/**
* Register the factory in the application container.
*/
public function register()
{
/*
* Register the e-mail checker
*/
$this->app->singleton(EmailChecker::class, function ($app) {
return new EmailChecker();
});
/*
* Alias the dependency for ease.
*/
$this->app->alias(EmailChecker::class, 'email.checker');
}
/**
* Bootstrap any application services.
*/
public function boot(EmailChecker $checker)
{
/*
* Add a custom validator filter.
*/
$check = function ($attr, $value, $param, $validator) use ($checker) {
return $checker->isValid($value);
};
Validator::extend(
'not_throw_away', $check, 'The :attribute domain is invalid.'
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['email.checker', EmailChecker::class];
}
}
| <?php
/*
* This file is part of the EmailChecker package.
*
* (c) Matthieu Moquet <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EmailChecker\Laravel;
use EmailChecker\EmailChecker;
use Illuminate\Support\ServiceProvider;
use Validator;
/**
* Laravel service provider.
*
* @author Oliver Green <[email protected]>
*/
class EmailCheckerServiceProvider extends ServiceProvider
{
/**
* Register the factory in the application container.
*/
public function register()
{
/*
* Register the e-mail checker
*/
$this->app->singleton(EmailChecker::class, function ($app) {
return new EmailChecker();
});
/*
* Alias the dependency for ease.
*/
$this->app->alias(EmailChecker::class, 'email.checker');
}
/**
* Bootstrap any application services.
*/
public function boot(EmailChecker $checker)
{
/*
* Add a custom validator filter.
*/
$check = function ($attr, $value, $param, $validator) use ($checker) {
return $checker->isValid($value);
};
Validator::extend(
'not_throw_away', $check, 'The :attribute domain is invalid.'
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['email.checker', EmailChecker::class];
}
}
|
Remove last bits of file browser stuff | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url('', include('uqam.cat.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^dashboard/', include('uqam.dashboard.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^collection/', include('uqamcollections.urls')),
(r'^search/', include('haystack.urls')),
url(r'^accounts/login/$',
'django.contrib.auth.views.login',
name='auth_login'),
url(r'^accounts/logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', 'redirect_field_name': 'next'},
name='auth_logout'),
url(r'^report/', include('reports.urls')),
url(r'^', include('common.urls')),
url(r'^place/', include('location.urls')),
url(r'^mediaman/', include('mediaman.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from filebrowser.sites import site
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url('', include('uqam.cat.urls')),
url(r'^admin/filebrowser/', include(site.urls)),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^dashboard/', include('uqam.dashboard.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^collection/', include('uqamcollections.urls')),
(r'^search/', include('haystack.urls')),
url(r'^accounts/login/$',
'django.contrib.auth.views.login',
name='auth_login'),
url(r'^accounts/logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', 'redirect_field_name': 'next'},
name='auth_logout'),
url(r'^report/', include('reports.urls')),
url(r'^', include('common.urls')),
url(r'^place/', include('location.urls')),
url(r'^mediaman/', include('mediaman.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
|
Add .ico to the allowed extension list. | #!/usr/bin/python
# -*-coding: utf8 -*-
from BaseHTTPServer import BaseHTTPRequestHandler
import mimetypes
from os import curdir, sep
import os
class HttpServerHandler(BaseHTTPRequestHandler):
allowed_extensions = ['.html', '.jpg', '.gif', '.ico', '.js', '.css', '.tff', '.woff']
def has_permission_to_reply(self, file_path):
file_name, file_extension = os.path.splitext(file_path)
send_reply = file_extension in self.allowed_extensions
mimetype = mimetypes.guess_type(file_name + file_extension)
return mimetype, send_reply
def do_GET(self):
file_path = self.path
if file_path == "/":
file_path = "/index.html"
try:
mimetype, send_reply = self.has_permission_to_reply(file_path)
if send_reply:
full_path = curdir + sep + "pages" + sep + file_path
f = open(full_path)
self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404, 'File Not Found: %s' % file_path) | #!/usr/bin/python
# -*-coding: utf8 -*-
from BaseHTTPServer import BaseHTTPRequestHandler
import mimetypes
from os import curdir, sep
import os
class HttpServerHandler(BaseHTTPRequestHandler):
allowed_extensions = ['.html', '.jpg', '.gif', '.js', '.css', '.tff', '.woff']
def has_permission_to_reply(self, file_path):
file_name, file_extension = os.path.splitext(file_path)
send_reply = file_extension in self.allowed_extensions
mimetype = mimetypes.guess_type(file_name + file_extension)
return mimetype, send_reply
def do_GET(self):
file_path = self.path
if file_path == "/":
file_path = "/index.html"
try:
mimetype, send_reply = self.has_permission_to_reply(file_path)
if True:
full_path = curdir + sep + "pages" + sep + file_path
f = open(full_path)
self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404, 'File Not Found: %s' % file_path) |
[IMP] Rename state of SO according to LO and Cost Estimate | # -*- coding: utf-8 -*-
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
'state': fields.selection([
('draft', 'Draft Cost Estimate'),
('sent', 'Cost Estimate Sent'),
('cancel', 'Cancelled'),
('waiting_date', 'Waiting Schedule'),
('progress', 'Logistic Order'),
('manual', 'Logistic Order to Invoice'),
('invoice_except', 'Invoice Exception'),
('done', 'Done'),
], 'Status', readonly=True, track_visibility='onchange',
help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True),
}
| # -*- coding: utf-8 -*-
from openerp.osv import orm, fields
class sale_order(orm.Model):
_inherit = 'sale.order'
_columns = {
# override only to change the 'string' argument
# from 'Customer' to 'Requesting Entity'
'partner_id': fields.many2one(
'res.partner',
'Requesting Entity',
readonly=True,
states={'draft': [('readonly', False)],
'sent': [('readonly', False)]},
required=True,
change_default=True,
select=True,
track_visibility='always'),
'consignee_id': fields.many2one(
'res.partner',
string='Consignee',
required=True),
'incoterm_address': fields.char(
'Incoterm Place',
help="Incoterm Place of Delivery. "
"International Commercial Terms are a series of "
"predefined commercial terms used in "
"international transactions."),
'requested_by': fields.text('Requested By'),
}
|
Update default pushTo option of grunt-bump | /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
globals: {}
},
gruntfile: {
src: 'Gruntfile.js'
},
lib_test: {
src: ['lib/**/*.js', 'test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib_test: {
files: '<%= jshint.lib_test.src %>',
tasks: ['jshint:lib_test', 'nodeunit']
}
},
bump: {
options: {
pushTo: '<%=pkg.repository.url%>'
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-bump');
// Default task.
grunt.registerTask('default', ['jshint']);
};
| /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Task configuration.
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
globals: {}
},
gruntfile: {
src: 'Gruntfile.js'
},
lib_test: {
src: ['lib/**/*.js', 'test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib_test: {
files: '<%= jshint.lib_test.src %>',
tasks: ['jshint:lib_test', 'nodeunit']
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-bump');
// Default task.
grunt.registerTask('default', ['jshint']);
};
|
Fix java client to accept new parameters | package io.aigar.game.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public class GameState {
private int id;
private int tick;
private boolean paused;
private boolean disabledLeaderboard;
private int multiplier;
private float timeLeft;
private List<Player> players;
private Resources resources;
private Size map;
private List<Virus> viruses;
@JsonIgnore
private Player me;
@JsonIgnore
private List<Player> enemies;
public int getId() {
return id;
}
public int getTick() {
return tick;
}
public boolean isPaused() {
return paused;
}
public boolean isDisabledLeaderboard() { return disabledLeaderboard; }
public int getMultiplier() {
return multiplier;
}
public float getTimeLeft() {
return timeLeft;
}
public List<Player> getPlayers() {
return players;
}
public Resources getResources() {
return resources;
}
public Size getMap() {
return map;
}
public List<Virus> getViruses() {
return viruses;
}
public Player getMe() {
return me;
}
public void setMe(Player me) {
this.me = me;
}
public List<Player> getEnemies() {
return enemies;
}
public void setEnemies(List<Player> enemies) {
this.enemies = enemies;
}
}
| package io.aigar.game.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public class GameState {
private int id;
private int tick;
private boolean paused;
private int multiplier;
private float timeLeft;
private List<Player> players;
private Resources resources;
private Size map;
private List<Virus> viruses;
@JsonIgnore
private Player me;
@JsonIgnore
private List<Player> enemies;
public int getId() {
return id;
}
public int getTick() {
return tick;
}
public boolean isPaused() {
return paused;
}
public int getMultiplier() {
return multiplier;
}
public float getTimeLeft() {
return timeLeft;
}
public List<Player> getPlayers() {
return players;
}
public Resources getResources() {
return resources;
}
public Size getMap() {
return map;
}
public List<Virus> getViruses() {
return viruses;
}
public Player getMe() {
return me;
}
public void setMe(Player me) {
this.me = me;
}
public List<Player> getEnemies() {
return enemies;
}
public void setEnemies(List<Player> enemies) {
this.enemies = enemies;
}
}
|
Adjust to match modern style conventions. | # This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def initialize_options(self):
_bdist_rpm.initialize_options(self)
self.no_egg = None
def run(self):
# ensure distro name is up-to-date
self.run_command('egg_info')
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version ' + version
line24 = '%define version ' + rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23, line24)
for line in spec
]
insert_loc = spec.index(line24) + 1
unmangled_version = "%define unmangled_version " + version
spec.insert(insert_loc, unmangled_version)
return spec
| # This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs.
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
class bdist_rpm(_bdist_rpm):
def initialize_options(self):
_bdist_rpm.initialize_options(self)
self.no_egg = None
def run(self):
self.run_command('egg_info') # ensure distro name is up-to-date
_bdist_rpm.run(self)
def _make_spec_file(self):
version = self.distribution.get_version()
rpmversion = version.replace('-','_')
spec = _bdist_rpm._make_spec_file(self)
line23 = '%define version '+version
line24 = '%define version '+rpmversion
spec = [
line.replace(
"Source0: %{name}-%{version}.tar",
"Source0: %{name}-%{unmangled_version}.tar"
).replace(
"setup.py install ",
"setup.py install --single-version-externally-managed "
).replace(
"%setup",
"%setup -n %{name}-%{unmangled_version}"
).replace(line23,line24)
for line in spec
]
spec.insert(spec.index(line24)+1, "%define unmangled_version "+version)
return spec
|
:new: Set websocket retry interval to 5 seconds | 'use babel'
import {CompositeDisposable, Emitter} from 'atom'
import {readFile} from './helpers'
import WebSocket from 'reconnectingwebsocket'
export default class Connection {
constructor(projectPath, manifest) {
this.subscriptions = new CompositeDisposable()
this.emitter = new Emitter()
this.projectPath = projectPath
this.socket = new WebSocket(`ws://localhost:${manifest.wport}`, null, {reconnectInterval: 5 * 1000})
this.subscriptions.add(this.emitter)
this.socket.addEventListener('message', e => {
const message = JSON.parse(e.data)
this.emitter.emit(`on-message:${message._type}`, message)
})
}
getPath() {
return this.projectPath
}
send(type, message) {
this.socket.send(JSON.stringify(Object.assign({}, {_type: type}, message)))
}
onMessage(type, callback) {
return this.emitter.on(`on-message:${type}`, callback)
}
onDidDestroy(callback) {
return this.emitter.on('did-destroy', callback)
}
destroy() {
this.emitter.emit('did-destroy')
this.dispose()
}
dispose() {
this.socket.close()
this.subscriptions.dispose()
}
static create(projectPath, configPath) {
return readFile(configPath).then(function(contents) {
try {
const parsed = JSON.parse(contents)
return new Connection(projectPath, parsed)
} catch (_) {
throw new Error(`Malformed state file found in ${projectPath}`)
}
})
}
}
| 'use babel'
import {CompositeDisposable, Emitter} from 'atom'
import {readFile} from './helpers'
import WebSocket from 'reconnectingwebsocket'
export default class Connection {
constructor(projectPath, manifest) {
this.subscriptions = new CompositeDisposable()
this.emitter = new Emitter()
this.projectPath = projectPath
this.socket = new WebSocket(`ws://localhost:${manifest.wport}`)
this.subscriptions.add(this.emitter)
this.socket.addEventListener('message', e => {
const message = JSON.parse(e.data)
this.emitter.emit(`on-message:${message._type}`, message)
})
}
getPath() {
return this.projectPath
}
send(type, message) {
this.socket.send(JSON.stringify(Object.assign({}, {_type: type}, message)))
}
onMessage(type, callback) {
return this.emitter.on(`on-message:${type}`, callback)
}
onDidDestroy(callback) {
return this.emitter.on('did-destroy', callback)
}
destroy() {
this.emitter.emit('did-destroy')
this.dispose()
}
dispose() {
this.socket.close()
this.subscriptions.dispose()
}
static create(projectPath, configPath) {
return readFile(configPath).then(function(contents) {
try {
const parsed = JSON.parse(contents)
return new Connection(projectPath, parsed)
} catch (_) {
throw new Error(`Malformed state file found in ${projectPath}`)
}
})
}
}
|
Fix debug plugin to simulate notifications more reliably | enabled(){
this.isDebugging = false;
this.onKeyDown = (e) => {
// ==========================
// F4 key - toggle debug mode
// ==========================
if (e.keyCode === 115){
this.isDebugging = !this.isDebugging;
$(".app-title").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33");
}
// Debug mode handling
else if (this.isDebugging){
e.preventDefault();
// ===================================
// N key - simulate popup notification
// S key - simulate sound notification
// ===================================
if (e.keyCode === 78 || e.keyCode === 83){
var col = TD.controller.columnManager.getAllOrdered()[0];
var prevPopup = col.model.getHasNotification();
var prevSound = col.model.getHasSound();
col.model.setHasNotification(e.keyCode === 78);
col.model.setHasSound(e.keyCode === 83);
$.publish("/notifications/new",[{
column: col,
items: [
col.updateArray[Math.floor(Math.random()*col.updateArray.length)]
]
}]);
setTimeout(function(){
col.model.setHasNotification(prevPopup);
col.model.setHasSound(prevSound);
}, 1);
}
}
};
}
ready(){
$(document).on("keydown", this.onKeyDown);
}
disabled(){
$(document).off("keydown", this.onKeyDown);
}
| enabled(){
this.isDebugging = false;
this.onKeyDown = (e) => {
// ==========================
// F4 key - toggle debug mode
// ==========================
if (e.keyCode === 115){
this.isDebugging = !this.isDebugging;
$(".app-title").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33");
}
// Debug mode handling
else if (this.isDebugging){
e.preventDefault();
// ===================================
// N key - simulate popup notification
// ===================================
if (e.keyCode === 78){
var col = TD.controller.columnManager.getAllOrdered()[0];
$.publish("/notifications/new",[{
column: col,
items: [
col.updateArray[Math.floor(Math.random()*col.updateArray.length)]
]
}]);
}
// ===================================
// S key - simulate sound notification
// ===================================
else if (e.keyCode === 83){
if ($TDX.hasCustomNotificationSound){
$TD.onTweetSound();
}
else{
document.getElementById("update-sound").play();
}
}
}
};
}
ready(){
$(document).on("keydown", this.onKeyDown);
}
disabled(){
$(document).off("keydown", this.onKeyDown);
}
|
Use ceil() instead of floor() for midpoint calculation
This allows us to drop the if (start === length) kludge, while ensuring that
text.slice(0, end) is tested, fixing an off-by-one error that occurs when the
loop ends with (end - start) == 1. | (function($) {
$.fn.ellipsis = function(options) {
// デフォルトオプション
var defaults = {
'row' : 1, // 省略行数
'char' : '...' // 省略文字
};
options = $.extend(defaults, options);
this.each(function() {
// 現在のテキストを取得
var $this = $(this);
var text = $this.text();
var origHeight = $this.height();
// 1行分の高さを取得
$this.text('a');
var rowHeight = $this.height();
var targetHeight = rowHeight * options.row;
if (origHeight <= targetHeight) {
$this.text(text);
return;
}
// Binary search for max length
var start = 1;
var end = text.length;
while (start < end) {
var length = Math.ceil((start + end) / 2);
$this.text(text.slice(0, length) + options['char']);
if ($this.height () <= targetHeight) {
start = length;
} else {
end = length - 1;
}
}
$this.text(text.slice(0, start) + options['char']);
});
return this;
};
}) (jQuery);
| (function($) {
$.fn.ellipsis = function(options) {
// デフォルトオプション
var defaults = {
'row' : 1, // 省略行数
'char' : '...' // 省略文字
};
options = $.extend(defaults, options);
this.each(function() {
// 現在のテキストを取得
var $this = $(this);
var text = $this.text();
var origHeight = $this.height();
// 1行分の高さを取得
$this.text('a');
var rowHeight = $this.height();
var targetHeight = rowHeight * options.row;
if (origHeight <= targetHeight) {
$this.text(text);
return;
}
// Binary search for max length
var start = 1;
var end = text.length;
while (start < end) {
var length = Math.floor((start + end) / 2);
if (start === length) {
break;
}
$this.text(text.slice(0, length) + options['char']);
if ($this.height () <= targetHeight) {
start = length;
} else {
end = length - 1;
}
}
$this.text(text.slice(0, start) + options['char']);
});
return this;
};
}) (jQuery);
|
Add Link in front page | import React from 'react'
import { Link } from 'react-router-dom'
import 'isomorphic-fetch';
class FrontPage extends React.Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
fetch('https://199911.github.io/blog-data/front-page.json')
.then((res) => (res.json()))
.then((posts) => {
this.setState({
posts
});
})
}
render() {
const { posts } = this.state;
if (posts) {
return (
<div>
{
posts.map((post) => {
return (
<Link key={ post.slug } style={{ display: 'block', height: '300px', overflow: 'hidden' }} to={ post.slug }>
<h1>
{post.title}
</h1>
<div dangerouslySetInnerHTML={{ __html: post.__content }}>
</div>
<pre>
{ JSON.stringify(post, null, 4) }
</pre>
</Link>
);
})
}
</div>
)
} else {
return <div>Loading</div>;
}
}
}
export default FrontPage
| import React from 'react'
import 'isomorphic-fetch';
class HelloMessage extends React.Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
fetch('https://199911.github.io/blog-data/front-page.json')
.then((res) => (res.json()))
.then((posts) => {
this.setState({
posts
});
})
}
render() {
const { posts } = this.state;
if (posts) {
return (
<div>
{
posts.map((post) => {
return (
<div style={{ height: '300px', overflow: 'hidden' }}>
<h1>
{post.title}
</h1>
<div dangerouslySetInnerHTML={{ __html: post.__content }}>
</div>
<pre>
{ JSON.stringify(post, null, 4) }
</pre>
</div>
);
})
}
</div>
)
} else {
return <div>Loading</div>;
}
}
}
export default HelloMessage
|
Add emptyBookmark and fix bugs in history module | define(['summernote/core/range'], function (range) {
/**
* History
* @class
*/
var History = function () {
var stack = [], stackOffset = 0;
var makeSnapshot = function ($editable) {
var editable = $editable[0];
var rng = range.create();
var emptyBookmark = {s: {path: [0], offset: 0}, e: {path: [0], offset: 0}};
return {
contents: $editable.html(),
bookmark: (rng ? rng.bookmark(editable) : emptyBookmark)
};
};
var applySnapshot = function ($editable, snapshot) {
if (snapshot.contents !== null) {
$editable.html(snapshot.contents);
}
if (snapshot.bookmark !== null) {
range.createFromBookmark($editable[0], snapshot.bookmark).select();
}
};
this.undo = function ($editable) {
if (0 < stackOffset) {
stackOffset--;
applySnapshot($editable, stack[stackOffset]);
}
};
this.redo = function ($editable) {
if (stack.length - 1 > stackOffset) {
stackOffset++;
applySnapshot($editable, stack[stackOffset]);
}
};
this.recordUndo = function ($editable) {
// Wash out stack after stackOffset
if (stack.length > stackOffset) {
stack = stack.slice(0, stackOffset);
}
// Create new snapshot and push it to the end
stack.push(makeSnapshot($editable));
stackOffset++;
};
};
return History;
});
| define(['summernote/core/range'], function (range) {
/**
* History
* @class
*/
var History = function () {
var stack = [], stackOffset = 0;
var makeSnapshot = function ($editable) {
var editable = $editable[0];
var rng = range.create();
return {
contents: $editable.html(),
bookmark: (rng ? rng.bookmark(editable) : null)
};
};
var applySnapshot = function ($editable, snapshot) {
$editable.html(snapshot.contents);
// FIXME: Still buggy, use marker tag
// range.createFromBookmark($editable[0], snapshot.bookmark).select();
};
this.undo = function ($editable) {
if (0 < stackOffset) {
stackOffset--;
applySnapshot($editable, stack[stackOffset]);
}
};
this.redo = function ($editable) {
if (stack.length > stackOffset) {
applySnapshot($editable, stack[stackOffset]);
stackOffset++;
}
};
this.recordUndo = function ($editable) {
// Wash out stack after stackOffset
if (stack.length > stackOffset) {
stack = stack.slice(0, stackOffset);
}
// Create new snapshot and push it to the end
stack.push(makeSnapshot($editable));
stackOffset++;
};
};
return History;
});
|
Add debug print of data | from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceRepository()
def main(event, context):
method = event['method']
if 'data' in event:
data = event['data']
else:
data = None
print(data)
if method == 'submitJob':
return submitJob(data, context)
elif method == 'getJob':
return getJob(data, context)
elif method == 'listDatasources':
return listDatasources(data, context)
elif method == 'getDatasource':
return getDatasource(data, context)
else:
return None
def submitJob(event, context):
# Put initial entry in dynamo db
jobId = jobRepo.createJob(event)
# Put the job ID on the SQS queue
response = queue.send_message(MessageBody=jobId)
# Update the DB entry with sqs message ID for traceability
return jobRepo.updateWithMessageId(jobId, response.get('MessageId'))
def getJob(event, context):
return jobRepo.getJob(event['jobId'])
def listDatasources(event, context):
return dsRepo.listDatasources()
def getDatasource(event, context):
return dsRepo.getDatasource(event['datasourceId'])
| from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceRepository()
def main(event, context):
method = event['method']
if 'data' in event:
data = event['data']
else:
data = None
if method == 'submitJob':
return submitJob(data, context)
elif method == 'getJob':
return getJob(data, context)
elif method == 'listDatasources':
return listDatasources(data, context)
elif method == 'getDatasource':
return getDatasource(data, context)
else:
return None
def submitJob(event, context):
# Put initial entry in dynamo db
jobId = jobRepo.createJob(event)
# Put the job ID on the SQS queue
response = queue.send_message(MessageBody=jobId)
# Update the DB entry with sqs message ID for traceability
return jobRepo.updateWithMessageId(jobId, response.get('MessageId'))
def getJob(event, context):
return jobRepo.getJob(event['jobId'])
def listDatasources(event, context):
return dsRepo.listDatasources()
def getDatasource(event, context):
return dsRepo.getDatasource(event['datasourceId'])
|
Disable fuzzy output in po2json for disco | /*
* This is the default (production) config for the discovery pane app.
*/
const amoCDN = 'https://addons.cdn.mozilla.net';
const staticHost = 'https://addons-discovery.cdn.mozilla.net';
module.exports = {
// The keys listed here will be exposed on the client.
// Since by definition client-side code is public these config keys
// must not contain sensitive data.
clientConfigKeys: [
'appName',
'amoCDN',
'apiHost',
'apiPath',
'cookieName',
'cookieMaxAge',
'cookieSecure',
'enableClientConsole',
'defaultLang',
'isDeployed',
'isDevelopment',
'langs',
'langMap',
'rtlLangs',
'trackingEnabled',
'trackingId',
'useUiTour',
],
staticHost,
CSP: {
directives: {
// Script is limited to the discovery specific CDN.
scriptSrc: [
staticHost,
'https://www.google-analytics.com/analytics.js',
],
styleSrc: [staticHost],
imgSrc: [
"'self'",
'data:',
amoCDN,
staticHost,
'https://www.google-analytics.com',
],
mediaSrc: [staticHost],
},
},
trackingEnabled: true,
trackingId: 'UA-36116321-7',
enablePostCssLoader: false,
// If this is false we'll use an in-page
// stand-in for the ui-tour.
useUiTour: false,
po2jsonFuzzyOutput: false,
};
| /*
* This is the default (production) config for the discovery pane app.
*/
const amoCDN = 'https://addons.cdn.mozilla.net';
const staticHost = 'https://addons-discovery.cdn.mozilla.net';
module.exports = {
// The keys listed here will be exposed on the client.
// Since by definition client-side code is public these config keys
// must not contain sensitive data.
clientConfigKeys: [
'appName',
'amoCDN',
'apiHost',
'apiPath',
'cookieName',
'cookieMaxAge',
'cookieSecure',
'enableClientConsole',
'defaultLang',
'isDeployed',
'isDevelopment',
'langs',
'langMap',
'rtlLangs',
'trackingEnabled',
'trackingId',
'useUiTour',
],
staticHost,
CSP: {
directives: {
// Script is limited to the discovery specific CDN.
scriptSrc: [
staticHost,
'https://www.google-analytics.com/analytics.js',
],
styleSrc: [staticHost],
imgSrc: [
"'self'",
'data:',
amoCDN,
staticHost,
'https://www.google-analytics.com',
],
mediaSrc: [staticHost],
},
},
trackingEnabled: true,
trackingId: 'UA-36116321-7',
enablePostCssLoader: false,
// If this is false we'll use an in-page
// stand-in for the ui-tour.
useUiTour: false,
po2jsonFuzzyOutput: true,
};
|
Fix | Adicionando status code na validação do token | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.add(req, res);
}
}
delete(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.delete(req, res);
}
}
get(req, res) {
this._orm.get(req, res);
}
getById(req, res) {
this._orm.getById(req, res);
}
update(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.update(req, res);
}
}
}
module.exports = OrmProxy; | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.send(response);
} else {
this._orm.add(req, res);
}
}
delete(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.send(response);
} else {
this._orm.delete(req, res);
}
}
get(req, res) {
this._orm.get(req, res);
}
getById(req, res) {
this._orm.getById(req, res);
}
update(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.send(response);
} else {
this._orm.update(req, res);
}
}
}
module.exports = OrmProxy; |
Allow cursorColor override in config
The default cursorColor for this theme is quite low-contrast (especially when opting for `cursorShape: 'UNDERLINE'|'BEAM'`). I think allowing the user to specify their preferred cursor color would be ideal. | exports.decorateConfig = (config) => {
return Object.assign({}, config, {
foregroundColor: '#ECEFF1',
backgroundColor: '#263238',
borderColor: '#222d32',
cursorColor: config.cursorColor || 'rgba(0, 150, 136, .5)',
colors: {
black: '#263238',
red: '#FF5252',
green: '#9CCC65',
yellow: '#fee94e',
blue: '#2b98f0',
magenta: '#b38bfc',
cyan: '#68b6f3',
white: '#ECEFF1',
lightBlack: '#617d8a',
lightRed: '#fc625d',
lightGreen: '#9CCC65',
lightYellow: '#fee94e',
lightBlue: '#2b98f0',
lightMagenta: '#b38bfc',
lightCyan: '#68b6f3',
lightWhite: '#ffffff'
},
css: `
${config.css || ''}
.hyper_main {
border: none !important;
}
.header_header {
background: #222d32 !important;
}
.tab_tab {
border: 0;
}
.tab_textActive {
border-bottom: 2px solid #009688;
}
.splitpane_divider {
background-color: rgba(170, 187, 195, 0.16) !important;
}
`
})
}
| exports.decorateConfig = (config) => {
return Object.assign({}, config, {
foregroundColor: '#ECEFF1',
backgroundColor: '#263238',
borderColor: '#222d32',
cursorColor: 'rgba(0, 150, 136, .5)',
colors: {
black: '#263238',
red: '#FF5252',
green: '#9CCC65',
yellow: '#fee94e',
blue: '#2b98f0',
magenta: '#b38bfc',
cyan: '#68b6f3',
white: '#ECEFF1',
lightBlack: '#617d8a',
lightRed: '#fc625d',
lightGreen: '#9CCC65',
lightYellow: '#fee94e',
lightBlue: '#2b98f0',
lightMagenta: '#b38bfc',
lightCyan: '#68b6f3',
lightWhite: '#ffffff'
},
css: `
${config.css || ''}
.hyper_main {
border: none !important;
}
.header_header {
background: #222d32 !important;
}
.tab_tab {
border: 0;
}
.tab_textActive {
border-bottom: 2px solid #009688;
}
.splitpane_divider {
background-color: rgba(170, 187, 195, 0.16) !important;
}
`
})
}
|
TEST: Update test that relies on fragile string comparison
It is a string comparison of formulae. The new output differs from the
reference in terms of whitespace and redundant parens. | import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('tulip.ltl_parser_log').setLevel(logging.ERROR)
from nose.tools import raises
#from tulip.spec.parser import parse
from tulip import spec
from tulip.spec import translation as ts
from tulip.spec import form
def test_translate_ast_to_gr1c():
x = '(loc = "s2") -> X((((env_alice = "left") && (env_bob = "bright"))))'
s = spec.GRSpec(sys_vars={'loc': ['s0', 's2'],
'env_alice': ['left', 'right'],
'env_bob': ['bleft', 'bright']},
sys_safety=[x])
s.str_to_int()
sint = s._bool_int[x]
print(repr(sint))
rint = s.ast(sint)
print(repr(rint))
r = ts.translate_ast(rint, 'gr1c')
print(repr(r))
print(r.flatten())
assert r.flatten() == ("( ( loc = 1 ) -> "
"( ( env_alice' = 0 ) & ( env_bob' = 1 ) ) )")
@raises(TypeError)
def check_translate_unrecognized_types(spc):
ts.translate(spc, 'gr1c')
def test_translate_unrecognized_types():
for spc in [form.LTL(), 'a -> b']:
yield check_translate_unrecognized_types, spc
| import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('tulip.ltl_parser_log').setLevel(logging.ERROR)
from nose.tools import raises
#from tulip.spec.parser import parse
from tulip import spec
from tulip.spec import translation as ts
from tulip.spec import form
def test_translate_ast_to_gr1c():
x = '(loc = "s2") -> X((((env_alice = "left") && (env_bob = "bright"))))'
s = spec.GRSpec(sys_vars={'loc': ['s0', 's2'],
'env_alice': ['left', 'right'],
'env_bob': ['bleft', 'bright']},
sys_safety=[x])
s.str_to_int()
sint = s._bool_int[x]
print(repr(sint))
rint = s.ast(sint)
print(repr(rint))
r = ts.translate_ast(rint, 'gr1c')
print(repr(r))
print(r.flatten())
assert r.flatten() == ("( ( loc = 1 ) -> "
"( ( ( env_alice' = 0 ) & ( env_bob' = 1 ) ) ) )")
@raises(TypeError)
def check_translate_unrecognized_types(spc):
ts.translate(spc, 'gr1c')
def test_translate_unrecognized_types():
for spc in [form.LTL(), 'a -> b']:
yield check_translate_unrecognized_types, spc
|
Allow enabling OR disabling resource blocking when calling fetchPageContent | /* eslint no-console: 0 */
'use strict';
const phantom = require('phantom');
function* blockResourceLoading(page) {
yield page.property('onResourceRequested', function(requestData, request) {
var BLOCKED_RESOURCES = [
/\.gif/gi,
/\.png/gi,
/\.css/gi,
/^((?!(feuseradmin\.js|tinymce|jquery-)).)*\.js.*/gi
];
var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) {
return r.test(requestData['url']);
});
if (is_blacklisted_resource) {
request.abort();
}
});
}
function* fetchPageContent(url, instance, block_assets=true) {
let is_local_instance = false;
if (!instance) {
instance = yield * initPhantomInstance();
is_local_instance = true;
}
const page = yield instance.createPage();
if (block_assets) {
yield * blockResourceLoading(page);
}
yield page.open(url);
let html = yield page.property('content');
yield page.close();
if (is_local_instance) {
instance.exit();
}
return html;
}
function* initPhantomInstance() {
return yield phantom.create();
}
module.exports = {
blockResourceLoading: blockResourceLoading,
fetchPageContent: fetchPageContent,
initPhantomInstance: initPhantomInstance
};
| /* eslint no-console: 0 */
'use strict';
const phantom = require('phantom');
function* blockResourceLoading(page) {
yield page.property('onResourceRequested', function(requestData, request) {
var BLOCKED_RESOURCES = [
/\.gif/gi,
/\.png/gi,
/\.css/gi,
/^((?!(feuseradmin\.js|tinymce|jquery-)).)*\.js.*/gi
];
var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) {
return r.test(requestData['url']);
});
if (is_blacklisted_resource) {
request.abort();
}
});
}
function* fetchPageContent(url, instance) {
let is_local_instance = false;
if (!instance) {
instance = yield * initPhantomInstance();
is_local_instance = true;
}
const page = yield instance.createPage();
yield * blockResourceLoading(page);
yield page.open(url);
let html = yield page.property('content');
yield page.close();
if (is_local_instance) {
instance.exit();
}
return html;
}
function* initPhantomInstance() {
return yield phantom.create();
}
module.exports = {
blockResourceLoading: blockResourceLoading,
fetchPageContent: fetchPageContent,
initPhantomInstance: initPhantomInstance
};
|
Add getTime as default wit action in boilerplate | const moment = require('moment');
const weather = require('./weather');
const actions = {
getWeather: (data) => new Promise((resolve, reject) => {
const context = data.context;
const entities = data.entities;
const missingLocation = entities.location === undefined;
const location = entities.location ? entities.location[0].value : null;
const datetime = entities.datetime ? entities.datetime[0].value : null;
if (missingLocation) {
const contextData = Object.assign({}, context, { missingLocation });
resolve(contextData);
} else if (datetime) {
weather.forecastByLocationName(location, datetime)
.then((weatherData) => {
const contextData = Object.assign({}, context, weatherData);
if (datetime) {
Object.assign(contextData, { datetime: moment(datetime).calendar().toLowerCase() });
}
resolve(contextData);
})
.catch(reject);
} else {
weather.weatherByLocationName(location)
.then((weatherData) => {
const contextData = Object.assign({}, context, weatherData);
if (datetime) {
Object.assign(contextData, { datetime: moment(datetime).calendar().toLowerCase() });
}
resolve(contextData);
})
.catch(reject);
}
}),
getTime: (data) => new Promise((resolve, reject) => {
const context = data.context;
const contextData = {};
const datetime = new Date();
Object.assign(contextData, { datetime: moment(datetime).calendar().toLowerCase() });
resolve(contextData);
})
}
module.exports = actions; | const moment = require('moment');
const weather = require('./weather');
const actions = {
getWeather: (data) => new Promise((resolve, reject) => {
const context = data.context;
const entities = data.entities;
const missingLocation = entities.location === undefined;
const location = entities.location ? entities.location[0].value : null;
const datetime = entities.datetime ? entities.datetime[0].value : null;
if (missingLocation) {
const contextData = Object.assign({}, context, { missingLocation });
resolve(contextData);
} else if (datetime) {
weather.forecastByLocationName(location, datetime)
.then((weatherData) => {
const contextData = Object.assign({}, context, weatherData);
if (datetime) {
Object.assign(contextData, { datetime: moment(datetime).calendar().toLowerCase() });
}
resolve(contextData);
})
.catch(reject);
} else {
weather.weatherByLocationName(location)
.then((weatherData) => {
const contextData = Object.assign({}, context, weatherData);
if (datetime) {
Object.assign(contextData, { datetime: moment(datetime).calendar().toLowerCase() });
}
resolve(contextData);
})
.catch(reject);
}
})
}
module.exports = actions; |
Rename variable to conform to naming convention | "use strict";
var request = require('request-promise');
const baseUrl = 'https://api.yelp.com/v3/';
class Yelpv3 {
constructor(opts) {
this.api_key = opts.api_key;
}
get(resource, params) {
params = (typeof params === 'undefined') ? {} : params;
return request({
uri: baseUrl + resource + jsonToQueryString(params),
headers: {
'Authorization': 'Bearer ' + this.api_key
}
}).then((response) => {
return response;
}).catch((err) => {
throw err;
});
}
search(params) {
return this.get('businesses/search', params);
}
phoneSearch(params) {
return this.get('businesses/search/phone', params);
}
transactionSearch(transactionType, params) {
return this.get(`transactions/${transactionType}/search`, params);
}
business(id) {
return this.get(`businesses/${id}`, undefined);
}
reviews(id) {
return this.get(`businesses/${id}/reviews`, undefined);
}
autocomplete(params) {
return this.get('autocomplete', params);
}
}
function jsonToQueryString(json) {
return '?' +
Object.keys(json).map(function(key) {
if (key === 'price') {
return key + '=' + json[key];
} else {
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
}
}).join('&');
}
module.exports = Yelpv3;
| "use strict";
var request = require('request-promise');
const baseUrl = 'https://api.yelp.com/v3/';
class Yelpv3 {
constructor(opts) {
this.apiKey = opts.apiKey;
}
get(resource, params) {
params = (typeof params === 'undefined') ? {} : params;
return request({
uri: baseUrl + resource + jsonToQueryString(params),
headers: {
'Authorization': 'Bearer ' + this.apiKey
}
}).then((response) => {
return response;
}).catch((err) => {
throw err;
});
}
search(params) {
return this.get('businesses/search', params);
}
phoneSearch(params) {
return this.get('businesses/search/phone', params);
}
transactionSearch(transactionType, params) {
return this.get(`transactions/${transactionType}/search`, params);
}
business(id) {
return this.get(`businesses/${id}`, undefined);
}
reviews(id) {
return this.get(`businesses/${id}/reviews`, undefined);
}
autocomplete(params) {
return this.get('autocomplete', params);
}
}
function jsonToQueryString(json) {
return '?' +
Object.keys(json).map(function(key) {
if (key === 'price') {
return key + '=' + json[key];
} else {
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
}
}).join('&');
}
module.exports = Yelpv3;
|
Rename 'name' argument to 'filename' |
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].render(context))
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simple_tag(takes_context=True)
def asset(context, filename=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and filename is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if filename is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(filename=filename, alias=alias, mode=mode, deps=args)
return ''
|
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
content = self.nodelist.render(context)
# Now output out tags
extra_tags = '\n'.join(context.render_context['AMN'].render(context))
return mark_safe(extra_tags) + content
@register.tag
def assets(parser, token):
nodelist = parser.parse()
return AssetsNode(nodelist)
@register.simple_tag(takes_context=True)
def asset(context, name=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
{% asset name depends depends... %}
alias = short name for asset
file = static relative filename
mode = asset mode [inferred from filename extension]
args == dependencies [aliases or files]
'''
if alias is None and name is None:
raise template.TemplateSyntaxError(
'asset tag requires at least one of name or alias'
)
if name is None and mode is None:
raise template.TemplateSyntaxError(
'asset tag reqires mode when using an alias'
)
context.render_context['AMN'].add_asset(name=name, alias=alias, mode=mode, deps=args)
return ''
|
Change from /prev to /v1 | var Chalk = require('chalk');
var Cli = require('structured-cli');
var Open = require('opn');
module.exports = Cli.createCommand('edit', {
description: 'Edit this webtask in your browser',
plugins: [
require('./_plugins/profile'),
],
params: {
'name': {
description: 'The named webtask you want to edit',
type: 'string',
required: false
},
},
optionGroups: {
'Editor options': {
'editor-version': {
description: 'Open the webtask in a specific version of the Webtask Editor',
dest: 'editorVersion',
choices: ['v1', 'v2'],
type: 'string',
},
}
},
handler: handleEdit,
});
// Command handler
function handleEdit(args) {
var profile = args.profile;
var wtName = args.name ? args.name + '/' : '';
var url = profile.url + '/edit/' + profile.container + '#/' + wtName + profile.token;
if (args.editorVersion) {
url = profile.url + '/edit/' + args.editorVersion + '/' + profile.container + '#/' + wtName + profile.token;
}
console.log('Attempting to open the following url in your browser: ');
console.log();
console.log(Chalk.underline(url));
console.log();
console.log('If the webtask editor does not automatically open, please copy this address and paste it into your browser.');
return Open(url, { wait: false });
} | var Chalk = require('chalk');
var Cli = require('structured-cli');
var Open = require('opn');
module.exports = Cli.createCommand('edit', {
description: 'Edit this webtask in your browser',
plugins: [
require('./_plugins/profile'),
],
params: {
'name': {
description: 'The named webtask you want to edit',
type: 'string',
required: false
},
},
optionGroups: {
'Output options': {
'version': {
alias: 'v',
description: 'Use the previous version of the editor',
dest: 'version',
choices: ['v1', 'v2'],
type: 'string',
},
}
},
handler: handleEdit,
});
// Command handler
function handleEdit(args) {
var profile = args.profile;
var wtName = args.name ? args.name + '/' : '';
var url = profile.url + '/edit/' + profile.container + '#/' + wtName + profile.token;
if (args.version) {
url = profile.url + (args.version === `v1` ? '/prev' : '') + '/edit/' + profile.container + '#/' + wtName + profile.token;
}
console.log('Attempting to open the following url in your browser: ');
console.log();
console.log(Chalk.underline(url));
console.log();
console.log('If the webtask editor does not automatically open, please copy this address and paste it into your browser.');
return Open(url, { wait: false });
} |
Add dependency on having psutil available. | from __future__ import print_function
from setuptools import setup
setup_kwargs = dict(
name = 'mod_wsgi-metrics',
version = '1.1.0',
description = 'Metrics package for Apache/mod_wsgi.',
author = 'Graham Dumpleton',
author_email = '[email protected]',
maintainer = 'Graham Dumpleton',
maintainer_email = '[email protected]',
url = 'http://www.modwsgi.org/',
license = 'Apache License, Version 2.0',
platforms = [],
download_url = None,
classifiers= [
'Development Status :: 6 - Mature',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Operating System :: POSIX :: BSD',
'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: SunOS/Solaris',
'Programming Language :: Python',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI',
],
packages = ['mod_wsgi', 'mod_wsgi.metrics', 'mod_wsgi.metrics.newrelic'],
package_dir = {'mod_wsgi': 'src'},
install_requires=['psutil >= 2.0.0'],
)
setup(**setup_kwargs)
| from __future__ import print_function
from setuptools import setup
setup_kwargs = dict(
name = 'mod_wsgi-metrics',
version = '1.1.0',
description = 'Metrics package for Apache/mod_wsgi.',
author = 'Graham Dumpleton',
author_email = '[email protected]',
maintainer = 'Graham Dumpleton',
maintainer_email = '[email protected]',
url = 'http://www.modwsgi.org/',
license = 'Apache License, Version 2.0',
platforms = [],
download_url = None,
classifiers= [
'Development Status :: 6 - Mature',
'License :: OSI Approved :: Apache Software License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Operating System :: POSIX :: BSD',
'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: SunOS/Solaris',
'Programming Language :: Python',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI',
],
packages = ['mod_wsgi', 'mod_wsgi.metrics', 'mod_wsgi.metrics.newrelic'],
package_dir = {'mod_wsgi': 'src'},
)
setup(**setup_kwargs)
|
Fix for missing optionalSettings in overriden googleChartApiConfig value
At present one must always include optionalSettings:{} in the overriden googleChartApiConfig even when node optional settings are needed. | /* global angular */
(function(){
angular.module('googlechart')
.factory('googleChartApiPromise', googleChartApiPromiseFactory);
googleChartApiPromiseFactory.$inject = ['$rootScope', '$q', 'googleChartApiConfig', 'googleJsapiUrl'];
function googleChartApiPromiseFactory($rootScope, $q, apiConfig, googleJsapiUrl) {
apiConfig.optionalSettings = apiConfig.optionalSettings || {};
var apiReady = $q.defer();
var onLoad = function () {
// override callback function
var settings = {
callback: function () {
var oldCb = apiConfig.optionalSettings.callback;
$rootScope.$apply(function () {
apiReady.resolve(google);
});
if (angular.isFunction(oldCb)) {
oldCb.call(this);
}
}
};
settings = angular.extend({}, apiConfig.optionalSettings, settings);
window.google.load('visualization', apiConfig.version, settings);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = googleJsapiUrl;
if (script.addEventListener) { // Standard browsers (including IE9+)
script.addEventListener('load', onLoad, false);
} else { // IE8 and below
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
onLoad();
}
};
}
head.appendChild(script);
return apiReady.promise;
}
})(); | /* global angular */
(function(){
angular.module('googlechart')
.factory('googleChartApiPromise', googleChartApiPromiseFactory);
googleChartApiPromiseFactory.$inject = ['$rootScope', '$q', 'googleChartApiConfig', 'googleJsapiUrl'];
function googleChartApiPromiseFactory($rootScope, $q, apiConfig, googleJsapiUrl) {
var apiReady = $q.defer();
var onLoad = function () {
// override callback function
var settings = {
callback: function () {
var oldCb = apiConfig.optionalSettings.callback;
$rootScope.$apply(function () {
apiReady.resolve(google);
});
if (angular.isFunction(oldCb)) {
oldCb.call(this);
}
}
};
settings = angular.extend({}, apiConfig.optionalSettings, settings);
window.google.load('visualization', apiConfig.version, settings);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = googleJsapiUrl;
if (script.addEventListener) { // Standard browsers (including IE9+)
script.addEventListener('load', onLoad, false);
} else { // IE8 and below
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
onLoad();
}
};
}
head.appendChild(script);
return apiReady.promise;
}
})(); |
Add glyphicon with remove icon in case of failure | /**!
* AngularJS Ladda directive
* @author Chungsub Kim <[email protected]>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
element.append(' <span style="display:none" class="glyphicon glyphicon-remove"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
console.log(scope.btn_error);
var ladda_class='ladda-success';
if(scope.btn_error){
var ladda_class='ladda-remove';
}
element.addClass(ladda_class);
setTimeout(function () {
element.removeClass(ladda_class);
}, 2000);
}
}
});
}
};
}
]
);
})();
| /**!
* AngularJS Ladda directive
* @author Chungsub Kim <[email protected]>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
element.addClass('ladda-success');
setTimeout(function () {
element.removeClass('ladda-success');
}, 1000);
}
}
});
}
};
}
]
);
})();
|
Add comment on HOG calculations | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many values are returned and why.
Creates a square array and inputs it to hog. For simplicity the
blocks and the cells are square. The calculated orientations are set to 9.
Based on these the result should include a number of values equal to::
block_possitions^2 * cells_per_block^2 * orientations
HOG calculations take place in row major order.
"""
pixels_per_cell = 9
cells_per_block = 8
orientations = 9
# double the size so to generate some blocks and initialize the array
arr_dim = 2 * pixels_per_cell * cells_per_block
arr = numpy.zeros((arr_dim, arr_dim))
parameters = {'data': [arr],
'orientations': orientations,
'pixels_per_cell': [pixels_per_cell, pixels_per_cell],
'cells_per_block': [cells_per_block, cells_per_block]}
results = descriptors.hog(parameters)
# calculate how many blocks fit in the array, basically how many
# sliding window positions are there
block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1
assert_equal(results.shape[0], block_positions**2 *\
cells_per_block**2 *\
orientations)
| """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many values are returned and why.
Creates a square array and inputs it to hog. For simplicity the
blocks and the cells are square. The calculated orientations are set to 9.
Based on these the result should include a number of values equal to::
block_possitions^2 * cells_per_block^2 * orientations
"""
pixels_per_cell = 9
cells_per_block = 8
orientations = 9
# double the size so to generate some blocks and initialize the array
arr_dim = 2 * pixels_per_cell * cells_per_block
arr = numpy.zeros((arr_dim, arr_dim))
parameters = {'data': [arr],
'orientations': orientations,
'pixels_per_cell': [pixels_per_cell, pixels_per_cell],
'cells_per_block': [cells_per_block, cells_per_block]}
results = descriptors.hog(parameters)
# calculate how many blocks fit in the array, basically how many
# sliding window positions are there
block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1
assert_equal(results.shape[0], block_positions**2 *\
cells_per_block**2 *\
orientations)
|
Fix invalid bitmask for release archives | var eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip'),
rename = require('gulp-rename');
gulp.task('prepare-release', function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('external-api-plugin-' + version + '.zip')),
getSources()
.pipe(tar('external-api-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(644))
.pipe(gulp.dest('release'));
});
// Builds and packs plugins sources
gulp.task('default', ['prepare-release'], function() {
// The "default" task is just an alias for "prepare-release" task.
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Controller/*',
'LICENSE',
'Plugin.php',
'README.md',
'routing.yml'
],
{base: './'}
)
.pipe(rename(function(path) {
path.dirname = 'Mibew/Mibew/Plugin/ExternalApi/' + path.dirname;
}));
}
| var eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip'),
rename = require('gulp-rename');
gulp.task('prepare-release', function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('external-api-plugin-' + version + '.zip')),
getSources()
.pipe(tar('external-api-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(0644))
.pipe(gulp.dest('release'));
});
// Builds and packs plugins sources
gulp.task('default', ['prepare-release'], function() {
// The "default" task is just an alias for "prepare-release" task.
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Controller/*',
'LICENSE',
'Plugin.php',
'README.md',
'routing.yml'
],
{base: './'}
)
.pipe(rename(function(path) {
path.dirname = 'Mibew/Mibew/Plugin/ExternalApi/' + path.dirname;
}));
}
|
Hide AbstractMethod class from the docs. | #!/usr/bin/env python
# Generates the *public* API documentation.
# Remember to hide your private parts, people!
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.join(['--name', project,
'--exclude Exscript.AbstractMethod',
'--exclude Exscript.AccountManager',
'--exclude Exscript.HostAction',
'--exclude Exscript.Log',
'--exclude Exscript.Logfile',
'--exclude Exscript.QueueLogger',
'--exclude Exscript.QueueListener',
'--exclude Exscript.util.otp',
'--exclude Exscript.interpreter',
'--exclude Exscript.protocols.AbstractMethod',
'--exclude Exscript.protocols.telnetlib',
'--exclude Exscript.stdlib',
'--exclude Exscript.workqueue',
'--exclude Exscript.version',
'--html',
'--no-private',
'--no-source',
'--no-frames',
'--inheritance=included',
'-v',
'-o %s' % doc_dir,
base_dir]))
| #!/usr/bin/env python
# Generates the *public* API documentation.
# Remember to hide your private parts, people!
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Generate the API documentation.
os.system('epydoc ' + ' '.join(['--name', project,
'--exclude Exscript.AccountManager',
'--exclude Exscript.HostAction',
'--exclude Exscript.Log',
'--exclude Exscript.Logfile',
'--exclude Exscript.QueueLogger',
'--exclude Exscript.QueueListener',
'--exclude Exscript.util.otp',
'--exclude Exscript.interpreter',
'--exclude Exscript.protocols.AbstractMethod',
'--exclude Exscript.protocols.telnetlib',
'--exclude Exscript.stdlib',
'--exclude Exscript.workqueue',
'--exclude Exscript.version',
'--html',
'--no-private',
'--no-source',
'--no-frames',
'--inheritance=included',
'-v',
'-o %s' % doc_dir,
base_dir]))
|
Fix missing return statement in getUserByIdentifier | <?php
namespace Auth0\Login\Repository;
use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;
class Auth0UserRepository implements Auth0UserRepositoryContract
{
/**
* @param array $decodedJwt
*
* @return Auth0JWTUser
*/
public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
{
return new Auth0JWTUser($decodedJwt);
}
/**
* @param array $userInfo
*
* @return Auth0User
*/
public function getUserByUserInfo(array $userInfo) : Authenticatable
{
return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
}
/**
* @param string|int|null $identifier
*
* @return Authenticatable|null
*/
public function getUserByIdentifier($identifier) : ?Authenticatable
{
// Get the user info of the user logged in (probably in session)
$user = \App::make('auth0')->getUser();
if ($user === null) {
return null;
}
// Build the user
$auth0User = $this->getUserByUserInfo($user);
// It is not the same user as logged in, it is not valid
if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
return $auth0User;
}
return null;
}
}
| <?php
namespace Auth0\Login\Repository;
use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;
class Auth0UserRepository implements Auth0UserRepositoryContract
{
/**
* @param array $decodedJwt
*
* @return Auth0JWTUser
*/
public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
{
return new Auth0JWTUser($decodedJwt);
}
/**
* @param array $userInfo
*
* @return Auth0User
*/
public function getUserByUserInfo(array $userInfo) : Authenticatable
{
return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
}
/**
* @param string|int|null $identifier
*
* @return Authenticatable|null
*/
public function getUserByIdentifier($identifier) : ?Authenticatable
{
// Get the user info of the user logged in (probably in session)
$user = \App::make('auth0')->getUser();
if ($user === null) {
return null;
}
// Build the user
$auth0User = $this->getUserByUserInfo($user);
// It is not the same user as logged in, it is not valid
if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
return $auth0User;
}
}
}
|
Add L5.1 fallback to system test provider seed | <?php
namespace Tests\System\AlgoWeb\PODataLaravel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
class TestServiceProvider extends BaseServiceProvider
{
protected $defer = false;
public function register()
{
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'DatabaseSeeder.php');
}
/**
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function boot()
{
$this->loadMigrationsFrom(
__DIR__ .'/database/migrations'
);
$this->seed();
}
/**
* @param array|string $path
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function loadMigrationsFrom($path)
{
$migrator = $this->app->make('migrator');
$migrationRepository = $migrator->getRepository();
$migrationRepository->setSource('testbench');
$migrationRepository->createRepository();
$migrator->run($path);
}
protected function seed()
{
Model::unguarded(function () {
$seeder = $this->getSeeder();
if (method_exists($seeder, 'run')) {
$seeder->run();
} else {
$seeder->__invoke();
}
});
}
/**
* Get a seeder instance from the container.
*
* @return \Illuminate\Database\Seeder
*/
protected function getSeeder()
{
$class = $this->app->make('DatabaseSeeder');
return $class->setContainer($this->app);
}
}
| <?php
namespace Tests\System\AlgoWeb\PODataLaravel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
class TestServiceProvider extends BaseServiceProvider
{
protected $defer = false;
public function register()
{
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'DatabaseSeeder.php');
}
/**
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function boot()
{
$this->loadMigrationsFrom(
__DIR__ .'/database/migrations'
);
$this->seed();
}
/**
* @param array|string $path
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function loadMigrationsFrom($path)
{
$migrator = $this->app->make('migrator');
$migrationRepository = $migrator->getRepository();
$migrationRepository->setSource('testbench');
$migrationRepository->createRepository();
$migrator->run($path);
}
protected function seed()
{
Model::unguarded(function () {
$this->getSeeder()->__invoke();
});
}
/**
* Get a seeder instance from the container.
*
* @return \Illuminate\Database\Seeder
*/
protected function getSeeder()
{
$class = $this->app->make('DatabaseSeeder');
return $class->setContainer($this->app);
}
}
|
Fix initial action to include a type | import {
BehaviorSubject,
ReplaySubject
} from 'rx'
export default function createDispatcher() {
const dispatcher = new ReplaySubject()
dispatcher.onNext({ type: '_INIT_' }) // Initialisation action
const identifier = Symbol()
const cache = []
const state = []
// Extend Observable with our Dispatcher methods
const res = dispatcher.asObservable()
const proto = Object.create(Object.getPrototypeOf(res))
Object.setPrototypeOf(res, proto)
proto.dispatch = action => {
if (typeof action === 'function') {
return Promise.resolve(
action(res => {
dispatcher.onNext(res)
})
).then(res => {
dispatcher.onNext(res)
return res
})
}
dispatcher.onNext(action)
return Promise.resolve(action)
}
proto.getState = fn => {
if (typeof fn[identifier] === 'number')
return state[fn[identifier]]()
throw `Function wasn't yet reduced and is therefore unknown.`
}
proto.reduce = (fn, init = null) => {
if (typeof fn[identifier] === 'number')
return cache[fn[identifier]]
const store = new BehaviorSubject(init)
const anon = store.asObservable()
dispatcher
.scan(fn)
.distinctUntilChanged()
.subscribe(x => store.onNext(x))
fn[identifier] = cache.length
state.push(store.getValue.bind(store))
cache.push(anon)
return anon
}
return res
}
| import {
BehaviorSubject,
ReplaySubject
} from 'rx'
export default function createDispatcher() {
const dispatcher = new ReplaySubject()
dispatcher.onNext(null) // Initialisation action
const identifier = Symbol()
const cache = []
const state = []
// Extend Observable with our Dispatcher methods
const res = dispatcher.asObservable()
const proto = Object.create(Object.getPrototypeOf(res))
Object.setPrototypeOf(res, proto)
proto.dispatch = action => {
if (typeof action === 'function') {
return Promise.resolve(
action(res => {
dispatcher.onNext(res)
})
).then(res => {
dispatcher.onNext(res)
return res
})
}
dispatcher.onNext(action)
return Promise.resolve(action)
}
proto.getState = fn => {
if (typeof fn[identifier] === 'number')
return state[fn[identifier]]()
throw `Function wasn't yet reduced and is therefore unknown.`
}
proto.reduce = (fn, init = null) => {
if (typeof fn[identifier] === 'number')
return cache[fn[identifier]]
const store = new BehaviorSubject(init)
const anon = store.asObservable()
dispatcher
.scan(fn)
.distinctUntilChanged()
.subscribe(x => store.onNext(x))
fn[identifier] = cache.length
state.push(store.getValue.bind(store))
cache.push(anon)
return anon
}
return res
}
|
Update problem 55 (stil TLE) | package leetcode;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
public class Problem55 {
public boolean canJump(int[] nums) {
Stack<Integer> stack = new Stack<>();
Set<Integer> set = new HashSet<>();
stack.add(0);
while (!stack.isEmpty()) {
int idx = stack.pop();
if (idx == nums.length-1) {
return true;
}
int val = nums[idx];
for (int i = idx+1; i <= idx+val; i++) {
if (i == nums.length-1) {
return true;
}
if (set.contains(i)) {
continue;
}
set.add(i);
stack.push(i);
}
}
return false;
}
public static void main(String[] args) {
Problem55 prob = new Problem55();
System.out.println(prob.canJump(new int[]{2,3,1,1,4})); // true
System.out.println(prob.canJump(new int[]{3,2,1,0,4})); // false
System.out.println(prob.canJump(new int[]{2,0})); // true
System.out.println(prob.canJump(new int[]{0})); // true
System.out.println(prob.canJump(new int[]{0,2,3})); // false
System.out.println(prob.canJump(new int[]{1,0,1,0})); // false
}
}
| package leetcode;
public class Problem55 {
public boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
for (int i = 0; i < nums.length; i++) {
if (canJump(nums, i)) {
return true;
}
}
return false;
}
private boolean canJump(int[] nums, int idx) {
int i = idx;
while (i < nums.length) {
if (nums[i] == 0) {
return false;
}
int val = (nums.length-1) - i - nums[i];
if (val == 0) {
return true;
}
i += nums[i];
}
return false;
}
public static void main(String[] args) {
Problem55 prob = new Problem55();
System.out.println(prob.canJump(new int[]{2,3,1,1,4}));
System.out.println(prob.canJump(new int[]{3,2,1,0,4}));
System.out.println(prob.canJump(new int[]{2,0}));
System.out.println(prob.canJump(new int[]{0}));
}
}
|
admin_programme: Add active field to form. | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.ext_programme.models import ProgrammeEvent
class ProgrammeEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProgrammeEventForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Tapahtuma',
'event_type',
'title',
'description',
'start',
'end',
'presenters',
'presenters_titles',
'icon_original',
'email',
'home_url',
'twitter_url',
'github_url',
'facebook_url',
'linkedin_url',
'wiki_url',
'gplus_url',
'active',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = ProgrammeEvent
exclude = ('event','icon_small',)
| # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.ext_programme.models import ProgrammeEvent
class ProgrammeEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProgrammeEventForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'Tapahtuma',
'event_type',
'title',
'description',
'start',
'end',
'presenters',
'presenters_titles',
'icon_original',
'email',
'home_url',
'twitter_url',
'github_url',
'facebook_url',
'linkedin_url',
'wiki_url',
'gplus_url',
ButtonHolder (
Submit('submit', u'Tallenna')
)
)
)
class Meta:
model = ProgrammeEvent
exclude = ('event','icon_small',)
|
Test incorrect creation of attributes. | describe("Species", function() {
var Human, bob;
beforeEach(function() {
Human = Species({
bringToLife: function() {
this.wings = "Yes! now I can fly"; // no you can't. defining attributes here won't work.
return function(name) {
this.name = name;
this.sayName = function() {
return "My name is " + this.name;
}
}
}
});
bob = new Human("bob");
});
describe("object instance", function() {
it("has the attributes specified in the 'bringToLife' function (in the inner function)", function(){
expect(bob.name).toEqual("bob");
expect(bob.sayName()).toEqual("My name is bob");
});
it("does NOT have the attributes specified outside the inner function in the 'bringToLife' function", function() {
expect(bob.wings).toBe(undefined);
});
it("can override a specified attribute", function() {
expect(bob.sayName()).toEqual("My name is bob");
bob.sayName = function() { return "I'm not telling" }; // redefine the function
expect(bob.sayName()).toEqual("I'm not telling");
});
it("has attributes that are completely separate from other object instances", function() {
jane = new Human("jane");
expect(jane.sayName()).toEqual("My name is jane");
bob.sayName = function() { return "I'm not telling" }; // redefine bob's function
expect(jane.sayName()).toEqual("My name is jane"); // jane's function is not affected
bob.sayName = jane.sayName; // restore the function to bob
expect(bob.sayName()).toEqual("My name is bob");
});
});
}); | describe("Species;", function() {
var Human, bob;
beforeEach(function() {
Human = Species({
bringToLife: function() {
return function(name) {
this.name = name;
this.sayName = function() {
return "My name is " + this.name;
}
}
}
});
bob = new Human("bob");
});
describe("an object instance", function() {
it("has the attributes specified in the 'bringToLife' function", function(){
expect(bob.name).toEqual("bob");
expect(bob.sayName()).toEqual("My name is bob");
});
it("can override a specified attribute", function() {
expect(bob.sayName()).toEqual("My name is bob");
bob.sayName = function() { return "I'm not telling" }; // redefine the function
expect(bob.sayName()).toEqual("I'm not telling");
});
it("has attributes that are completely separate from other object instances", function() {
jane = new Human("jane");
expect(jane.sayName()).toEqual("My name is jane");
bob.sayName = function() { return "I'm not telling" }; // redefine bob's function
expect(jane.sayName()).toEqual("My name is jane"); // jane's function is not affected
bob.sayName = jane.sayName; // restore the function to bob
expect(bob.sayName()).toEqual("My name is bob");
});
});
}); |
Bring ZF2 error into view | define([
"intern!object",
"intern/chai!assert",
"require",
"tests/support/helper"
], function ( registerSuite, assert, require, testHelper ) {
var signIn = testHelper.getAppUrl( "admin/signin" );
var mainPage = testHelper.getAppUrl( "" );
registerSuite({
name: "Main page.",
"Main page is loading.": function () {
return this.remote
.get( mainPage )
.setExecuteAsyncTimeout( 10000 )
.executeAsync( function () {
window.scrollTo( 1000, 0 );
});
// .setFindTimeout( 3000 )
// .findByCssSelector( "body.application" )
// .isDisplayed()
// .then( function ( visible ) {
// assert.ok( visible, "Sign in form loaded." );
// });
}
});
return;
registerSuite({
name: "Admin auth.",
"Panel is loading.": function () {
return this.remote
.get( signIn )
.setFindTimeout( 3000 )
.findByCssSelector( "div.admin-auth" )
.isDisplayed()
.then( function ( visible ) {
assert.ok( visible, "Sign in form loaded." );
});
}
});
}); | define([
"intern!object",
"intern/chai!assert",
"require",
"tests/support/helper"
], function ( registerSuite, assert, require, testHelper ) {
var signIn = testHelper.getAppUrl( "admin/signin" );
var mainPage = testHelper.getAppUrl( "" );
registerSuite({
name: "Main page.",
/** Check if link to profile configuration is added. */
"Main page is loading.": function () {
return this.remote
.get( mainPage )
.setFindTimeout( 1000 )
/** Check if $panel property is null at first. */
.execute( function () {
document.getElementsByTagName( "table" )[ 0 ].style.width = "500px";
});
// .setFindTimeout( 3000 )
// /** Open panel by clicking entry. */
// .findByCssSelector( "body.application" )
// .isDisplayed()
// .then( function ( visible ) {
// assert.ok( visible, "Sign in form loaded." );
// });
}
});
registerSuite({
name: "Admin auth.",
/** Check if link to profile configuration is added. */
"Panel is loading.": function () {
return this.remote
.get( signIn )
.setFindTimeout( 3000 )
/** Open panel by clicking entry. */
.findByCssSelector( "div.admin-auth" )
.isDisplayed()
.then( function ( visible ) {
assert.ok( visible, "Sign in form loaded." );
});
}
});
}); |
Update the admin interface and demo site generator
Update the admin interface to feature a fully responsive, fully retina, cleaned up look and feel based on Bootstrap 3. Simultaniously updated the generated demo site to be more in line with what we use as a starting point for our websites.
While this commit is squashed under my name, this is the result of the hard work by too many people to mention by name. | <?php
namespace Kunstmaan\SeoBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* SeoType
*/
class SeoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden')
->add('metaTitle', null, array(
'label' => 'Meta title',
'attr' => array(
'info_text' => 'Sets the title in the head of your document. It should be short and descriptive. The content of the "Navigation title" field will be used if this field is left blank.'
)
))
->add('metaAuthor', null, array('label' => 'Meta author'))
->add('metaDescription', null, array('label' => 'Meta description'))
->add('metaKeywords', null, array('label' => 'Meta keywords'))
->add('metaRobots', null, array('label' => 'Meta robots'))
->add('metaRevised', null, array('label' => 'Meta revised'))
->add('extraMetadata', 'textarea', array('label' => 'Extra metadata', 'required' => false));
}
/**
* @return string
*/
public function getName()
{
return 'seo';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kunstmaan\SeoBundle\Entity\Seo',
));
}
}
| <?php
namespace Kunstmaan\SeoBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* SeoType
*/
class SeoType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'hidden')
->add('metaTitle', null, array('label' => 'Title', 'attr' => array('info_text' => 'Use %websitetitle% to dynamic fill in the main website title.')))
->add('metaAuthor', null, array('label' => 'Meta author'))
->add('metaDescription', null, array('label' => 'Meta description'))
->add('metaKeywords', null, array('label' => 'Meta keywords'))
->add('metaRobots', null, array('label' => 'Meta robots'))
->add('metaRevised', null, array('label' => 'Meta revised'))
->add('extraMetadata', 'textarea', array('label' => 'Extra metadata', 'required' => false));
}
/**
* @return string
*/
public function getName()
{
return 'seo';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kunstmaan\SeoBundle\Entity\Seo',
));
}
}
|
Switch to a Python3 Compataible open + read + exec vs execfile | #!/usr/bin/env python
# Support setuptools or distutils
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Version info -- read without importing
_locals = {}
with open('invocations/_version.py') as fp:
exec(fp.read(), None, _locals)
version = _locals['__version__']
setup(
name='invocations',
version=version,
description='Reusable Invoke tasks',
license='BSD',
author='Jeff Forcier',
author_email='[email protected]',
url='http://pyinvoke.org',
# Release requirements. See dev-requirements.txt for dev version reqs.
requirements=['invoke>=0.1.0'],
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Software Distribution',
'Topic :: System :: Systems Administration',
],
)
| #!/usr/bin/env python
# Support setuptools or distutils
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Version info -- read without importing
_locals = {}
version_module = execfile('invocations/_version.py', _locals)
version = _locals['__version__']
setup(
name='invocations',
version=version,
description='Reusable Invoke tasks',
license='BSD',
author='Jeff Forcier',
author_email='[email protected]',
url='http://pyinvoke.org',
# Release requirements. See dev-requirements.txt for dev version reqs.
requirements=['invoke>=0.1.0'],
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Build Tools',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Software Distribution',
'Topic :: System :: Systems Administration',
],
)
|
Move password service to factories | <?php
namespace GoalioForgotPassword;
use Zend\Loader\StandardAutoloader;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\ModuleRouteListener;
class Module {
public function getAutoloaderConfig() {
return array(
AutoloaderFactory::STANDARD_AUTOLOADER => array(
StandardAutoloader::LOAD_NS => array(
__NAMESPACE__ => __DIR__,
),
),
);
}
public function getConfig() {
return include __DIR__ . '/../../config/module.config.php';
}
public function getModuleDependencies() {
return array('ZfcUser', 'ZfcBase');
}
public function getServiceConfig() {
return array(
'invokables' => array(
),
'factories' => array(
'goalioforgotpassword_module_options' => 'GoalioForgotPassword\Options\Service\ModuleOptionsFactory',
'goalioforgotpassword_forgot_form' => 'GoalioForgotPassword\Form\Service\ForgotFactory',
'goalioforgotpassword_reset_form' => 'GoalioForgotPassword\Form\Service\ResetFactory',
'goalioforgotpassword_password_mapper' => 'GoalioForgotPassword\Mapper\Service\PasswordFactory',
'goalioforgotpassword_password_service' => 'GoalioForgotPassword\Factory\Service\PasswordFactory',
),
);
}
}
| <?php
namespace GoalioForgotPassword;
use Zend\Loader\StandardAutoloader;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\ModuleRouteListener;
class Module {
public function getAutoloaderConfig() {
return array(
AutoloaderFactory::STANDARD_AUTOLOADER => array(
StandardAutoloader::LOAD_NS => array(
__NAMESPACE__ => __DIR__,
),
),
);
}
public function getConfig() {
return include __DIR__ . '/../../config/module.config.php';
}
public function getModuleDependencies() {
return array('ZfcUser', 'ZfcBase');
}
public function getServiceConfig() {
return array(
'invokables' => array(
'goalioforgotpassword_password_service' => 'GoalioForgotPassword\Service\Password',
),
'factories' => array(
'goalioforgotpassword_module_options' => 'GoalioForgotPassword\Options\Service\ModuleOptionsFactory',
'goalioforgotpassword_forgot_form' => 'GoalioForgotPassword\Form\Service\ForgotFactory',
'goalioforgotpassword_reset_form' => 'GoalioForgotPassword\Form\Service\ResetFactory',
'goalioforgotpassword_password_mapper' => 'GoalioForgotPassword\Mapper\Service\PasswordFactory',
),
);
}
}
|
Correct the usage of title as a component
Documentation for this feature can be found [here](https://github.com/nfl/react-helmet#as-react-components) | import React from 'react'
import Helmet from 'react-helmet'
import { prefixLink } from 'gatsby-helpers'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render() {
const {body, route} = this.props
const {title} = Helmet.rewind()
const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
let css
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
{ title.toComponent() }
{ font }
{ css }
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } />
<script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } />
</body>
</html>
)
},
})
| import React from 'react'
import Helmet from 'react-helmet'
import { prefixLink } from 'gatsby-helpers'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render() {
const {body, route} = this.props
const head = Helmet.rewind()
const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
let css
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
<title>
{ head.title }
</title>
{ font }
{ css }
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } />
<script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } />
</body>
</html>
)
},
})
|
Add note in hog test doc string | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many values are returned and why.
Creates a square array and inputs it to hog. For simplicity the
blocks and the cells are square. The calculated orientations are set to 9.
Based on these the result should include a number of values equal to::
block_possitions^2 * cells_per_block^2 * orientations
"""
pixels_per_cell = 9
cells_per_block = 8
orientations = 9
# double the size so to generate some blocks and initialize the array
arr_dim = 2 * pixels_per_cell * cells_per_block
arr = numpy.zeros((arr_dim, arr_dim))
parameters = {'data': [arr],
'orientations': orientations,
'pixels_per_cell': [pixels_per_cell, pixels_per_cell],
'cells_per_block': [cells_per_block, cells_per_block]}
results = descriptors.hog(parameters)
# calculate how many blocks fit in the array, basically how many
# sliding window positions are there
block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1
assert_equal(results.shape[0], block_positions**2 *\
cells_per_block**2 *\
orientations)
| """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
Creates a square array and inputs it to hog. For simplicity the
blocks and the cells are square. The calculated orientations are set to 9.
Based on these the result should include a number of values equal to::
block_possitions^2 * cells_per_block^2 * orientations
"""
pixels_per_cell = 9
cells_per_block = 8
orientations = 9
# double the size so to generate some blocks and initialize the array
arr_dim = 2 * pixels_per_cell * cells_per_block
arr = numpy.zeros((arr_dim, arr_dim))
parameters = {'data': [arr],
'orientations': orientations,
'pixels_per_cell': [pixels_per_cell, pixels_per_cell],
'cells_per_block': [cells_per_block, cells_per_block]}
results = descriptors.hog(parameters)
# calculate how many blocks fit in the array, basically how many
# sliding window positions are there
block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1
assert_equal(results.shape[0], block_positions**2 *\
cells_per_block**2 *\
orientations)
|
Add module for start-to-finish functions | from . import pre, csr
import imageio
import tqdm
import numpy as np
from skimage import morphology
import pandas as pd
def process_images(filenames, image_format, threshold_radius,
smooth_radius, brightness_offset, scale_metadata_path):
image_format = None if image_format == 'auto' else image_format
results = []
for file in tqdm(filenames):
image = imageio.imread(file, format=image_format)
if scale_metadata_path is not None:
md_path = scale_metadata_path.split(sep=',')
meta = image.meta
for key in md_path:
meta = meta[key]
scale = float(meta)
else:
scale = 1 # measurements will be in pixel units
pixel_threshold_radius = int(np.ceil(threshold_radius / scale))
pixel_smoothing_radius = smooth_radius * pixel_threshold_radius
thresholded = pre.threshold(image, sigma=pixel_smoothing_radius,
radius=pixel_threshold_radius,
offset=brightness_offset)
skeleton = morphology.skeletonize(thresholded)
framedata = csr.summarise(skeleton, spacing=scale)
framedata['squiggle'] = np.log2(framedata['branch-distance'] /
framedata['euclidean-distance'])
framedata['filename'] = [file] * len(framedata)
results.append(framedata)
return pd.concat(results)
| from . import pre, csr
import imageio
import tqdm
import numpy as np
from skimage import morphology
import pandas as pd
def process_images(filenames, image_format, threshold_radius,
smooth_radius, brightness_offset, scale_metadata_path):
image_format = (None if self.image_format.get() == 'auto'
else self.image_format.get())
results = []
from skan import pre, csr
for file in tqdm(filenames):
image = imageio.imread(file, format=image_format)
if self.scale_metadata_path is not None:
md_path = self.scale_metadata_path.get().split(sep=',')
meta = image.meta
for key in md_path:
meta = meta[key]
scale = float(meta)
else:
scale = 1 # measurements will be in pixel units
pixel_threshold_radius = int(np.ceil(self.threshold_radius.get() /
scale))
pixel_smoothing_radius = (self.smooth_radius.get() *
pixel_threshold_radius)
thresholded = pre.threshold(image, sigma=pixel_smoothing_radius,
radius=pixel_threshold_radius,
offset=self.brightness_offset.get())
skeleton = morphology.skeletonize(thresholded)
framedata = csr.summarise(skeleton, spacing=scale)
framedata['squiggle'] = np.log2(framedata['branch-distance'] /
framedata['euclidean-distance'])
framedata['filename'] = [file] * len(framedata)
results.append(framedata)
results = pd.concat(results)
|
Make the select field type work like it's supposed to | <?php
/**
* Front End Accounts
*
* @category WordPress
* @package FrontEndAccounts
* @since 0.1
* @author Christopher Davis <http://christopherdavis.me>
* @copyright 2013 Christopher Davis
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Chrisguitarguy\FrontEndAccounts\Form\Field;
class Select extends FieldBase implements FieldInterface
{
/**
* {@inheritdoc}
* @see Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
*/
public function render()
{
printf(
'<select id="%1$s" name="%1$s" %2$s>',
$this->escAttr($this->getName()),
$this->arrayToAttr($this->getAdditionalAttributes())
);
if ($emp = $this->getArg('empty_first')) {
printf('<option value="">%s</option>', $this->escAttr($emp));
}
foreach ($this->getArg('choices', array()) as $val => $label) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
$this->escAttr($val),
selected($this->getValue(), $val, false), // XXX WordPress specific
$this->escHtml($label)
);
}
echo '</select>';
}
/**
* {@inheritdoc}
*/
protected function getAdditionalAttributes()
{
$atts = parent::getAdditionalAttributes();
if (!empty($this->args['multi'])) {
$atts['multiple'] = 'multiple';
}
return $atts;
}
}
| <?php
/**
* Front End Accounts
*
* @category WordPress
* @package FrontEndAccounts
* @since 0.1
* @author Christopher Davis <http://christopherdavis.me>
* @copyright 2013 Christopher Davis
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Chrisguitarguy\FrontEndAccounts\Form\Field;
class Select extends FieldBase implements FieldInterface
{
/**
* {@inheritdoc}
* @see Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
*/
public function render()
{
printf(
'<select id="%1$s" name="%1$s" %2$s>',
$this->escAttr($this->getName()),
$this->arrayToAttr($this->getAdditionalAttributes())
);
if ($emp = $this->getArg('empty_first')) {
printf('<option value="">%s</option>', $this->escAttr($emp));
}
foreach ($this->getArg('choices', array()) as $val => $label) {
printf(
'<option value="%2$s">%2$s</option>',
$this->escAttr($val),
$this->escHtml($label)
);
}
echo '</select>';
}
/**
* {@inheritdoc}
*/
protected function getAdditionalAttributes()
{
$atts = parent::getAdditionalAttributes();
if (!empty($this->args['multi'])) {
$atts['multiple'] = 'multiple';
}
return $atts;
}
}
|
Remove conditional on seeding users. | <?php
use Illuminate\Database\Seeder;
use VotingApp\Models\User;
class UsersTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Naomi',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
foreach (range(1, 25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
foreach (range(1, 25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
}
}
| <?php
use Illuminate\Database\Seeder;
use VotingApp\Models\User;
class UsersTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
User::truncate();
User::create([
'first_name' => 'Dave',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Andrea',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
User::create([
'first_name' => 'Naomi',
'email' => '[email protected]',
'password' => 'tops3cret',
])->assignRole(1);
if (app()->environment('local')) {
foreach (range(1, 25) as $index) {
User::create([
'first_name' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
foreach (range(1, 25) as $index) {
User::create([
'first_name' => $faker->firstName,
'phone' => $faker->unique()->phoneNumber,
'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
]);
}
}
}
}
|
Remove textwrap because python 2.7 lacks indent() function | import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
| import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
Fix missing import for throwing timeout Exception | <?php
namespace ConnectionManager\Extra;
use React\SocketClient\ConnectorInterface;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use Exception;
class ConnectionManagerTimeout implements ConnectorInterface
{
private $connectionManager;
private $loop;
private $timeout;
public function __construct(ConnectorInterface $connectionManager, LoopInterface $loop, $timeout)
{
$this->connectionManager = $connectionManager;
$this->loop = $loop;
$this->timeout = $timeout;
}
public function create($host, $port)
{
$deferred = new Deferred();
$timedout = false;
$tid = $this->loop->addTimer($this->timeout, function() use ($deferred, &$timedout) {
$deferred->reject(new Exception('Connection attempt timed out'));
$timedout = true;
// TODO: find a proper way to actually cancel the connection
});
$loop = $this->loop;
$this->connectionManager->create($host, $port)->then(function ($connection) use ($tid, $loop, &$timedout, $deferred) {
if ($timedout) {
// connection successfully established but timeout already expired => close successful connection
$connection->end();
} else {
$loop->cancelTimer($tid);
$deferred->resolve($connection);
}
}, function ($error) use ($loop, $tid) {
$loop->cancelTimer($tid);
throw $error;
});
return $deferred->promise();
}
}
| <?php
namespace ConnectionManager\Extra;
use React\SocketClient\ConnectorInterface;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
class ConnectionManagerTimeout implements ConnectorInterface
{
private $connectionManager;
private $loop;
private $timeout;
public function __construct(ConnectorInterface $connectionManager, LoopInterface $loop, $timeout)
{
$this->connectionManager = $connectionManager;
$this->loop = $loop;
$this->timeout = $timeout;
}
public function create($host, $port)
{
$deferred = new Deferred();
$timedout = false;
$tid = $this->loop->addTimer($this->timeout, function() use ($deferred, &$timedout) {
$deferred->reject(new Exception('Connection attempt timed out'));
$timedout = true;
// TODO: find a proper way to actually cancel the connection
});
$loop = $this->loop;
$this->connectionManager->create($host, $port)->then(function ($connection) use ($tid, $loop, &$timedout, $deferred) {
if ($timedout) {
// connection successfully established but timeout already expired => close successful connection
$connection->end();
} else {
$loop->cancelTimer($tid);
$deferred->resolve($connection);
}
}, function ($error) use ($loop, $tid) {
$loop->cancelTimer($tid);
throw $error;
});
return $deferred->promise();
}
}
|
Make code comments gender neutral
Replaces gendered references to users with a neutral 'them'. | <?php
namespace Auth0\Login;
use Auth0\Login\Contract\Auth0UserRepository;
use Illuminate\Routing\Controller;
class Auth0Controller extends Controller
{
/**
* @var Auth0UserRepository
*/
protected $userRepository;
/**
* Auth0Controller constructor.
*
* @param Auth0UserRepository $userRepository
*/
public function __construct(Auth0UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* Callback action that should be called by auth0, logs the user in.
*/
public function callback()
{
// Get a handle of the Auth0 service (we don't know if it has an alias)
$service = \App::make('auth0');
// Try to get the user information
$profile = $service->getUser();
// Get the user related to the profile
$auth0User = $this->userRepository->getUserByUserInfo($profile);
if ($auth0User) {
// If we have a user, we are going to log them in, but if
// there is an onLogin defined we need to allow the Laravel developer
// to implement the user as he wants an also let them store it.
if ($service->hasOnLogin()) {
$user = $service->callOnLogin($auth0User);
} else {
// If not, the user will be fine
$user = $auth0User;
}
\Auth::login($user, $service->rememberUser());
}
return \Redirect::intended('/');
}
}
| <?php
namespace Auth0\Login;
use Auth0\Login\Contract\Auth0UserRepository;
use Illuminate\Routing\Controller;
class Auth0Controller extends Controller
{
/**
* @var Auth0UserRepository
*/
protected $userRepository;
/**
* Auth0Controller constructor.
*
* @param Auth0UserRepository $userRepository
*/
public function __construct(Auth0UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* Callback action that should be called by auth0, logs the user in.
*/
public function callback()
{
// Get a handle of the Auth0 service (we don't know if it has an alias)
$service = \App::make('auth0');
// Try to get the user information
$profile = $service->getUser();
// Get the user related to the profile
$auth0User = $this->userRepository->getUserByUserInfo($profile);
if ($auth0User) {
// If we have a user, we are going to log him in, but if
// there is an onLogin defined we need to allow the Laravel developer
// to implement the user as he wants an also let him store it.
if ($service->hasOnLogin()) {
$user = $service->callOnLogin($auth0User);
} else {
// If not, the user will be fine
$user = $auth0User;
}
\Auth::login($user, $service->rememberUser());
}
return \Redirect::intended('/');
}
}
|
Remove unused statements from jobs | import React from "react";
import { connect } from "react-redux";
import { Switch, Route } from "react-router-dom";
import JobsList from "./List";
import JobDetail from "./Detail";
import JobsResources from "./Resources";
import Resources from "../../administration/components/Jobs/Resources";
import Tasks from "../../administration/components/Jobs/Tasks";
import { LoadingPlaceholder } from "../../base";
const JobsSettings = () => (
<div className="settings-container">
<h3 className="view-header">
<strong>
Job Settings
</strong>
</h3>
<Resources />
<Tasks />
</div>
);
const Jobs = (props) => {
if (props.settings === null) {
return <LoadingPlaceholder />;
}
return (
<div className="container">
<Switch>
<Route path="/jobs" component={JobsList} exact />
<Route path="/jobs/resources" component={JobsResources} />
<Route path="/jobs/settings" component={JobsSettings} />
<Route path="/jobs/:jobId" component={JobDetail} />
</Switch>
</div>
);
};
const mapStateToProps = (state) => ({
settings: state.settings.data
});
export default connect(mapStateToProps, null)(Jobs);
| import React from "react";
import { connect } from "react-redux";
import { Switch, Route } from "react-router-dom";
import { findJobs } from "../actions";
import JobsList from "./List";
import JobDetail from "./Detail";
import JobsResources from "./Resources";
import Resources from "../../administration/components/Jobs/Resources";
import Tasks from "../../administration/components/Jobs/Tasks";
import { LoadingPlaceholder } from "../../base";
const JobsSettings = () => (
<div className="settings-container">
<h3 className="view-header">
<strong>
Job Settings
</strong>
</h3>
<Resources />
<Tasks />
</div>
);
const Jobs = (props) => {
if (props.settings === null) {
return <LoadingPlaceholder />;
}
return (
<div className="container">
<Switch>
<Route path="/jobs" component={JobsList} exact />
<Route path="/jobs/resources" component={JobsResources} />
<Route path="/jobs/settings" component={JobsSettings} />
<Route path="/jobs/:jobId" component={JobDetail} />
</Switch>
</div>
);
};
const mapStateToProps = (state) => ({
documents: state.jobs.list,
settings: state.settings.data
});
const mapDispatchToProps = (dispatch) => ({
onFind: () => {
dispatch(findJobs());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Jobs);
|
Clean the lines in a seperate function. | #!/usr/bin/env python
import os
import setuptools
def _clean_line(line):
line = line.strip()
line = line.split("#")[0]
line = line.strip()
return line
def read_requires(base):
path = os.path.join('tools', base)
requires = []
if not os.path.isfile(path):
return requires
with open(path, 'rb') as h:
for line in h.read().splitlines():
line = _clean_line(line)
if not line:
continue
requires.append(line)
return requires
setuptools.setup(
name='taskflow',
version='0.0.1',
author='OpenStack',
license='Apache Software License',
description='Taskflow structured state management library.',
long_description='The taskflow library provides core functionality that '
'can be used to build [resumable, reliable, '
'easily understandable, ...] highly available '
'systems which process workflows in a structured manner.',
author_email='[email protected]',
url='http://www.openstack.org/',
tests_require=read_requires('test-requires'),
install_requires=read_requires('pip-requires'),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6', ],
)
| #!/usr/bin/env python
import os
import setuptools
def read_requires(base):
path = os.path.join('tools', base)
requires = []
if not os.path.isfile(path):
return requires
with open(path, 'rb') as h:
for line in h.read().splitlines():
line = line.strip()
if len(line) == 0 or line.startswith("#"):
continue
requires.append(line)
return requires
setuptools.setup(
name='taskflow',
version='0.0.1',
author='OpenStack',
license='Apache Software License',
description='Taskflow structured state management library.',
long_description='The taskflow library provides core functionality that '
'can be used to build [resumable, reliable, '
'easily understandable, ...] highly available '
'systems which process workflows in a structured manner.',
author_email='[email protected]',
url='http://www.openstack.org/',
tests_require=read_requires('test-requires'),
install_requires=read_requires('pip-requires'),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6', ],
)
|
Kill an Unused import - thanks to @landscapeio | """
Standalone test runner for wardrounds plugin
"""
import sys
from opal.core import application
class Application(application.OpalApplication):
pass
from django.conf import settings
settings.configure(DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
OPAL_OPTIONS_MODULE = 'referral.tests.dummy_options_module',
ROOT_URLCONF='referral.urls',
STATIC_URL='/assets/',
INSTALLED_APPS=('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.admin',
'opal',
'opal.tests',
'referral',))
from django.test.runner import DiscoverRunner
test_runner = DiscoverRunner(verbosity=1)
if len(sys.argv) == 2:
failures = test_runner.run_tests([sys.argv[-1], ])
else:
failures = test_runner.run_tests(['referral', ])
if failures:
sys.exit(failures)
| """
Standalone test runner for wardrounds plugin
"""
import os
import sys
from opal.core import application
class Application(application.OpalApplication):
pass
from django.conf import settings
settings.configure(DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
OPAL_OPTIONS_MODULE = 'referral.tests.dummy_options_module',
ROOT_URLCONF='referral.urls',
STATIC_URL='/assets/',
INSTALLED_APPS=('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.admin',
'opal',
'opal.tests',
'referral',))
from django.test.runner import DiscoverRunner
test_runner = DiscoverRunner(verbosity=1)
if len(sys.argv) == 2:
failures = test_runner.run_tests([sys.argv[-1], ])
else:
failures = test_runner.run_tests(['referral', ])
if failures:
sys.exit(failures)
|
Revert "Temporary turn off the batch attachments sanitize job handler"
b51dc42a6ed78b46051f21bf086596bffa198c05 | import monitor from 'monitor-dog';
import Raven from 'raven';
import config from 'config';
import { JobManager } from '../models';
import { initHandlers as initPeriodicHandlers } from './periodic';
import { initHandlers as initUserGoneHandlers } from './user-gone';
import { initHandlers as initAttachmentsSanitizeHandlers } from './attachments-sanitize';
export async function initJobProcessing(app) {
const jobManager = new JobManager(config.jobManager);
await Promise.all(
[initPeriodicHandlers, initUserGoneHandlers, initAttachmentsSanitizeHandlers].map((h) =>
h(jobManager, app),
),
);
// Use monitor and Sentry to collect job statistics and report errors
jobManager.use((handler) => async (job) => {
const timerName = `job-${job.name}-time`;
const requestsName = `job-${job.name}-requests`;
const errorsName = `job-${job.name}-errors`;
const timer = monitor.timer(timerName);
try {
const result = await handler(job);
monitor.increment(requestsName);
return result;
} catch (err) {
monitor.increment(errorsName);
if ('sentryDsn' in config) {
Raven.captureException(err, {
extra: { err: `error processing job '${job.name}': ${err.message}` },
});
}
// Job is still failed
throw err;
} finally {
timer.stop();
}
});
if (process.env.NODE_ENV !== 'test') {
jobManager.startPolling();
}
return jobManager;
}
| import monitor from 'monitor-dog';
import Raven from 'raven';
import config from 'config';
import { JobManager } from '../models';
import { initHandlers as initPeriodicHandlers } from './periodic';
import { initHandlers as initUserGoneHandlers } from './user-gone';
// import { initHandlers as initAttachmentsSanitizeHandlers } from './attachments-sanitize';
export async function initJobProcessing(app) {
const jobManager = new JobManager(config.jobManager);
await Promise.all(
[initPeriodicHandlers, initUserGoneHandlers /* , initAttachmentsSanitizeHandlers*/].map((h) =>
h(jobManager, app),
),
);
// Use monitor and Sentry to collect job statistics and report errors
jobManager.use((handler) => async (job) => {
const timerName = `job-${job.name}-time`;
const requestsName = `job-${job.name}-requests`;
const errorsName = `job-${job.name}-errors`;
const timer = monitor.timer(timerName);
try {
const result = await handler(job);
monitor.increment(requestsName);
return result;
} catch (err) {
monitor.increment(errorsName);
if ('sentryDsn' in config) {
Raven.captureException(err, {
extra: { err: `error processing job '${job.name}': ${err.message}` },
});
}
// Job is still failed
throw err;
} finally {
timer.stop();
}
});
if (process.env.NODE_ENV !== 'test') {
jobManager.startPolling();
}
return jobManager;
}
|
Add component form select on header filter | 'use strict'
import React from 'react'
import FormSelect from '../../components/form-select'
import SvgIcon from '../../components/svg-icon'
const HeaderFilter = () => (
<nav className='filter'>
<FormSelect
key='select-date'
icon={{
id: 'date',
label: 'Data'
}}
label='Escolha um mês'
options={[{
text: 'Escolha um mês',
value: ''
}, {
text: 'Janeiro',
value: 'Janeiro'
}, {
text: 'Fevereiro',
value: 'Fevereiro'
}, {
text: 'Março',
value: 'Março'
}]}
/>
<FormSelect
key='select-location'
icon={{
id: 'location',
label: 'Local'
}}
label='Escolha um estado'
options={[{
text: 'São Paulo',
value: 'São Paulo'
}, {
text: 'Acre',
value: 'Acre'
}, {
text: 'Paraná',
value: 'Paraná'
}]}
/>
<div className='search'>
<input className='form-control' type='search' placeholder='Busque por palavras chaves' />
<button className='search-btn' type='submit' role='button'>
<SvgIcon id='search' label='Search' />
</button>
</div>
</nav>
)
export default HeaderFilter
| 'use strict'
import React from 'react'
import SvgIcon from '../../components/svg-icon'
const HeaderFilter = () => (
<nav className='filter'>
<div className='form-select'>
<SvgIcon id='date' label='Data' />
<label className='sr-only'>Escolha um mês</label>
<select>
<option>Escolha um mês</option>
<option>Janeiro</option>
<option>Fevereiro</option>
<option>Março</option>
</select>
</div>
<div className='form-select'>
<SvgIcon id='location' label='Local' />
<label className='sr-only'>Escolha um estado</label>
<select>
<option>Escolha um estado</option>
<option>São Paulo</option>
<option>Acre</option>
<option>Paraná</option>
</select>
</div>
<div className='search'>
<input className='form-control' type='search' placeholder='Busque por palavras chaves' />
<button className='search-btn' type='submit' role='button'>
<SvgIcon id='search' label='Search' />
</button>
</div>
</nav>
)
export default HeaderFilter
|
Fix possible undefined methods in inherited classes | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib\Hydrator\Filter;
use InvalidArgumentException;
use ReflectionException;
use ReflectionMethod;
use ReflectionParameter;
/**
* Filter that includes methods which have no parameters or only optional parameters
*/
class OptionalParametersFilter implements FilterInterface
{
/**
* Map of methods already analyzed
* by {@see \Zend\Stdlib\Hydrator\Filter\OptionalParametersFilter::filter()},
* cached for performance reasons
*
* @var bool[]
*/
protected static $propertiesCache = array();
/**
* {@inheritDoc}
*/
public function filter($property)
{
if (isset(static::$propertiesCache[$property])) {
return static::$propertiesCache[$property];
}
try {
$reflectionMethod = new ReflectionMethod($property);
} catch (ReflectionException $exception) {
throw new InvalidArgumentException(sprintf('Method %s doesn\'t exist', $property));
}
$mandatoryParameters = array_filter(
$reflectionMethod->getParameters(),
function (ReflectionParameter $parameter) {
return ! $parameter->isOptional();
}
);
return static::$propertiesCache[$property] = empty($mandatoryParameters);
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib\Hydrator\Filter;
use InvalidArgumentException;
use ReflectionException;
use ReflectionMethod;
use ReflectionParameter;
/**
* Filter that includes methods which have no parameters or only optional parameters
*/
class OptionalParametersFilter implements FilterInterface
{
/**
* Map of methods already analyzed
* by {@see \Zend\Stdlib\Hydrator\Filter\OptionalParametersFilter::filter()},
* cached for performance reasons
*
* @var bool[]
*/
private static $propertiesCache = array();
/**
* {@inheritDoc}
*/
public function filter($property)
{
if (isset(static::$propertiesCache[$property])) {
return static::$propertiesCache[$property];
}
try {
$reflectionMethod = new ReflectionMethod($property);
} catch (ReflectionException $exception) {
throw new InvalidArgumentException(sprintf('Method %s doesn\'t exist', $property));
}
$mandatoryParameters = array_filter(
$reflectionMethod->getParameters(),
function (ReflectionParameter $parameter) {
return ! $parameter->isOptional();
}
);
return static::$propertiesCache[$property] = empty($mandatoryParameters);
}
}
|
Use empty message instead None. | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCase):
def test_sending_a_order_related_messages(self):
email = '[email protected]'
user = User.objects.create_user('testuser', email,
'somesimplepassword')
order_number = '12345'
order = create_order(number=order_number, user=user)
et = CommunicationEventType.objects.create(code="ORDER_PLACED",
name="Order Placed",
category="Order related")
messages = et.get_messages({
'order': order,
'lines': order.lines.all()
})
self.assertIn(order_number, messages['body'])
self.assertIn(order_number, messages['html'])
dispatcher = Dispatcher()
dispatcher.dispatch_order_messages(order, messages, et)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn(order_number, message.body)
# test sending messages to emails without account and text body
messages['body'] = ''
dispatcher.dispatch_direct_messages(email, messages)
self.assertEqual(len(mail.outbox), 2)
| from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCase):
def test_sending_a_order_related_messages(self):
email = '[email protected]'
user = User.objects.create_user('testuser', email,
'somesimplepassword')
order_number = '12345'
order = create_order(number=order_number, user=user)
et = CommunicationEventType.objects.create(code="ORDER_PLACED",
name="Order Placed",
category="Order related")
messages = et.get_messages({
'order': order,
'lines': order.lines.all()
})
self.assertIn(order_number, messages['body'])
self.assertIn(order_number, messages['html'])
dispatcher = Dispatcher()
dispatcher.dispatch_order_messages(order, messages, et)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn(order_number, message.body)
# test sending messages to emails without account and text body
messages['body'] = None
dispatcher.dispatch_direct_messages(email, messages)
self.assertEqual(len(mail.outbox), 2)
|
Fix source url to cache | let doCache = false;
let CACHE_NAME = 'quickbill-cache-v1';
let urlsToCache = [
'/',
'./assets/css/styles.css',
'./assets/images/*',
'./dist/index-bundle.js'
];
self.addEventListener("activate", event => {
const cacheWhiteList = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!cacheWhiteList.includes(key)) {
console.log('Deleting Cache: ' + key);
return caches.delete(key);
}
}))
)
);
});
self.addEventListener("install", function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch("manifest.json")
.then(resp => {
resp.json();
})
.then(() => {
cache.addAll(urlsToCache);
console.log('cached');
})
})
)
}
})
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
}); | let doCache = false;
let CACHE_NAME = 'quickbill-cache-v1';
let urlsToCache = [
'/',
'./assets/styles/css/styles.css',
'./assets/styles/images/*',
'./dist/index-bundle.js'
];
self.addEventListener("activate", event => {
const cacheWhiteList = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!cacheWhiteList.includes(key)) {
console.log('Deleting Cache: ' + key);
return caches.delete(key);
}
}))
)
);
});
self.addEventListener("install", function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch("manifest.json")
.then(resp => {
resp.json();
})
.then(() => {
cache.addAll(urlsToCache);
console.log('cached');
})
})
)
}
})
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
}); |
Add currency's symbol to dashboard | @extends('layout')
@section('body')
<h1>Dashboard</h1>
<div class="box spacing-bottom-large">
<div class="box__section">
<span style="font-size: 18px;">Earnings</span>
</div>
<table class="box__section">
<tbody>
@foreach (Auth::user()->earnings as $earning)
<tr>
<td>{{ $earning->description }}</td>
<td>{{ Auth::user()->currency->symbol }} {{ $earning->amount }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="box">
<div class="box__section">
<span style="font-size: 18px;">Spendings</span>
</div>
<table class="box__section">
<tbody>
@foreach (Auth::user()->spendings as $spending)
<tr>
<td>{{ $spending->description }}</td>
<td>{{ Auth::user()->currency->symbol }} {{ $spending->amount }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
| @extends('layout')
@section('body')
<h1>Dashboard</h1>
<div class="box spacing-bottom-large">
<div class="box__section">
<span style="font-size: 18px;">Earnings</span>
</div>
<table class="box__section">
<tbody>
@foreach (Auth::user()->earnings as $earning)
<tr>
<td>{{ $earning->description }}</td>
<td>{{ $earning->amount }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="box">
<div class="box__section">
<span style="font-size: 18px;">Spendings</span>
</div>
<table class="box__section">
<tbody>
@foreach (Auth::user()->spendings as $spending)
<tr>
<td>{{ $spending->description }}</td>
<td>{{ $spending->amount }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
|
Add nose to list of test requirements. | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='nova_limits',
version='0.5.2',
author='Kevin L. Mitchell',
author_email='[email protected]',
description="Nova-specific rate-limit class for turnstile",
license='Apache License (2.0)',
py_modules=['nova_limits'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Paste',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
url='https://github.com/klmitch/nova_limits',
long_description=read('README.rst'),
entry_points={
'console_scripts': [
'limit_class = nova_limits:limit_class',
],
},
install_requires=[
'argparse',
'msgpack-python',
'nova',
'turnstile',
],
tests_require=[
'mox',
'nose',
'unittest2>=0.5.1',
],
)
| import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='nova_limits',
version='0.5.2',
author='Kevin L. Mitchell',
author_email='[email protected]',
description="Nova-specific rate-limit class for turnstile",
license='Apache License (2.0)',
py_modules=['nova_limits'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Paste',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
url='https://github.com/klmitch/nova_limits',
long_description=read('README.rst'),
entry_points={
'console_scripts': [
'limit_class = nova_limits:limit_class',
],
},
install_requires=[
'argparse',
'msgpack-python',
'nova',
'turnstile',
],
tests_require=[
'mox',
'unittest2>=0.5.1',
],
)
|
Fix error propagation on feed fetching. | var feedRead = require('feed-read');
var readabilitySax = require('readabilitySAX');
var _url = require('url');
function fetchFeed(url, cb) {
console.log('[.] Fetching feed: ' + url);
feedRead(url, function(err, articles) {
if (err) {
console.error('[x] Unable to fetch feed: ' + url, err);
cb(err);
} else {
var articlesList = [];
articles.forEach(function (article) {
// append link to feed host if link doesn't contain protocol
if (!article.link.match(/^http/)) {
if (!article.link.match(/^\//)) {
article.link = '/' + article.link;
}
elems = _url.parse(url);
article.link = url.replace(new RegExp(elems.path), '') + article.link;
}
articlesList.push({
url : article.link,
title: article.title
});
});
cb(null, articlesList);
}
});
}
function fetchArticle(url, cb) {
console.log('[.] Fetching article: ' + url);
readabilitySax.get(url, function (result) {
cb({
url : url,
source : _url.parse(url).hostname,
title : result.title,
content: result.html
});
});
}
exports.fetchFeed = fetchFeed;
exports.fetchArticle = fetchArticle; | var feedRead = require('feed-read');
var readabilitySax = require('readabilitySAX');
var _url = require('url');
function fetchFeed(url, cb) {
console.log('[.] Fetching feed: ' + url);
feedRead(url, function(err, articles) {
if (err) {
console.error('[x] Unable to fetch feed: ' + url, err);
cb();
} else {
var articlesList = [];
articles.forEach(function (article) {
// append link to feed host if link doesn't contain protocol
if (!article.link.match(/^http/)) {
if (!article.link.match(/^\//)) {
article.link = '/' + article.link;
}
elems = _url.parse(url);
article.link = url.replace(new RegExp(elems.path), '') + article.link;
}
articlesList.push({
url : article.link,
title: article.title
});
});
cb(null, articlesList);
}
});
}
function fetchArticle(url, cb) {
console.log('[.] Fetching article: ' + url);
readabilitySax.get(url, function (result) {
cb({
url : url,
source : _url.parse(url).hostname,
title : result.title,
content: result.html
});
});
}
exports.fetchFeed = fetchFeed;
exports.fetchArticle = fetchArticle; |
Add method to calculate count issues by label | <?php
namespace Bap\Bundle\IssueBundle\Entity\Repository;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityRepository;
/**
* Class IssueRepository
* @package Bap\Bundle\IssueBundle\Entity\Repository
*/
class IssueRepository extends EntityRepository
{
public function getIssuesByStatus()
{
$items = $this->getCountIssuesByLabel();
$result = [];
while($item = array_pop($items)) {
$key = $item['label'];
$count = $item['count_issues'];
$result[$key] = [
'count' => $count
];
}
return $result;
}
public function getCountIssuesByLabel()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select(['COUNT(issue.id) as count_issues', 'workflowStep.label'])
->from('OroWorkflowBundle:WorkflowStep', 'workflowStep')
->leftJoin('workflowStep.definition', 'definition')
->leftJoin(
'BapIssueBundle:Issue',
'issue',
'WITH',
'issue.workflowStep = workflowStep AND definition.name = :d_name'
)
->andWhere('')
->groupBy('workflowStep.label')
->orderBy('cnt')
->setParameter('d_name', 'issue_flow');
return $qb
->getQuery()
->getResult(
AbstractQuery::HYDRATE_SIMPLEOBJECT
);
}
} | <?php
namespace Bap\Bundle\IssueBundle\Entity\Repository;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityRepository;
/**
* Class IssueRepository
* @package Bap\Bundle\IssueBundle\Entity\Repository
*/
class IssueRepository extends EntityRepository
{
public function getIssuesByStatus()
{
$result = $this->getFullEntityList();
}
public function getFullEntityList()
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select(['COUNT(issue.id) as cnt', 'workflowStep.label'])
->from('OroWorkflowBundle:WorkflowStep', 'workflowStep')
->leftJoin('workflowStep.definition', 'definition')
->leftJoin(
'BapIssueBundle:Issue',
'issue',
'WITH',
'issue.workflowStep = workflowStep AND definition.name = :d_name'
)
->andWhere('')
->groupBy('workflowStep.label')
->orderBy('cnt')
->setParameter('d_name', 'issue_flow');
return $qb
->getQuery()
->getResult(
AbstractQuery::HYDRATE_SIMPLEOBJECT
);
}
} |
BAP-3749: Disable screen for maintenance mode - show popup dialog with overlay instead of red message Maintanance Mode is ON
-fix unit tests | <?php
namespace Oro\Bundle\SyncBundle\Tests\Unit\EventListener;
use Oro\Bundle\SyncBundle\EventListener\MaintenanceListener;
class MaintenanceListenerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $topicPublisher;
protected function setUp()
{
$this->topicPublisher = $this->getMockBuilder('Oro\Bundle\SyncBundle\Wamp\TopicPublisher')
->disableOriginalConstructor()
->getMock();
}
protected function tearDown()
{
unset($this->topicPublisher);
}
public function testOnModeOn()
{
$this->topicPublisher
->expects($this->once())
->method('send')
->with('oro/maintenance', array('isOn' => true));
/** @var MaintenanceListener $publisher */
$publisher = new MaintenanceListener($this->topicPublisher);
$publisher->onModeOn();
}
public function testOnModeOff()
{
$this->topicPublisher
->expects($this->once())
->method('send')
->with('oro/maintenance', array('isOn' => false));
/** @var MaintenanceListener $publisher */
$publisher = new MaintenanceListener($this->topicPublisher);
$publisher->onModeOff();
}
}
| <?php
namespace Oro\Bundle\SyncBundle\Tests\Unit\EventListener;
use Oro\Bundle\SyncBundle\EventListener\MaintenanceListener;
class MaintenanceListenerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $topicPublisher;
protected function setUp()
{
$this->topicPublisher = $this->getMockBuilder('Oro\Bundle\SyncBundle\Wamp\TopicPublisher')
->disableOriginalConstructor()
->getMock();
}
protected function tearDown()
{
unset($this->topicPublisher);
}
public function testOnModeOn()
{
$this->topicPublisher
->expects($this->once())
->method('send')
->with('oro/maintenance', array('isOn' => true, 'msg' => 'Maintenance mode is ON'));
/** @var MaintenanceListener $publisher */
$publisher = new MaintenanceListener($this->topicPublisher);
$publisher->onModeOn();
}
public function testOnModeOff()
{
$this->topicPublisher
->expects($this->once())
->method('send')
->with('oro/maintenance', array('isOn' => false, 'msg' => 'Maintenance mode is OFF'));
/** @var MaintenanceListener $publisher */
$publisher = new MaintenanceListener($this->topicPublisher);
$publisher->onModeOff();
}
}
|
Fix integration test path to module | var gpio = require('../../rpi-gpio');
var async = require('async');
var assert = require('assert');
var sinon = require('sinon');
var message =
'Please ensure that your Raspberry Pi is set up with with physical pins ' +
'7 and 11 connected via a 1kΩ resistor (or similar) to make this test work'
console.log(message)
var writePin = 7
var readPin = 11
describe('rpi-gpio integration', function() {
var readValue;
var onChange = sinon.spy()
before(function(done) {
gpio.on('change', onChange);
async.waterfall([
function(next) {
gpio.setup(writePin, gpio.DIR_OUT, next)
},
function(next) {
gpio.setup(readPin, gpio.DIR_IN, gpio.EDGE_BOTH, next)
},
function(next) {
gpio.write(writePin, 1, next);
},
function(next) {
setTimeout(next, 100)
},
function(next) {
gpio.read(readPin, function(err, value) {
readValue = value;
next();
});
}
], function(err) {
done(err)
});
});
after(function(done) {
gpio.destroy(done)
});
it('should trigger the change listener', function() {
sinon.assert.calledOnce(onChange)
sinon.assert.calledWith(onChange, 11, true)
});
it('should set the read pin on', function() {
assert.equal(readValue, true)
});
});
| var gpio = require('rpi-gpio');
var async = require('async');
var assert = require('assert');
var sinon = require('sinon');
var message =
'Please ensure that your Raspberry Pi is set up with with physical pins ' +
'7 and 11 connected via a 1kΩ resistor (or similar) to make this test work'
console.log(message)
var writePin = 7
var readPin = 11
describe('rpi-gpio integration', function() {
var readValue;
var onChange = sinon.spy()
before(function(done) {
gpio.on('change', onChange);
async.waterfall([
function(next) {
gpio.setup(writePin, gpio.DIR_OUT, next)
},
function(next) {
gpio.setup(readPin, gpio.DIR_IN, gpio.EDGE_BOTH, next)
},
function(next) {
gpio.write(writePin, 1, next);
},
function(next) {
setTimeout(next, 100)
},
function(next) {
gpio.read(readPin, function(err, value) {
readValue = value;
next();
});
}
], function(err) {
done(err)
});
});
after(function(done) {
gpio.destroy(done)
});
it('should trigger the change listener', function() {
sinon.assert.calledOnce(onChange)
sinon.assert.calledWith(onChange, 11, true)
});
it('should set the read pin on', function() {
assert.equal(readValue, true)
});
});
|
Fix array notation to support PHP 5.3 | <?php
namespace Omnipay\Stripe\Message;
use Mockery as m;
use Omnipay\Tests\TestCase;
class AbstractRequestTest extends TestCase
{
public function testSendDataSetsApiVersionIfPresent_Mockery()
{
$apiVersion = '2014-10-12';
$eventDispatcher = m::mock('\Symfony\Component\EventDispatcher\EventDispatcherInterface')
->shouldReceive('addListener')->getMock();
$response = m::mock('\Guzzle\Http\Message\Response')->shouldReceive('json')->getMock();
$request = $this->getMockRequest()
->shouldReceive('setHeader')->once()->withArgs(array('Authorization', 'Basic Og=='))
->shouldReceive('setHeader')->once()->withArgs(array('Stripe-Version', $apiVersion))
->shouldReceive('send')->andReturn($response)
->getMock();
$httpClient = m::mock('Guzzle\Http\ClientInterface')
->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher)
->shouldReceive('createRequest')->andReturn($request)
->getMock();
$request = m::mock('\Omnipay\Stripe\Message\AbstractRequest[getEndPoint,getApiVersion]', array($httpClient, $this->getHttpRequest()));
$request->shouldReceive('getApiVersion')->andReturn($apiVersion);
$request->shouldReceive('getEndpoint')->andReturn('foo');
$request->sendData(array('foo' => 'bar'));
}
} | <?php
namespace Omnipay\Stripe\Message;
use Mockery as m;
use Omnipay\Tests\TestCase;
class AbstractRequestTest extends TestCase
{
public function testSendDataSetsApiVersionIfPresent_Mockery()
{
$apiVersion = '2014-10-12';
$eventDispatcher = m::mock('\Symfony\Component\EventDispatcher\EventDispatcherInterface')
->shouldReceive('addListener')->getMock();
$response = m::mock('\Guzzle\Http\Message\Response')->shouldReceive('json')->getMock();
$request = $this->getMockRequest()
->shouldReceive('setHeader')->once()->withArgs(['Authorization', 'Basic Og=='])
->shouldReceive('setHeader')->once()->withArgs(['Stripe-Version', $apiVersion])
->shouldReceive('send')->andReturn($response)
->getMock();
$httpClient = m::mock('Guzzle\Http\ClientInterface')
->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher)
->shouldReceive('createRequest')->andReturn($request)
->getMock();
$request = m::mock('\Omnipay\Stripe\Message\AbstractRequest[getEndPoint,getApiVersion]', array($httpClient, $this->getHttpRequest()));
$request->shouldReceive('getApiVersion')->andReturn($apiVersion);
$request->shouldReceive('getEndpoint')->andReturn('foo');
$request->sendData(array('foo' => 'bar'));
}
} |
Revert "The login handler now returns a response"
This reverts commit 90c53eebeece07cb7e8f54b757c509a364502022. | <?php
namespace Aureka\VBBundle\Handler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Aureka\VBBundle\VBUsers,
Aureka\VBBundle\VBSession;
use Aureka\VBBundle\Exception\VBUserException;
class LoginHandler implements AuthenticationSuccessHandlerInterface
{
private $userProvider;
private $session;
private $userToLogIn;
public function __construct(VBUsers $user_provider, VBSession $session)
{
$this->userProvider = $user_provider;
$this->session = $session;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
try {
$this->userToLogIn = $this->userProvider->load($this->session, $user->getUsername());
} catch (VBUserException $e) {
$this->userToLogIn = $this->userProvider->create($this->session, $user->getUsername(), $user->getPassword());
}
}
public function onKernelResponse(FilterResponseEvent $event)
{
if (!is_null($this->userToLogIn)) {
$this->session->login($event->getResponse());
$this->userProvider->updateSession($this->session);
$this->userToLogIn = null;
}
}
}
| <?php
namespace Aureka\VBBundle\Handler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Aureka\VBBundle\VBUsers,
Aureka\VBBundle\VBSession;
use Aureka\VBBundle\Exception\VBUserException;
class LoginHandler implements AuthenticationSuccessHandlerInterface
{
private $userProvider;
private $session;
private $userToLogIn;
public function __construct(VBUsers $user_provider, VBSession $session)
{
$this->userProvider = $user_provider;
$this->session = $session;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
try {
$this->userToLogIn = $this->userProvider->load($this->session, $user->getUsername());
} catch (VBUserException $e) {
$this->userToLogIn = $this->userProvider->create($this->session, $user->getUsername(), $user->getPassword());
}
return new RedirectResponse('/');
}
public function onKernelResponse(FilterResponseEvent $event)
{
if (!is_null($this->userToLogIn)) {
$this->session->login($event->getResponse());
$this->userProvider->updateSession($this->session);
$this->userToLogIn = null;
}
}
}
|
Fix order sorting to prevent incorrect order number generation.
See https://github.com/Sylius/Sylius/pull/631 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\OrderBundle\Doctrine\ORM;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Bundle\OrderBundle\Repository\OrderRepositoryInterface;
/**
* Order repository.
*
* @author Paweł Jędrzejewski <[email protected]>
*/
class OrderRepository extends EntityRepository implements OrderRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function findRecentOrders($amount = 10)
{
$queryBuilder = $this->getQueryBuilder();
$this->_em->getFilters()->disable('softdeleteable');
return $queryBuilder
->andWhere($queryBuilder->expr()->isNotNull('o.completedAt'))
->setMaxResults($amount)
->orderBy('o.completedAt', 'desc')
->getQuery()
->getResult()
;
}
/**
* {@inheritdoc}
*/
protected function getQueryBuilder()
{
return parent::getQueryBuilder()
->leftJoin('o.items', 'item')
->addSelect('item')
;
}
/**
* {@inheritdoc}
*/
protected function getAlias()
{
return 'o';
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\OrderBundle\Doctrine\ORM;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
use Sylius\Bundle\OrderBundle\Repository\OrderRepositoryInterface;
/**
* Order repository.
*
* @author Paweł Jędrzejewski <[email protected]>
*/
class OrderRepository extends EntityRepository implements OrderRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function findRecentOrders($amount = 10)
{
$queryBuilder = $this->getQueryBuilder();
$this->_em->getFilters()->disable('softdeleteable');
return $queryBuilder
->andWhere($queryBuilder->expr()->isNotNull('o.completedAt'))
->setMaxResults($amount)
->orderBy('o.id', 'desc')
->getQuery()
->getResult()
;
}
/**
* {@inheritdoc}
*/
protected function getQueryBuilder()
{
return parent::getQueryBuilder()
->leftJoin('o.items', 'item')
->addSelect('item')
;
}
/**
* {@inheritdoc}
*/
protected function getAlias()
{
return 'o';
}
}
|
Fix migration for model verbose name changes | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ADGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(db_index=True, max_length=200)),
('display_name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='ADGroupMapping',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')),
],
options={
'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings'
},
),
migrations.AlterUniqueTogether(
name='adgroupmapping',
unique_together=set([('group', 'ad_group')]),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ADGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(db_index=True, max_length=200)),
('display_name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='ADGroupMapping',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')),
],
options={
'verbose_name': 'AD Group Mapping',
},
),
migrations.AlterUniqueTogether(
name='adgroupmapping',
unique_together=set([('group', 'ad_group')]),
),
]
|
Add support for custom serializer | <?php
namespace Bridge\HttpApi\Worker;
use Bridge\HttpApi\Serializer\PathDenormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
use Transfer\Worker\WorkerInterface;
class SerializationWorker implements WorkerInterface
{
/**
* @var array
*/
private $deserialization;
/**
* @var array
*/
private $source;
/**
* @param array $deserialization
* @param array $source
*/
public function __construct($deserialization, $source)
{
$this->deserialization = $deserialization;
$this->source = $source;
}
/**
* {@inheritdoc}
*/
public function handle($object)
{
if (isset($this->deserialization['serializer'])) {
$serializer = $this->deserialization['serializer'];
} else {
$serializer = $this->getDefaultSerializer();
}
$object = $serializer->deserialize(
$object,
$this->deserialization['type'],
$this->source['format']
);
return $object;
}
private function getDefaultSerializer()
{
$normalizers = array();
$normalizers[] = new GetSetMethodNormalizer();
if (isset($this->deserialization['path'])) {
$normalizers[] = new PathDenormalizer($this->deserialization['path']);
}
$normalizers[] = new ArrayDenormalizer();
$encoders = array(new JsonEncoder());
$serializer = new Serializer($normalizers, $encoders);
return $serializer;
}
}
| <?php
namespace Bridge\HttpApi\Worker;
use Bridge\HttpApi\Serializer\PathDenormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
use Transfer\Worker\WorkerInterface;
class SerializationWorker implements WorkerInterface
{
/**
* @var array
*/
private $deserialization;
/**
* @var array
*/
private $source;
/**
* @param array $deserialization
* @param array $source
*/
public function __construct($deserialization, $source)
{
$this->deserialization = $deserialization;
$this->source = $source;
}
/**
* {@inheritdoc}
*/
public function handle($object)
{
$normalizers = array();
$normalizers[] = new GetSetMethodNormalizer();
if (isset($this->deserialization['path'])) {
$normalizers[] = new PathDenormalizer($this->deserialization['path']);
}
$normalizers[] = new ArrayDenormalizer();
$encoders = array(new JsonEncoder());
$serializer = new Serializer($normalizers, $encoders);
$object = $serializer->deserialize(
$object,
$this->deserialization['type'],
$this->source['format']
);
return $object;
}
}
|
Add new constructor for logic manager | package seedu.jobs.logic;
import java.io.IOException;
import java.util.logging.Logger;
import javafx.collections.ObservableList;
import seedu.jobs.commons.core.ComponentManager;
import seedu.jobs.commons.core.LogsCenter;
import seedu.jobs.logic.calendar.CalendarManager;
import seedu.jobs.logic.commands.Command;
import seedu.jobs.logic.commands.CommandResult;
import seedu.jobs.logic.commands.exceptions.CommandException;
import seedu.jobs.logic.parser.Parser;
import seedu.jobs.model.Model;
import seedu.jobs.model.task.ReadOnlyTask;
import seedu.jobs.storage.Storage;
import seedu.jobs.storage.StorageManager;
/**
* The main LogicManager of the app.
*/
public class LogicManager extends ComponentManager implements Logic {
private final Logger logger = LogsCenter.getLogger(LogicManager.class);
private final Model model;
private final Parser parser;
private final CalendarManager calendar;
public LogicManager(Model model, Storage storage, CalendarManager calendar) {
this.model = model;
this.parser = new Parser();
this.calendar = calendar;
}
public LogicManager(Model model, StorageManager storageManager) {
this.model = model;
this.parser = new Parser();
}
@Override
public CommandResult execute(String commandText) throws CommandException, IOException {
logger.info("----------------[USER COMMAND][" + commandText + "]");
Command command = parser.parseCommand(commandText);
command.setData(model);
command.setCalendar(calendar);
return command.execute();
}
@Override
public ObservableList<ReadOnlyTask> getFilteredTaskList() {
return model.getFilteredTaskList();
}
}
| package seedu.jobs.logic;
import java.io.IOException;
import java.util.logging.Logger;
import javafx.collections.ObservableList;
import seedu.jobs.commons.core.ComponentManager;
import seedu.jobs.commons.core.LogsCenter;
import seedu.jobs.logic.calendar.CalendarManager;
import seedu.jobs.logic.commands.Command;
import seedu.jobs.logic.commands.CommandResult;
import seedu.jobs.logic.commands.exceptions.CommandException;
import seedu.jobs.logic.parser.Parser;
import seedu.jobs.model.Model;
import seedu.jobs.model.task.ReadOnlyTask;
import seedu.jobs.storage.Storage;
/**
* The main LogicManager of the app.
*/
public class LogicManager extends ComponentManager implements Logic {
private final Logger logger = LogsCenter.getLogger(LogicManager.class);
private final Model model;
private final Parser parser;
private final CalendarManager calendar;
public LogicManager(Model model, Storage storage, CalendarManager calendar) {
this.model = model;
this.parser = new Parser();
this.calendar = calendar;
}
@Override
public CommandResult execute(String commandText) throws CommandException, IOException {
logger.info("----------------[USER COMMAND][" + commandText + "]");
Command command = parser.parseCommand(commandText);
command.setData(model);
command.setCalendar(calendar);
return command.execute();
}
@Override
public ObservableList<ReadOnlyTask> getFilteredTaskList() {
return model.getFilteredTaskList();
}
}
|
[cli] Print more complete error message | #!/usr/bin/env node
var parseArgs = require('minimist');
var gonzales = require('..');
var fs = require('fs');
var path = require('path');
var options = getOptions();
process.stdin.isTTY ? processFile(options._[0]) : processSTDIN();
function getOptions() {
var parserOptions = {
boolean: ['silent'],
alias: {
syntax: 's',
context: 'c'
}
};
return parseArgs(process.argv.slice(2), parserOptions);
}
function processSTDIN() {
var input = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (data) {
input += data;
});
process.stdin.on('end', function () {
processInputData(input);
});
}
function processFile(file) {
if (!file) process.exit(0);
if (!options.syntax) options.syntax = path.extname(file).substring(1);
var css = fs.readFileSync(file, 'utf-8').trim();
processInputData(css);
}
function processInputData(input) {
try {
var ast = gonzales.parse(input, {
syntax: options.syntax,
rule: options.context
});
process.stdout.write(ast.toJson());
process.exit(0);
} catch (e) {
if (!options.silent) process.stderr.write(e.toString());
process.exit(1);
}
}
| #!/usr/bin/env node
var parseArgs = require('minimist');
var gonzales = require('..');
var fs = require('fs');
var path = require('path');
var options = getOptions();
process.stdin.isTTY ? processFile(options._[0]) : processSTDIN();
function getOptions() {
var parserOptions = {
boolean: ['silent'],
alias: {
syntax: 's',
context: 'c'
}
};
return parseArgs(process.argv.slice(2), parserOptions);
}
function processSTDIN() {
var input = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (data) {
input += data;
});
process.stdin.on('end', function () {
processInputData(input);
});
}
function processFile(file) {
if (!file) process.exit(0);
if (!options.syntax) options.syntax = path.extname(file).substring(1);
var css = fs.readFileSync(file, 'utf-8').trim();
processInputData(css);
}
function processInputData(input) {
try {
var ast = gonzales.parse(input, {
syntax: options.syntax,
rule: options.context
});
process.stdout.write(ast.toJson());
process.exit(0);
} catch (e) {
if (!options.silent) process.stderr.write(e.message);
process.exit(1);
}
}
|
Allow double click zoom when map is not frozen | import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={!frozen}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
| import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={false}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
|
test: Clear caches in test item teardown
Rather than relying on the user manually clearing the COFS function
cache and linear problem cache, clear them in the teardown step of each
test. | import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
# Print a progress "." once a minute when running in travis mode
# This is an attempt to stop travis timing the builds out due to lack
# of output.
progress_process = None
def pytest_configure(config):
global progress_process
if config.getoption("--travis") and progress_process is None:
import multiprocessing
import py
terminal = py.io.TerminalWriter()
def writer():
import time
while True:
terminal.write("still alive\n")
time.sleep(60)
progress_process = multiprocessing.Process(target=writer)
progress_process.daemon = True
progress_process.start()
def pytest_unconfigure(config):
global progress_process
if config.getoption("--travis") and progress_process is not None:
progress_process.terminate()
def pytest_runtest_teardown(item, nextitem):
"""Clear COFS caches after running a test"""
from cofs.utility import linProblemCache, tmpFunctionCache
linProblemCache.clear()
tmpFunctionCache.clear()
| import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
# Print a progress "." once a minute when running in travis mode
# This is an attempt to stop travis timing the builds out due to lack
# of output.
progress_process = None
def pytest_configure(config):
global progress_process
if config.getoption("--travis") and progress_process is None:
import multiprocessing
import py
terminal = py.io.TerminalWriter()
def writer():
import time
while True:
terminal.write("still alive\n")
time.sleep(60)
progress_process = multiprocessing.Process(target=writer)
progress_process.daemon = True
progress_process.start()
def pytest_unconfigure(config):
global progress_process
if config.getoption("--travis") and progress_process is not None:
progress_process.terminate()
|
Fix client IP on dashboard | <?php
namespace App\Controllers;
use Illuminate\Http\Request;
use App\Libs\Controller;
class DashboardController extends Controller{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$admin_logo = $this->request->settings['admin_logo'];
$this->view->title(trans('dashboard.title'));
return $this->view->render("dashboard/index",[
'domain' => $this->request->getHost(),
'server_ip' => isset($_SERVER['SERVER_ADDR'])? $_SERVER['SERVER_ADDR']: "unknown",
'client_ip' => $this->request->ip(),
'blogposts' => \App\Model\Blogpost::count(),
'users' => \App\Model\User::count(),
'visits' => \App\Model\Visits::count(),
'admin_logo' => ($admin_logo!="" && file_exists("storage/images/logos/".$admin_logo))? "storage/images/logos/".$admin_logo : \Config::get('horizontcms.admin_logo'),
'disk_space' => @(disk_free_space("/")/disk_total_space("/"))*100,
'upgrade' => $this->request->settings['auto_upgrade_check']==1 && \Auth::user()->hasPermission('settings')? \App\Model\SystemUpgrade::checkUpgrade(): NULL,
]);
}
public function unauthorized(){
$this->view->title('Access denied');
return $this->view->render('errors/unauthorized');
}
}
| <?php
namespace App\Controllers;
use Illuminate\Http\Request;
use App\Libs\Controller;
class DashboardController extends Controller{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$admin_logo = $this->request->settings['admin_logo'];
$this->view->title(trans('dashboard.title'));
return $this->view->render("dashboard/index",[
'domain' => $this->request->getHost(),
'server_ip' => isset($_SERVER['SERVER_ADDR'])? $_SERVER['SERVER_ADDR']: "unknown",
'client_ip' => $this->request->ip,
'blogposts' => \App\Model\Blogpost::count(),
'users' => \App\Model\User::count(),
'visits' => \App\Model\Visits::count(),
'admin_logo' => ($admin_logo!="" && file_exists("storage/images/logos/".$admin_logo))? "storage/images/logos/".$admin_logo : \Config::get('horizontcms.admin_logo'),
'disk_space' => @(disk_free_space("/")/disk_total_space("/"))*100,
'upgrade' => $this->request->settings['auto_upgrade_check']==1 && \Auth::user()->hasPermission('settings')? \App\Model\SystemUpgrade::checkUpgrade(): NULL,
]);
}
public function unauthorized(){
$this->view->title('Access denied');
return $this->view->render('errors/unauthorized');
}
}
|
Add config for disabling tools links | <?php
namespace Slate\UI;
use Slate;
class Tools implements ILinksSource
{
public static $enabled = true;
public static $weight = -500;
public static $tools = [];
public static function __classLoaded()
{
// append legacy manage/web tools
if (!empty(Slate::$manageTools)) {
static::appendtools(Slate::$manageTools);
}
if (!empty(Slate::$webTools)) {
static::appendtools(Slate::$webTools);
}
}
public static function appendTools(array $tools)
{
foreach ($tools AS $key => $value) {
if (
is_array($value) &&
!empty(static::$tools[$key]) &&
is_array(static::$tools[$key])
) {
static::$tools[$key] = array_merge(static::$tools[$key], $value);
} else {
static::$tools[$key] = $value;
}
}
}
public static function getLinks($context = null)
{
if (!static::$enabled || empty($_SESSION['User'])) {
return [];
}
return [
'Tools' => [
'_icon' => 'tools',
'_weight' => -500,
'_children' => static::$tools
]
];
}
} | <?php
namespace Slate\UI;
use Slate;
class Tools implements ILinksSource
{
public static $weight = -500;
public static $tools = [];
public static function __classLoaded()
{
// append legacy manage/web tools
if (!empty(Slate::$manageTools)) {
static::appendtools(Slate::$manageTools);
}
if (!empty(Slate::$webTools)) {
static::appendtools(Slate::$webTools);
}
}
public static function appendTools(array $tools)
{
foreach ($tools AS $key => $value) {
if (
is_array($value) &&
!empty(static::$tools[$key]) &&
is_array(static::$tools[$key])
) {
static::$tools[$key] = array_merge(static::$tools[$key], $value);
} else {
static::$tools[$key] = $value;
}
}
}
public static function getLinks($context = null)
{
return [
'Tools' => empty($_SESSION['User']) ? null : [
'_icon' => 'tools',
'_weight' => -500,
'_children' => static::$tools
]
];
}
} |
Return exception as error message | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
abort = base.abort
BaseController = base.BaseController
class RequestDataController(BaseController):
def send_request(self):
'''Send mail to resource owner.
:param data: Contact form data.
:type data: object
:rtype: json
'''
print "Entered"
context = {'model': model, 'session': model.Session,
'user': c.user, 'auth_user_obj': c.userobj}
try:
if p.toolkit.request.method == 'POST':
data = dict(toolkit.request.POST)
content = data["message_content"]
to = data['email_address']
mail_subject = "Request data"
get_action('requestdata_request_create')(context, data)
except NotAuthorized:
abort(403, _('Unauthorized to update this dataset.'))
except ValidationError as e:
error = {
'success': False,
'error': {
'message': str(e)
}
}
return json.dumps(error)
response_message = emailer.send_email(content, to, mail_subject)
return json.dumps(response_message) | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
abort = base.abort
BaseController = base.BaseController
class RequestDataController(BaseController):
def send_request(self):
'''Send mail to resource owner.
:param data: Contact form data.
:type data: object
:rtype: json
'''
print "Entered"
context = {'model': model, 'session': model.Session,
'user': c.user, 'auth_user_obj': c.userobj}
try:
if p.toolkit.request.method == 'POST':
data = dict(toolkit.request.POST)
content = data["message_content"]
to = data['email_address']
mail_subject = "Request data"
get_action('requestdata_request_create')(context, data)
except NotAuthorized:
abort(403, _('Unauthorized to update this dataset.'))
except ValidationError:
error = {
'success': False,
'error': {
'message': 'An error occurred while requesting the data.'
}
}
return json.dumps(error)
response_message = emailer.send_email(content, to, mail_subject)
return json.dumps(response_message) |
Fix case of Django dependency. Thanks Travis Swicegood. | from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_utils', '__init__.py')) as f:
for line in f:
if line.startswith('__version__ ='):
return line.split('=')[1].strip().strip('"\'')
setup(
name='django-model-utils',
version=get_version(),
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='[email protected]',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
install_requires=['Django>=1.4.2'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.4.2"],
test_suite='runtests.runtests'
)
| from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_utils', '__init__.py')) as f:
for line in f:
if line.startswith('__version__ ='):
return line.split('=')[1].strip().strip('"\'')
setup(
name='django-model-utils',
version=get_version(),
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='[email protected]',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
install_requires=['django>=1.4.2'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.4.2"],
test_suite='runtests.runtests'
)
|
Correct way to use get or create | import socket
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
class GooglebotMiddleware(object):
"""
Middleware to automatically log in the Googlebot with the user account 'googlebot'
"""
def process_request(self, request):
request.is_googlebot = False # Assume false, until proven
if request.user == AnonymousUser():
if request.META.get('HTTP_USER_AGENT'):
if 'Googlebot' in request.META['HTTP_USER_AGENT']:
try:
remote_ip = request.META['REMOTE_ADDR']
hostname = socket.gethostbyaddr(remote_ip)[0]
if hostname.endswith('googlebot.com'):
request.user, created = User.objects.get_or_create(username='googlebot') # login our googlebot user :)
request.is_googlebot = True
else:
# FAKE googlebot!!!!
request.is_googlebot = False
except Exception, e:
pass # Don't bring down the site
return None
| import socket
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
class GooglebotMiddleware(object):
"""
Middleware to automatically log in the Googlebot with the user account 'googlebot'
"""
def process_request(self, request):
request.is_googlebot = False # Assume false, until proven
if request.user == AnonymousUser():
if request.META.get('HTTP_USER_AGENT'):
if 'Googlebot' in request.META['HTTP_USER_AGENT']:
try:
remote_ip = request.META['REMOTE_ADDR']
hostname = socket.gethostbyaddr(remote_ip)[0]
if hostname.endswith('googlebot.com'):
request.user = User.objects.get_or_create(username='googlebot') # login our googlebot user :)
request.is_googlebot = True
else:
# FAKE googlebot!!!!
request.is_googlebot = False
except Exception, e:
pass # Don't bring down the site
return None
|
Add keyword to echo worker. | # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connections been established"""
self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config)
self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config,
self.handle_inbound_message)
def handle_inbound_message(self, message):
log.msg("Received: %s" % (message.payload,))
"""Reply to the message with the same content"""
data = message.payload
reply = {
'to_msisdn': data['from_msisdn'],
'from_msisdn': data['to_msisdn'],
'message': data['message'],
'id': data['transport_message_id'],
'transport_network_id': data['transport_network_id'],
'transport_keyword': data['transport_keyword'],
}
return self.publisher.publish_message(Message(**reply))
def stopWorker(self):
"""shutdown"""
pass
| # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connections been established"""
self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config)
self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config,
self.handle_inbound_message)
def handle_inbound_message(self, message):
log.msg("Received: %s" % (message.payload,))
"""Reply to the message with the same content"""
data = message.payload
reply = {
'to_msisdn': data['from_msisdn'],
'from_msisdn': data['to_msisdn'],
'message': data['message'],
'id': data['transport_message_id'],
'transport_network_id': data['transport_network_id'],
}
return self.publisher.publish_message(Message(**reply))
def stopWorker(self):
"""shutdown"""
pass
|
Remove php 7.1 `?` operator | <?php
declare(strict_types=1);
namespace Roave\Signature;
use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;
final class FileContentChecker implements CheckerInterface
{
/**
* @var EncoderInterface
*/
private $encoder;
/**
* @var HasherInterface
*/
private $hasher;
/**
* {@inheritDoc}
*/
public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
{
$this->encoder = $encoder;
$this->hasher = $hasher;
}
/**
* {@inheritDoc}
*/
public function check(string $phpCode)
{
if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
return false;
}
// @todo extract this logic for get rid of signature
$codeWithoutSignature = array_reduce(
explode(PHP_EOL, $phpCode),
function (string $carry = null, string $currentLine = null): string {
// if current line is the signature line, we just ignore it
if (preg_match('{Roave/Signature: (\w)}', $currentLine)) {
return $carry;
}
if (null === $carry) {
return $currentLine;
}
if (null !== $currentLine) {
return $carry . PHP_EOL . $currentLine;
}
return $carry;
}
);
return $this->encoder->verify($codeWithoutSignature, $matches[1]);
}
}
| <?php
declare(strict_types=1);
namespace Roave\Signature;
use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;
final class FileContentChecker implements CheckerInterface
{
/**
* @var EncoderInterface
*/
private $encoder;
/**
* @var HasherInterface
*/
private $hasher;
/**
* {@inheritDoc}
*/
public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
{
$this->encoder = $encoder;
$this->hasher = $hasher;
}
/**
* {@inheritDoc}
*/
public function check(string $phpCode)
{
if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
return false;
}
// @todo extract this logic for get rid of signature
$codeWithoutSignature = array_reduce(
explode(PHP_EOL, $phpCode),
function (?string $carry, ?string $currentLine): string {
// if current line is the signature line, we just ignore it
if (preg_match('{Roave/Signature: (\w)}', $currentLine)) {
return $carry;
}
if (null === $carry) {
return $currentLine;
}
if (null !== $currentLine) {
return $carry . PHP_EOL . $currentLine;
}
return $carry;
}
);
return $this->encoder->verify($codeWithoutSignature, $matches[1]);
}
}
|
Comment out file we dont need | <?php
namespace phpSmug;
//use phpSmug\Api\ApiInterface;
use phpSmug\Exception\InvalidArgumentException;
use phpSmug\Exception\BadMethodCallException;
use phpSmug\HttpClient\HttpClient;
use phpSmug\HttpClient\HttpClientInterface;
/**
* Simple yet very cool PHP SmugMug client
*
* @method Api\User user()
*
*/
class Client
{
/**
* @var array
*/
private $options = array(
'endpoint_url' => 'https://api.smugmug.com/api/v2/',
'user_agent' => 'phpSmug (http://phpsmug.com)',
'timeout' => 10,
'cache_dir' => null,
'api_key' => null,
);
/**
* The instance used to communicate with SmugMug
*
* @var HttpClient
*/
private $httpClient;
/**
* Instantiate a new SmugMug client
*
* @param null|HttpClientInterface $httpClient SmugMug http client
*/
public function __construct(HttpClientInterface $httpClient = null)
{
$this->httpClient = $httpClient;
}
/**
* @param string $name
*
* @return ApiInterface
*
* @throws InvalidArgumentException
*/
public function api($name)
{
switch ($name) {
case 'user':
$api = new Api\User($this);
break;
default:
throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
}
return $api;
}
}
?>
| <?php
namespace phpSmug;
use phpSmug\Api\ApiInterface;
use phpSmug\Exception\InvalidArgumentException;
use phpSmug\Exception\BadMethodCallException;
use phpSmug\HttpClient\HttpClient;
use phpSmug\HttpClient\HttpClientInterface;
/**
* Simple yet very cool PHP SmugMug client
*
* @method Api\User user()
*
*/
class Client
{
/**
* @var array
*/
private $options = array(
'endpoint_url' => 'https://api.smugmug.com/api/v2/',
'user_agent' => 'phpSmug (http://phpsmug.com)',
'timeout' => 10,
'cache_dir' => null,
'api_key' => null,
);
/**
* The instance used to communicate with SmugMug
*
* @var HttpClient
*/
private $httpClient;
/**
* Instantiate a new SmugMug client
*
* @param null|HttpClientInterface $httpClient SmugMug http client
*/
public function __construct(HttpClientInterface $httpClient = null)
{
$this->httpClient = $httpClient;
}
/**
* @param string $name
*
* @return ApiInterface
*
* @throws InvalidArgumentException
*/
public function api($name)
{
switch ($name) {
case 'user':
$api = new Api\User($this);
break;
default:
throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
}
return $api;
}
}
?>
|
Change node build target libraryTarget from AMD to UMD | const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const webpackMerge = require('webpack-merge');
const defaultConfig = {
target: 'node',
entry: {
'bundle.node': './src/index.js',
'bundle.node.min': './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'maps4news',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
],
},
devtool: 'source-map',
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
}),
new webpack.BannerPlugin(fs.readFileSync('LICENSE', 'ascii')),
],
};
module.exports = [
defaultConfig,
webpackMerge(defaultConfig, {
target: 'web',
entry: {
'bundle.web': './src/index.js',
'bundle.web.min': './src/index.js',
},
output: {
libraryTarget: 'window',
},
}),
];
| const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const webpackMerge = require('webpack-merge');
const defaultConfig = {
target: 'node',
entry: {
'bundle.node': './src/index.js',
'bundle.node.min': './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: 'maps4news',
libraryTarget: 'amd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
},
},
},
],
},
devtool: 'source-map',
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
}),
new webpack.BannerPlugin(fs.readFileSync('LICENSE', 'ascii')),
],
};
module.exports = [
defaultConfig,
webpackMerge(defaultConfig, {
target: 'web',
entry: {
'bundle.web': './src/index.js',
'bundle.web.min': './src/index.js',
},
output: {
libraryTarget: 'window',
},
}),
];
|
Clean shitty phpstorm comment :( | <?php
namespace Nats\tests\Unit;
use Nats\ConnectionOptions;
/**
* Class ConnectionOptionsTest
*/
class ConnectionOptionsTest extends \PHPUnit_Framework_TestCase
{
/**
* Tests Connection Options getters and setters. Only necessary for code coverage.
*
* @return void
*/
public function testSettersAndGetters()
{
$options = new ConnectionOptions();
$options
->setHost('host')
->setPort(4222)
->setUser('user')
->setPass('password')
->setLang('lang')
->setVersion('version')
->setVerbose(true)
->setPedantic(true)
->setReconnect(true);
$this->assertEquals('host', $options->getHost());
$this->assertEquals(4222, $options->getPort());
$this->assertEquals('user', $options->getUser());
$this->assertEquals('password', $options->getPass());
$this->assertEquals('lang', $options->getLang());
$this->assertEquals('version', $options->getVersion());
$this->assertTrue($options->isVerbose());
$this->assertTrue($options->isPedantic());
$this->assertTrue($options->isReconnect());
}
}
| <?php
/**
* Created by PhpStorm.
* User: isselguberna
* Date: 29/9/15
* Time: 23:48
*/
namespace Nats\tests\Unit;
use Nats\ConnectionOptions;
/**
* Class ConnectionOptionsTest
*/
class ConnectionOptionsTest extends \PHPUnit_Framework_TestCase
{
/**
* Tests Connection Options getters and setters. Only necessary for code coverage.
*
* @return void
*/
public function testSettersAndGetters()
{
$options = new ConnectionOptions();
$options
->setHost('host')
->setPort(4222)
->setUser('user')
->setPass('password')
->setLang('lang')
->setVersion('version')
->setVerbose(true)
->setPedantic(true)
->setReconnect(true);
$this->assertEquals('host', $options->getHost());
$this->assertEquals(4222, $options->getPort());
$this->assertEquals('user', $options->getUser());
$this->assertEquals('password', $options->getPass());
$this->assertEquals('lang', $options->getLang());
$this->assertEquals('version', $options->getVersion());
$this->assertTrue($options->isVerbose());
$this->assertTrue($options->isPedantic());
$this->assertTrue($options->isReconnect());
}
}
|
Update the team view when a team is joined | angular.module('reg')
.controller('TeamCtrl', [
'$scope',
'currentUser',
'settings',
'Utils',
'UserService',
'TEAM',
function($scope, currentUser, settings, Utils, UserService, TEAM){
// Get the current user's most recent data.
var Settings = settings.data;
$scope.regIsOpen = Utils.isRegOpen(Settings);
$scope.user = currentUser.data;
$scope.TEAM = TEAM;
function _populateTeammates() {
UserService
.getMyTeammates()
.success(function(users){
$scope.error = null;
$scope.teammates = users;
});
}
if ($scope.user.teamCode){
_populateTeammates();
}
$scope.joinTeam = function(){
UserService
.joinOrCreateTeam($scope.code)
.success(function(user){
$scope.error = null;
$scope.user = user;
_populateTeammates();
})
.error(function(res){
$scope.error = res.message;
});
};
$scope.leaveTeam = function(){
UserService
.leaveTeam()
.success(function(user){
$scope.error = null;
$scope.user = user;
$scope.teammates = [];
})
.error(function(res){
$scope.error = res.data.message;
});
};
}]);
| angular.module('reg')
.controller('TeamCtrl', [
'$scope',
'currentUser',
'settings',
'Utils',
'UserService',
'TEAM',
function($scope, currentUser, settings, Utils, UserService, TEAM){
// Get the current user's most recent data.
var Settings = settings.data;
$scope.regIsOpen = Utils.isRegOpen(Settings);
$scope.user = currentUser.data;
$scope.TEAM = TEAM;
if ($scope.user.teamCode){
UserService
.getMyTeammates()
.success(function(users){
$scope.error = null;
$scope.teammates = users;
});
}
$scope.joinTeam = function(){
UserService
.joinOrCreateTeam($scope.code)
.success(function(user){
$scope.error = null;
$scope.user = user;
_populateTeammates();
})
.error(function(res){
$scope.error = res.message;
});
};
$scope.leaveTeam = function(){
UserService
.leaveTeam()
.success(function(user){
$scope.error = null;
$scope.user = user;
$scope.teammates = [];
})
.error(function(res){
$scope.error = res.data.message;
});
};
}]);
|
Add a correct dir to sys.path, remove unused imports. | import os
import sys
from setuptools import setup
def read_version_string():
version = None
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, current_dir)
from log_formatters import __version__
version = __version__
sys.path.pop(0)
return version
setup(
name='log-formatters',
version=read_version_string(),
#long_description=open('README.rst').read() + '\n\n' +
#open('CHANGES.rst').read(),
packages=[
'log_formatters'
],
package_dir={
'log_formatters': 'log_formatters'
},
url='https://github.com/Kami/python-log-formatters/',
license='Apache License (2.0)',
author='Tomaz Muraus',
author_email='[email protected]',
description='A collection of useful Python log formatter classes.',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| import os
import sys
from os.path import join as pjoin
from setuptools import setup
from setuptools import Command
from subprocess import call
def read_version_string():
version = None
sys.path.insert(0, pjoin(os.getcwd()))
from log_formatters import __version__
version = __version__
sys.path.pop(0)
return version
setup(
name='log-formatters',
version=read_version_string(),
#long_description=open('README.rst').read() + '\n\n' +
#open('CHANGES.rst').read(),
packages=[
'log_formatters'
],
package_dir={
'log_formatters': 'log_formatters'
},
url='https://github.com/Kami/python-log-formatters/',
license='Apache License (2.0)',
author='Tomaz Muraus',
author_email='[email protected]',
description='A collection of useful Python log formatter classes.',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Fix tests for PHP 5.4 | <?php
namespace SimpleSAML\Test\Module\core\Auth;
use SimpleSAML\Module\core\Auth\UserPassOrgBase;
class UserPassOrgBaseTest extends \PHPUnit_Framework_TestCase
{
public function testRememberOrganizationEnabled()
{
$config = array(
'ldap:LDAPMulti',
'remember.organization.enabled' => true,
'remember.organization.checked' => false,
'my-org' => array(
'description' => 'My organization',
// The rest of the options are the same as those available for
// the LDAP authentication source.
'hostname' => 'ldap://ldap.myorg.com',
'dnpattern' => 'uid=%username%,ou=employees,dc=example,dc=org',
// Whether SSL/TLS should be used when contacting the LDAP server.
'enable_tls' => false,
)
);
// When PHP 5.4 support is dropped, replace with:
// $mockUserPassOrgBase = $this->getMockBuilder(\SimpleSAML\Module\core\Auth\UserPassOrgBase::class)
$mockUserPassOrgBase = $this->getMockBuilder(get_parent_class(new \SimpleSAML\Module\ldap\Auth\Source\LDAPMulti(array('AuthId' => 'my-org'), array())))
->setConstructorArgs(array(array('AuthId' => 'my-org'), &$config))
->setMethods(array())
->getMockForAbstractClass();
$this->assertTrue($mockUserPassOrgBase->getRememberOrganizationEnabled());
}
}
| <?php
namespace SimpleSAML\Test\Module\core\Auth;
use SimpleSAML\Module\core\Auth\UserPassOrgBase;
class UserPassOrgBaseTest extends \PHPUnit_Framework_TestCase
{
public function testRememberOrganizationEnabled()
{
$config = array(
'ldap:LDAPMulti',
'remember.organization.enabled' => true,
'remember.organization.checked' => false,
'my-org' => array(
'description' => 'My organization',
// The rest of the options are the same as those available for
// the LDAP authentication source.
'hostname' => 'ldap://ldap.myorg.com',
'dnpattern' => 'uid=%username%,ou=employees,dc=example,dc=org',
// Whether SSL/TLS should be used when contacting the LDAP server.
'enable_tls' => false,
)
);
$mockUserPassOrgBase = $this->getMockBuilder(\SimpleSAML\Module\core\Auth\UserPassOrgBase::class)
->setConstructorArgs(array(array('AuthId' => 'my-org'), &$config))
->setMethods(array())
->getMockForAbstractClass();
$this->assertTrue($mockUserPassOrgBase->getRememberOrganizationEnabled());
}
}
|
Remove BitVector import - Build fails | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
| import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
|
Fix for Database access not allowed, use the "django_db" mark to enable it. | from django.contrib.auth import get_user_model
from rest_framework_json_api import serializers
from rest_framework_json_api.renderers import JSONRenderer
pytestmark = pytest.mark.django_db
class ResourceSerializer(serializers.ModelSerializer):
class Meta:
fields = ('username',)
model = get_user_model()
def test_build_json_resource_obj():
resource = {
'pk': 1,
'username': 'Alice',
}
serializer = ResourceSerializer(data={'username': 'Alice'})
serializer.is_valid()
resource_instance = serializer.save()
output = {
'type': 'user',
'id': '1',
'attributes': {
'username': 'Alice'
},
}
assert JSONRenderer.build_json_resource_obj(
serializer.fields, resource, resource_instance, 'user') == output
def test_extract_attributes():
fields = {
'id': serializers.Field(),
'username': serializers.Field(),
'deleted': serializers.ReadOnlyField(),
}
resource = {'id': 1, 'deleted': None, 'username': 'jerel'}
expected = {
'username': 'jerel',
'deleted': None
}
assert sorted(JSONRenderer.extract_attributes(fields, resource)) == sorted(expected), 'Regular fields should be extracted'
assert sorted(JSONRenderer.extract_attributes(fields, {})) == sorted(
{'username': ''}), 'Should not extract read_only fields on empty serializer'
| from django.contrib.auth import get_user_model
from rest_framework_json_api import serializers
from rest_framework_json_api.renderers import JSONRenderer
class ResourceSerializer(serializers.ModelSerializer):
class Meta:
fields = ('username',)
model = get_user_model()
def test_build_json_resource_obj():
resource = {
'pk': 1,
'username': 'Alice',
}
serializer = ResourceSerializer(data={'username': 'Alice'})
serializer.is_valid()
resource_instance = serializer.save()
output = {
'type': 'user',
'id': '1',
'attributes': {
'username': 'Alice'
},
}
assert JSONRenderer.build_json_resource_obj(
serializer.fields, resource, resource_instance, 'user') == output
def test_extract_attributes():
fields = {
'id': serializers.Field(),
'username': serializers.Field(),
'deleted': serializers.ReadOnlyField(),
}
resource = {'id': 1, 'deleted': None, 'username': 'jerel'}
expected = {
'username': 'jerel',
'deleted': None
}
assert sorted(JSONRenderer.extract_attributes(fields, resource)) == sorted(expected), 'Regular fields should be extracted'
assert sorted(JSONRenderer.extract_attributes(fields, {})) == sorted(
{'username': ''}), 'Should not extract read_only fields on empty serializer'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.